-
Notifications
You must be signed in to change notification settings - Fork 116
/
main.go
3868 lines (3410 loc) · 113 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"context"
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
cryptorand "crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/sha512"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"log"
"log/slog"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"runtime"
"slices"
"strconv"
"strings"
"time"
"golang.org/x/crypto/bcrypt"
"golang.org/x/text/secure/precis"
"github.com/mjl-/adns"
"github.com/mjl-/autocert"
"github.com/mjl-/bstore"
"github.com/mjl-/sconf"
"github.com/mjl-/sherpa"
"github.com/mjl-/mox/admin"
"github.com/mjl-/mox/config"
"github.com/mjl-/mox/dane"
"github.com/mjl-/mox/dkim"
"github.com/mjl-/mox/dmarc"
"github.com/mjl-/mox/dmarcdb"
"github.com/mjl-/mox/dmarcrpt"
"github.com/mjl-/mox/dns"
"github.com/mjl-/mox/dnsbl"
"github.com/mjl-/mox/message"
"github.com/mjl-/mox/mlog"
"github.com/mjl-/mox/mox-"
"github.com/mjl-/mox/moxio"
"github.com/mjl-/mox/moxvar"
"github.com/mjl-/mox/mtasts"
"github.com/mjl-/mox/publicsuffix"
"github.com/mjl-/mox/queue"
"github.com/mjl-/mox/smtp"
"github.com/mjl-/mox/smtpclient"
"github.com/mjl-/mox/spf"
"github.com/mjl-/mox/store"
"github.com/mjl-/mox/tlsrpt"
"github.com/mjl-/mox/tlsrptdb"
"github.com/mjl-/mox/updates"
"github.com/mjl-/mox/webadmin"
"github.com/mjl-/mox/webapi"
)
var (
changelogDomain = "xmox.nl"
changelogURL = "https://updates.xmox.nl/changelog"
changelogPubKey = base64Decode("sPNiTDQzvb4FrytNEiebJhgyQzn57RwEjNbGWMM/bDY=")
)
func base64Decode(s string) []byte {
buf, err := base64.StdEncoding.DecodeString(s)
if err != nil {
panic(err)
}
return buf
}
func envString(k, def string) string {
s := os.Getenv(k)
if s == "" {
return def
}
return s
}
var commands = []struct {
cmd string
fn func(c *cmd)
}{
{"serve", cmdServe},
{"quickstart", cmdQuickstart},
{"stop", cmdStop},
{"setaccountpassword", cmdSetaccountpassword},
{"setadminpassword", cmdSetadminpassword},
{"loglevels", cmdLoglevels},
{"queue holdrules list", cmdQueueHoldrulesList},
{"queue holdrules add", cmdQueueHoldrulesAdd},
{"queue holdrules remove", cmdQueueHoldrulesRemove},
{"queue list", cmdQueueList},
{"queue hold", cmdQueueHold},
{"queue unhold", cmdQueueUnhold},
{"queue schedule", cmdQueueSchedule},
{"queue transport", cmdQueueTransport},
{"queue requiretls", cmdQueueRequireTLS},
{"queue fail", cmdQueueFail},
{"queue drop", cmdQueueDrop},
{"queue dump", cmdQueueDump},
{"queue retired list", cmdQueueRetiredList},
{"queue retired print", cmdQueueRetiredPrint},
{"queue suppress list", cmdQueueSuppressList},
{"queue suppress add", cmdQueueSuppressAdd},
{"queue suppress remove", cmdQueueSuppressRemove},
{"queue suppress lookup", cmdQueueSuppressLookup},
{"queue webhook list", cmdQueueHookList},
{"queue webhook schedule", cmdQueueHookSchedule},
{"queue webhook cancel", cmdQueueHookCancel},
{"queue webhook print", cmdQueueHookPrint},
{"queue webhook retired list", cmdQueueHookRetiredList},
{"queue webhook retired print", cmdQueueHookRetiredPrint},
{"import maildir", cmdImportMaildir},
{"import mbox", cmdImportMbox},
{"export maildir", cmdExportMaildir},
{"export mbox", cmdExportMbox},
{"localserve", cmdLocalserve},
{"help", cmdHelp},
{"backup", cmdBackup},
{"verifydata", cmdVerifydata},
{"licenses", cmdLicenses},
{"config test", cmdConfigTest},
{"config dnscheck", cmdConfigDNSCheck},
{"config dnsrecords", cmdConfigDNSRecords},
{"config describe-domains", cmdConfigDescribeDomains},
{"config describe-static", cmdConfigDescribeStatic},
{"config account add", cmdConfigAccountAdd},
{"config account rm", cmdConfigAccountRemove},
{"config address add", cmdConfigAddressAdd},
{"config address rm", cmdConfigAddressRemove},
{"config domain add", cmdConfigDomainAdd},
{"config domain rm", cmdConfigDomainRemove},
{"config tlspubkey list", cmdConfigTlspubkeyList},
{"config tlspubkey get", cmdConfigTlspubkeyGet},
{"config tlspubkey add", cmdConfigTlspubkeyAdd},
{"config tlspubkey rm", cmdConfigTlspubkeyRemove},
{"config tlspubkey gen", cmdConfigTlspubkeyGen},
{"config alias list", cmdConfigAliasList},
{"config alias print", cmdConfigAliasPrint},
{"config alias add", cmdConfigAliasAdd},
{"config alias update", cmdConfigAliasUpdate},
{"config alias rm", cmdConfigAliasRemove},
{"config alias addaddr", cmdConfigAliasAddaddr},
{"config alias rmaddr", cmdConfigAliasRemoveaddr},
{"config describe-sendmail", cmdConfigDescribeSendmail},
{"config printservice", cmdConfigPrintservice},
{"config ensureacmehostprivatekeys", cmdConfigEnsureACMEHostprivatekeys},
{"config example", cmdConfigExample},
{"checkupdate", cmdCheckupdate},
{"cid", cmdCid},
{"clientconfig", cmdClientConfig},
{"deliver", cmdDeliver},
// todo: turn cmdDANEDialmx into a regular "dialmx" command that follows mta-sts policy, with options to require dane, mta-sts or requiretls. the code will be similar to queue/direct.go
{"dane dial", cmdDANEDial},
{"dane dialmx", cmdDANEDialmx},
{"dane makerecord", cmdDANEMakeRecord},
{"dns lookup", cmdDNSLookup},
{"dkim gened25519", cmdDKIMGened25519},
{"dkim genrsa", cmdDKIMGenrsa},
{"dkim lookup", cmdDKIMLookup},
{"dkim txt", cmdDKIMTXT},
{"dkim verify", cmdDKIMVerify},
{"dkim sign", cmdDKIMSign},
{"dmarc lookup", cmdDMARCLookup},
{"dmarc parsereportmsg", cmdDMARCParsereportmsg},
{"dmarc verify", cmdDMARCVerify},
{"dmarc checkreportaddrs", cmdDMARCCheckreportaddrs},
{"dnsbl check", cmdDNSBLCheck},
{"dnsbl checkhealth", cmdDNSBLCheckhealth},
{"mtasts lookup", cmdMTASTSLookup},
{"retrain", cmdRetrain},
{"sendmail", cmdSendmail},
{"spf check", cmdSPFCheck},
{"spf lookup", cmdSPFLookup},
{"spf parse", cmdSPFParse},
{"tlsrpt lookup", cmdTLSRPTLookup},
{"tlsrpt parsereportmsg", cmdTLSRPTParsereportmsg},
{"version", cmdVersion},
{"webapi", cmdWebapi},
{"example", cmdExample},
{"bumpuidvalidity", cmdBumpUIDValidity},
{"reassignuids", cmdReassignUIDs},
{"fixuidmeta", cmdFixUIDMeta},
{"fixmsgsize", cmdFixmsgsize},
{"reparse", cmdReparse},
{"ensureparsed", cmdEnsureParsed},
{"recalculatemailboxcounts", cmdRecalculateMailboxCounts},
{"message parse", cmdMessageParse},
{"reassignthreads", cmdReassignthreads},
// Not listed.
{"helpall", cmdHelpall},
{"junk analyze", cmdJunkAnalyze},
{"junk check", cmdJunkCheck},
{"junk play", cmdJunkPlay},
{"junk test", cmdJunkTest},
{"junk train", cmdJunkTrain},
{"dmarcdb addreport", cmdDMARCDBAddReport},
{"tlsrptdb addreport", cmdTLSRPTDBAddReport},
{"updates addsigned", cmdUpdatesAddSigned},
{"updates genkey", cmdUpdatesGenkey},
{"updates pubkey", cmdUpdatesPubkey},
{"updates serve", cmdUpdatesServe},
{"updates verify", cmdUpdatesVerify},
{"gentestdata", cmdGentestdata},
{"ximport maildir", cmdXImportMaildir},
{"ximport mbox", cmdXImportMbox},
{"openaccounts", cmdOpenaccounts},
{"readmessages", cmdReadmessages},
{"queuefillretired", cmdQueueFillRetired},
}
var cmds []cmd
func init() {
for _, xc := range commands {
c := cmd{words: strings.Split(xc.cmd, " "), fn: xc.fn}
cmds = append(cmds, c)
}
}
type cmd struct {
words []string
fn func(c *cmd)
// Set before calling command.
flag *flag.FlagSet
flagArgs []string
_gather bool // Set when using Parse to gather usage for a command.
// Set by invoked command or Parse.
unlisted bool // If set, command is not listed until at least some words are matched from command.
params string // Arguments to command. Multiple lines possible.
help string // Additional explanation. First line is synopsis, the rest is only printed for an explicit help/usage for that command.
args []string
log mlog.Log
}
func (c *cmd) Parse() []string {
// To gather params and usage information, we just run the command but cause this
// panic after the command has registered its flags and set its params and help
// information. This is then caught and that info printed.
if c._gather {
panic("gather")
}
c.flag.Usage = c.Usage
c.flag.Parse(c.flagArgs)
c.args = c.flag.Args()
return c.args
}
func (c *cmd) gather() {
c.flag = flag.NewFlagSet("mox "+strings.Join(c.words, " "), flag.ExitOnError)
c._gather = true
defer func() {
x := recover()
// panic generated by Parse.
if x != "gather" {
panic(x)
}
}()
c.fn(c)
}
func (c *cmd) makeUsage() string {
var r strings.Builder
cs := "mox " + strings.Join(c.words, " ")
for i, line := range strings.Split(strings.TrimSpace(c.params), "\n") {
s := ""
if i == 0 {
s = "usage:"
}
if line != "" {
line = " " + line
}
fmt.Fprintf(&r, "%6s %s%s\n", s, cs, line)
}
c.flag.SetOutput(&r)
c.flag.PrintDefaults()
return r.String()
}
func (c *cmd) printUsage() {
fmt.Fprint(os.Stderr, c.makeUsage())
if c.help != "" {
fmt.Fprint(os.Stderr, "\n"+c.help+"\n")
}
}
func (c *cmd) Usage() {
c.printUsage()
os.Exit(2)
}
func cmdHelp(c *cmd) {
c.params = "[command ...]"
c.help = `Prints help about matching commands.
If multiple commands match, they are listed along with the first line of their help text.
If a single command matches, its usage and full help text is printed.
`
args := c.Parse()
if len(args) == 0 {
c.Usage()
}
prefix := func(l, pre []string) bool {
if len(pre) > len(l) {
return false
}
return slices.Equal(pre, l[:len(pre)])
}
var partial []cmd
for _, c := range cmds {
if slices.Equal(c.words, args) {
c.gather()
fmt.Print(c.makeUsage())
if c.help != "" {
fmt.Print("\n" + c.help + "\n")
}
return
} else if prefix(c.words, args) {
partial = append(partial, c)
}
}
if len(partial) == 0 {
fmt.Fprintf(os.Stderr, "%s: unknown command\n", strings.Join(args, " "))
os.Exit(2)
}
for _, c := range partial {
c.gather()
line := "mox " + strings.Join(c.words, " ")
fmt.Printf("%s\n", line)
if c.help != "" {
fmt.Printf("\t%s\n", strings.Split(c.help, "\n")[0])
}
}
}
func cmdHelpall(c *cmd) {
c.unlisted = true
c.help = `Print all detailed usage and help information for all listed commands.
Used to generate documentation.
`
args := c.Parse()
if len(args) != 0 {
c.Usage()
}
n := 0
for _, c := range cmds {
c.gather()
if c.unlisted {
continue
}
if n > 0 {
fmt.Fprintf(os.Stderr, "\n")
}
n++
fmt.Fprintf(os.Stderr, "# mox %s\n\n", strings.Join(c.words, " "))
if c.help != "" {
fmt.Fprintln(os.Stderr, c.help+"\n")
}
s := c.makeUsage()
s = "\t" + strings.ReplaceAll(s, "\n", "\n\t")
fmt.Fprintln(os.Stderr, s)
}
}
func usage(l []cmd, unlisted bool) {
var lines []string
if !unlisted {
lines = append(lines, "mox [-config config/mox.conf] [-pedantic] ...")
}
for _, c := range l {
c.gather()
if c.unlisted && !unlisted {
continue
}
for _, line := range strings.Split(c.params, "\n") {
x := append([]string{"mox"}, c.words...)
if line != "" {
x = append(x, line)
}
lines = append(lines, strings.Join(x, " "))
}
}
for i, line := range lines {
pre := " "
if i == 0 {
pre = "usage: "
}
fmt.Fprintln(os.Stderr, pre+line)
}
os.Exit(2)
}
var loglevel string // Empty will be interpreted as info, except by localserve.
var pedantic bool
// subcommands that are not "serve" should use this function to load the config, it
// restores any loglevel specified on the command-line, instead of using the
// loglevels from the config file and it does not load files like TLS keys/certs.
func mustLoadConfig() {
mox.MustLoadConfig(false, false)
ll := loglevel
if ll == "" {
ll = "info"
}
if level, ok := mlog.Levels[ll]; ok {
mox.Conf.Log[""] = level
mlog.SetConfig(mox.Conf.Log)
} else {
log.Fatal("unknown loglevel", slog.String("loglevel", loglevel))
}
if pedantic {
mox.SetPedantic(true)
}
}
func main() {
// CheckConsistencyOnClose is true by default, for all the test packages. A regular
// mox server should never use it. But integration tests enable it again with a
// flag.
store.CheckConsistencyOnClose = false
ctxbg := context.Background()
mox.Shutdown = ctxbg
mox.Context = ctxbg
log.SetFlags(0)
// If invoked as sendmail, e.g. /usr/sbin/sendmail, we do enough so cron can get a
// message sent using smtp submission to a configured server.
if len(os.Args) > 0 && filepath.Base(os.Args[0]) == "sendmail" {
c := &cmd{
flag: flag.NewFlagSet("sendmail", flag.ExitOnError),
flagArgs: os.Args[1:],
log: mlog.New("sendmail", nil),
}
cmdSendmail(c)
return
}
flag.StringVar(&mox.ConfigStaticPath, "config", envString("MOXCONF", filepath.FromSlash("config/mox.conf")), "configuration file, other config files are looked up in the same directory, defaults to $MOXCONF with a fallback to mox.conf")
flag.StringVar(&loglevel, "loglevel", "", "if non-empty, this log level is set early in startup")
flag.BoolVar(&pedantic, "pedantic", false, "protocol violations result in errors instead of accepting/working around them")
flag.BoolVar(&store.CheckConsistencyOnClose, "checkconsistency", false, "dangerous option for testing only, enables data checks that abort/panic when inconsistencies are found")
var cpuprofile, memprofile, tracefile string
flag.StringVar(&cpuprofile, "cpuprof", "", "store cpu profile to file")
flag.StringVar(&memprofile, "memprof", "", "store mem profile to file")
flag.StringVar(&tracefile, "trace", "", "store execution trace to file")
flag.Usage = func() { usage(cmds, false) }
flag.Parse()
args := flag.Args()
if len(args) == 0 {
usage(cmds, false)
}
if tracefile != "" {
defer traceExecution(tracefile)()
}
defer profile(cpuprofile, memprofile)()
if pedantic {
mox.SetPedantic(true)
}
mox.ConfigDynamicPath = filepath.Join(filepath.Dir(mox.ConfigStaticPath), "domains.conf")
ll := loglevel
if ll == "" {
ll = "info"
}
if level, ok := mlog.Levels[ll]; ok {
mox.Conf.Log[""] = level
mlog.SetConfig(mox.Conf.Log)
// note: SetConfig may be called again when subcommands loads config.
} else {
log.Fatalf("unknown loglevel %q", loglevel)
}
var partial []cmd
next:
for _, c := range cmds {
for i, w := range c.words {
if i >= len(args) || w != args[i] {
if i > 0 {
partial = append(partial, c)
}
continue next
}
}
c.flag = flag.NewFlagSet("mox "+strings.Join(c.words, " "), flag.ExitOnError)
c.flagArgs = args[len(c.words):]
c.log = mlog.New(strings.Join(c.words, ""), nil)
c.fn(&c)
return
}
if len(partial) > 0 {
usage(partial, true)
}
usage(cmds, false)
}
func xcheckf(err error, format string, args ...any) {
if err == nil {
return
}
msg := fmt.Sprintf(format, args...)
log.Fatalf("%s: %s", msg, err)
}
func xparseIP(s, what string) net.IP {
ip := net.ParseIP(s)
if ip == nil {
log.Fatalf("invalid %s: %q", what, s)
}
return ip
}
func xparseDomain(s, what string) dns.Domain {
d, err := dns.ParseDomain(s)
xcheckf(err, "parsing %s %q", what, s)
return d
}
func cmdClientConfig(c *cmd) {
c.params = "domain"
c.help = `Print the configuration for email clients for a domain.
Sending email is typically not done on the SMTP port 25, but on submission
ports 465 (with TLS) and 587 (without initial TLS, but usually added to the
connection with STARTTLS). For IMAP, the port with TLS is 993 and without is
143.
Without TLS/STARTTLS, passwords are sent in clear text, which should only be
configured over otherwise secured connections, like a VPN.
`
args := c.Parse()
if len(args) != 1 {
c.Usage()
}
d := xparseDomain(args[0], "domain")
mustLoadConfig()
printClientConfig(d)
}
func printClientConfig(d dns.Domain) {
cc, err := admin.ClientConfigsDomain(d)
xcheckf(err, "getting client config")
fmt.Printf("%-20s %-30s %5s %-15s %s\n", "Protocol", "Host", "Port", "Listener", "Note")
for _, e := range cc.Entries {
fmt.Printf("%-20s %-30s %5d %-15s %s\n", e.Protocol, e.Host, e.Port, e.Listener, e.Note)
}
fmt.Printf(`
To prevent authentication mechanism downgrade attempts that may result in
clients sending plain text passwords to a MitM, clients should always be
explicitly configured with the most secure authentication mechanism supported,
the first of: SCRAM-SHA-256-PLUS, SCRAM-SHA-1-PLUS, SCRAM-SHA-256, SCRAM-SHA-1,
CRAM-MD5.
`)
}
func cmdConfigTest(c *cmd) {
c.help = `Parses and validates the configuration files.
If valid, the command exits with status 0. If not valid, all errors encountered
are printed.
`
args := c.Parse()
if len(args) != 0 {
c.Usage()
}
mox.FilesImmediate = true
_, errs := mox.ParseConfig(context.Background(), c.log, mox.ConfigStaticPath, true, true, false)
if len(errs) > 1 {
log.Printf("multiple errors:")
for _, err := range errs {
log.Printf("%s", err)
}
os.Exit(1)
} else if len(errs) == 1 {
log.Fatalf("%s", errs[0])
os.Exit(1)
}
fmt.Println("config OK")
}
func cmdConfigDescribeStatic(c *cmd) {
c.params = ">mox.conf"
c.help = `Prints an annotated empty configuration for use as mox.conf.
The static configuration file cannot be reloaded while mox is running. Mox has
to be restarted for changes to the static configuration file to take effect.
This configuration file needs modifications to make it valid. For example, it
may contain unfinished list items.
`
if len(c.Parse()) != 0 {
c.Usage()
}
var sc config.Static
err := sconf.Describe(os.Stdout, &sc)
xcheckf(err, "describing config")
}
func cmdConfigDescribeDomains(c *cmd) {
c.params = ">domains.conf"
c.help = `Prints an annotated empty configuration for use as domains.conf.
The domains configuration file contains the domains and their configuration,
and accounts and their configuration. This includes the configured email
addresses. The mox admin web interface, and the mox command line interface, can
make changes to this file. Mox automatically reloads this file when it changes.
Like the static configuration, the example domains.conf printed by this command
needs modifications to make it valid.
`
if len(c.Parse()) != 0 {
c.Usage()
}
var dc config.Dynamic
err := sconf.Describe(os.Stdout, &dc)
xcheckf(err, "describing config")
}
func cmdConfigPrintservice(c *cmd) {
c.params = ">mox.service"
c.help = `Prints a systemd unit service file for mox.
This is the same file as generated using quickstart. If the systemd service file
has changed with a newer version of mox, use this command to generate an up to
date version.
`
if len(c.Parse()) != 0 {
c.Usage()
}
pwd, err := os.Getwd()
if err != nil {
log.Printf("current working directory: %v", err)
pwd = "/home/mox"
}
service := strings.ReplaceAll(moxService, "/home/mox", pwd)
fmt.Print(service)
}
func cmdConfigDomainAdd(c *cmd) {
c.params = "domain account [localpart]"
c.help = `Adds a new domain to the configuration and reloads the configuration.
The account is used for the postmaster mailboxes the domain, including as DMARC and
TLS reporting. Localpart is the "username" at the domain for this account. If
must be set if and only if account does not yet exist.
`
args := c.Parse()
if len(args) != 2 && len(args) != 3 {
c.Usage()
}
d := xparseDomain(args[0], "domain")
mustLoadConfig()
var localpart smtp.Localpart
if len(args) == 3 {
var err error
localpart, err = smtp.ParseLocalpart(args[2])
xcheckf(err, "parsing localpart")
}
ctlcmdConfigDomainAdd(xctl(), d, args[1], localpart)
}
func ctlcmdConfigDomainAdd(ctl *ctl, domain dns.Domain, account string, localpart smtp.Localpart) {
ctl.xwrite("domainadd")
ctl.xwrite(domain.Name())
ctl.xwrite(account)
ctl.xwrite(string(localpart))
ctl.xreadok()
fmt.Printf("domain added, remember to add dns records, see:\n\nmox config dnsrecords %s\nmox config dnscheck %s\n", domain.Name(), domain.Name())
}
func cmdConfigDomainRemove(c *cmd) {
c.params = "domain"
c.help = `Remove a domain from the configuration and reload the configuration.
This is a dangerous operation. Incoming email delivery for this domain will be
rejected.
`
args := c.Parse()
if len(args) != 1 {
c.Usage()
}
d := xparseDomain(args[0], "domain")
mustLoadConfig()
ctlcmdConfigDomainRemove(xctl(), d)
}
func ctlcmdConfigDomainRemove(ctl *ctl, d dns.Domain) {
ctl.xwrite("domainrm")
ctl.xwrite(d.Name())
ctl.xreadok()
fmt.Printf("domain removed, remember to remove dns records for %s\n", d)
}
func cmdConfigAliasList(c *cmd) {
c.params = "domain"
c.help = `Show aliases (lists) for domain.`
args := c.Parse()
if len(args) != 1 {
c.Usage()
}
mustLoadConfig()
ctlcmdConfigAliasList(xctl(), args[0])
}
func ctlcmdConfigAliasList(ctl *ctl, address string) {
ctl.xwrite("aliaslist")
ctl.xwrite(address)
ctl.xreadok()
ctl.xstreamto(os.Stdout)
}
func cmdConfigAliasPrint(c *cmd) {
c.params = "alias"
c.help = `Print settings and members of alias (list).`
args := c.Parse()
if len(args) != 1 {
c.Usage()
}
mustLoadConfig()
ctlcmdConfigAliasPrint(xctl(), args[0])
}
func ctlcmdConfigAliasPrint(ctl *ctl, address string) {
ctl.xwrite("aliasprint")
ctl.xwrite(address)
ctl.xreadok()
ctl.xstreamto(os.Stdout)
}
func cmdConfigAliasAdd(c *cmd) {
c.params = "alias@domain rcpt1@domain ..."
c.help = `Add new alias (list) with one or more addresses and public posting enabled.
An alias is used for delivering incoming email to multiple recipients. If you
want to add an address to an account, don't use an alias, just add the address
to the account.
`
args := c.Parse()
if len(args) < 2 {
c.Usage()
}
alias := config.Alias{PostPublic: true, Addresses: args[1:]}
mustLoadConfig()
ctlcmdConfigAliasAdd(xctl(), args[0], alias)
}
func ctlcmdConfigAliasAdd(ctl *ctl, address string, alias config.Alias) {
ctl.xwrite("aliasadd")
ctl.xwrite(address)
xctlwriteJSON(ctl, alias)
ctl.xreadok()
}
func cmdConfigAliasUpdate(c *cmd) {
c.params = "alias@domain [-postpublic false|true -listmembers false|true -allowmsgfrom false|true]"
c.help = `Update alias (list) configuration.`
var postpublic, listmembers, allowmsgfrom string
c.flag.StringVar(&postpublic, "postpublic", "", "whether anyone or only list members can post")
c.flag.StringVar(&listmembers, "listmembers", "", "whether list members can list members")
c.flag.StringVar(&allowmsgfrom, "allowmsgfrom", "", "whether alias address can be used in message from header")
args := c.Parse()
if len(args) != 1 {
c.Usage()
}
alias := args[0]
mustLoadConfig()
ctlcmdConfigAliasUpdate(xctl(), alias, postpublic, listmembers, allowmsgfrom)
}
func ctlcmdConfigAliasUpdate(ctl *ctl, alias, postpublic, listmembers, allowmsgfrom string) {
ctl.xwrite("aliasupdate")
ctl.xwrite(alias)
ctl.xwrite(postpublic)
ctl.xwrite(listmembers)
ctl.xwrite(allowmsgfrom)
ctl.xreadok()
}
func cmdConfigAliasRemove(c *cmd) {
c.params = "alias@domain"
c.help = "Remove alias (list)."
args := c.Parse()
if len(args) != 1 {
c.Usage()
}
mustLoadConfig()
ctlcmdConfigAliasRemove(xctl(), args[0])
}
func ctlcmdConfigAliasRemove(ctl *ctl, alias string) {
ctl.xwrite("aliasrm")
ctl.xwrite(alias)
ctl.xreadok()
}
func cmdConfigAliasAddaddr(c *cmd) {
c.params = "alias@domain rcpt1@domain ..."
c.help = `Add addresses to alias (list).`
args := c.Parse()
if len(args) < 2 {
c.Usage()
}
mustLoadConfig()
ctlcmdConfigAliasAddaddr(xctl(), args[0], args[1:])
}
func ctlcmdConfigAliasAddaddr(ctl *ctl, alias string, addresses []string) {
ctl.xwrite("aliasaddaddr")
ctl.xwrite(alias)
xctlwriteJSON(ctl, addresses)
ctl.xreadok()
}
func cmdConfigAliasRemoveaddr(c *cmd) {
c.params = "alias@domain rcpt1@domain ..."
c.help = `Remove addresses from alias (list).`
args := c.Parse()
if len(args) < 2 {
c.Usage()
}
mustLoadConfig()
ctlcmdConfigAliasRmaddr(xctl(), args[0], args[1:])
}
func ctlcmdConfigAliasRmaddr(ctl *ctl, alias string, addresses []string) {
ctl.xwrite("aliasrmaddr")
ctl.xwrite(alias)
xctlwriteJSON(ctl, addresses)
ctl.xreadok()
}
func cmdConfigAccountAdd(c *cmd) {
c.params = "account address"
c.help = `Add an account with an email address and reload the configuration.
Email can be delivered to this address/account. A password has to be configured
explicitly, see the setaccountpassword command.
`
args := c.Parse()
if len(args) != 2 {
c.Usage()
}
mustLoadConfig()
ctlcmdConfigAccountAdd(xctl(), args[0], args[1])
}
func ctlcmdConfigAccountAdd(ctl *ctl, account, address string) {
ctl.xwrite("accountadd")
ctl.xwrite(account)
ctl.xwrite(address)
ctl.xreadok()
fmt.Printf("account added, set a password with \"mox setaccountpassword %s\"\n", account)
}
func cmdConfigAccountRemove(c *cmd) {
c.params = "account"
c.help = `Remove an account and reload the configuration.
Email addresses for this account will also be removed, and incoming email for
these addresses will be rejected.
All data for the account will be removed.
`
args := c.Parse()
if len(args) != 1 {
c.Usage()
}
mustLoadConfig()
ctlcmdConfigAccountRemove(xctl(), args[0])
}
func ctlcmdConfigAccountRemove(ctl *ctl, account string) {
ctl.xwrite("accountrm")
ctl.xwrite(account)
ctl.xreadok()
fmt.Println("account removed")
}
func cmdConfigTlspubkeyList(c *cmd) {
c.params = "[account]"
c.help = `List TLS public keys for TLS client certificate authentication.
If account is absent, the TLS public keys for all accounts are listed.
`
args := c.Parse()
var accountOpt string
if len(args) == 1 {
accountOpt = args[0]
} else if len(args) > 1 {
c.Usage()
}
mustLoadConfig()
ctlcmdConfigTlspubkeyList(xctl(), accountOpt)
}
func ctlcmdConfigTlspubkeyList(ctl *ctl, accountOpt string) {
ctl.xwrite("tlspubkeylist")
ctl.xwrite(accountOpt)
ctl.xreadok()
ctl.xstreamto(os.Stdout)
}
func cmdConfigTlspubkeyGet(c *cmd) {
c.params = "fingerprint"
c.help = `Get a TLS public key for a fingerprint.
Prints the type, name, account and address for the key, and the certificate in
PEM format.
`
args := c.Parse()
if len(args) != 1 {
c.Usage()
}
mustLoadConfig()
ctlcmdConfigTlspubkeyGet(xctl(), args[0])
}
func ctlcmdConfigTlspubkeyGet(ctl *ctl, fingerprint string) {
ctl.xwrite("tlspubkeyget")
ctl.xwrite(fingerprint)
ctl.xreadok()
typ := ctl.xread()
name := ctl.xread()
account := ctl.xread()
address := ctl.xread()
noimappreauth := ctl.xread()
var b bytes.Buffer
ctl.xstreamto(&b)
buf := b.Bytes()
var block *pem.Block
if len(buf) != 0 {
block = &pem.Block{
Type: "CERTIFICATE",
Bytes: buf,
}
}
fmt.Printf("type: %s\nname: %s\naccount: %s\naddress: %s\nno imap preauth: %s\n", typ, name, account, address, noimappreauth)
if block != nil {
fmt.Printf("certificate:\n\n")
pem.Encode(os.Stdout, block)
}
}