23 "github.com/mjl-/bstore"
25 "github.com/mjl-/mox/admin"
26 "github.com/mjl-/mox/config"
27 "github.com/mjl-/mox/dns"
28 "github.com/mjl-/mox/message"
29 "github.com/mjl-/mox/metrics"
30 "github.com/mjl-/mox/mlog"
31 "github.com/mjl-/mox/mox-"
32 "github.com/mjl-/mox/queue"
33 "github.com/mjl-/mox/smtp"
34 "github.com/mjl-/mox/store"
35 "github.com/mjl-/mox/webapi"
38// ctl represents a connection to the ctl unix domain socket of a running mox instance.
39// ctl provides functions to read/write commands/responses/data streams.
41 cmd string // Set for server-side of commands.
43 r *bufio.Reader // Set for first reader.
44 x any // If set, errors are handled by calling panic(x) instead of log.Fatal.
45 log mlog.Log // If set, along with x, logging is done here.
48// xctl opens a ctl connection.
50 p := mox.DataDirPath("ctl")
51 conn, err := net.Dial("unix", p)
53 log.Fatalf("connecting to control socket at %q: %v", p, err)
55 ctl := &ctl{conn: conn}
56 version := ctl.xread()
57 if version != "ctlv0" {
58 log.Fatalf("ctl protocol mismatch, got %q, expected ctlv0", version)
63// Interpret msg as an error.
64// If ctl.x is set, the string is also written to the ctl to be interpreted as error by the other party.
65func (c *ctl) xerror(msg string) {
69 c.log.Debugx("ctl error", fmt.Errorf("%s", msg), slog.String("cmd", c.cmd))
74// Check if err is not nil. If so, handle error through ctl.x or log.Fatal. If
75// ctl.x is set, the error string is written to ctl, to be interpreted as an error
76// by the command reading from ctl.
77func (c *ctl) xcheck(err error, msg string) {
82 log.Fatalf("%s: %s", msg, err)
84 c.log.Debugx(msg, err, slog.String("cmd", c.cmd))
85 fmt.Fprintf(c.conn, "%s: %s\n", msg, err)
89// Read a line and return it without trailing newline.
90func (c *ctl) xread() string {
92 c.r = bufio.NewReader(c.conn)
94 line, err := c.r.ReadString('\n')
95 c.xcheck(err, "read from ctl")
96 return strings.TrimSuffix(line, "\n")
99// Read a line. If not "ok", the string is interpreted as an error.
100func (c *ctl) xreadok() {
107// Write a string, typically a command or parameter.
108func (c *ctl) xwrite(text string) {
109 _, err := fmt.Fprintln(c.conn, text)
110 c.xcheck(err, "write")
113// Write "ok" to indicate success.
114func (c *ctl) xwriteok() {
118// Copy data from a stream from ctl to dst.
119func (c *ctl) xstreamto(dst io.Writer) {
120 _, err := io.Copy(dst, c.reader())
121 c.xcheck(err, "reading message")
124// Copy data from src to a stream to ctl.
125func (c *ctl) xstreamfrom(src io.Reader) {
127 _, err := io.Copy(w, src)
128 c.xcheck(err, "copying")
132// Writer returns an io.Writer for a data stream to ctl.
133// When done writing, caller must call xclose to signal the end of the stream.
134// Behaviour of "x" is copied from ctl.
135func (c *ctl) writer() *ctlwriter {
136 return &ctlwriter{cmd: c.cmd, conn: c.conn, x: c.x, log: c.log}
139// Reader returns an io.Reader for a data stream from ctl.
140// Behaviour of "x" is copied from ctl.
141func (c *ctl) reader() *ctlreader {
143 c.r = bufio.NewReader(c.conn)
145 return &ctlreader{cmd: c.cmd, conn: c.conn, r: c.r, x: c.x, log: c.log}
149Ctlwriter and ctlreader implement the writing and reading a data stream. They
150implement the io.Writer and io.Reader interface. In the protocol below each
151non-data message ends with a newline that is typically stripped when
154Zero or more data transactions:
156 > "123" (for data size) or an error message
158 < "ok" or an error message
160Followed by a end of stream indicated by zero data bytes message:
165type ctlwriter struct {
166 cmd string // Set for server-side of commands.
167 conn net.Conn // Ctl socket from which messages are read.
168 buf []byte // Scratch buffer, for reading response.
169 x any // If not nil, errors in Write and xcheckf are handled with panic(x), otherwise with a log.Fatal.
173func (s *ctlwriter) Write(buf []byte) (int, error) {
174 _, err := fmt.Fprintf(s.conn, "%d\n", len(buf))
175 s.xcheck(err, "write count")
176 _, err = s.conn.Write(buf)
177 s.xcheck(err, "write data")
179 s.buf = make([]byte, 512)
181 n, err := s.conn.Read(s.buf)
182 s.xcheck(err, "reading response to write")
183 line := strings.TrimSuffix(string(s.buf[:n]), "\n")
190func (s *ctlwriter) xerror(msg string) {
194 s.log.Debugx("error", fmt.Errorf("%s", msg), slog.String("cmd", s.cmd))
199func (s *ctlwriter) xcheck(err error, msg string) {
204 log.Fatalf("%s: %s", msg, err)
206 s.log.Debugx(msg, err, slog.String("cmd", s.cmd))
211func (s *ctlwriter) xclose() {
212 _, err := fmt.Fprintf(s.conn, "0\n")
213 s.xcheck(err, "write eof")
216type ctlreader struct {
217 cmd string // Set for server-side of command.
218 conn net.Conn // For writing "ok" after reading.
219 r *bufio.Reader // Buffered ctl socket.
220 err error // If set, returned for each read. can also be io.EOF.
221 npending int // Number of bytes that can still be read until a new count line must be read.
222 x any // If set, errors are handled with panic(x) instead of log.Fatal.
223 log mlog.Log // If x is set, logging goes to log.
226func (s *ctlreader) Read(buf []byte) (N int, Err error) {
231 line, err := s.r.ReadString('\n')
232 s.xcheck(err, "reading count")
233 line = strings.TrimSuffix(line, "\n")
234 n, err := strconv.ParseInt(line, 10, 32)
248 n, err := s.r.Read(buf[:rn])
249 s.xcheck(err, "read from ctl")
252 _, err = fmt.Fprintln(s.conn, "ok")
253 s.xcheck(err, "writing ok after reading")
258func (s *ctlreader) xerror(msg string) {
262 s.log.Debugx("error", fmt.Errorf("%s", msg), slog.String("cmd", s.cmd))
267func (s *ctlreader) xcheck(err error, msg string) {
272 log.Fatalf("%s: %s", msg, err)
274 s.log.Debugx(msg, err, slog.String("cmd", s.cmd))
279// servectl handles requests on the unix domain socket "ctl", e.g. for graceful shutdown, local mail delivery.
280func servectl(ctx context.Context, log mlog.Log, conn net.Conn, shutdown func()) {
281 log.Debug("ctl connection")
283 var stop = struct{}{} // Sentinel value for panic and recover.
284 ctl := &ctl{conn: conn, x: stop, log: log}
287 if x == nil || x == stop {
290 log.Error("servectl panic", slog.Any("err", x), slog.String("cmd", ctl.cmd))
292 metrics.PanicInc(metrics.Ctl)
299 servectlcmd(ctx, ctl, shutdown)
303func xparseJSON(ctl *ctl, s string, v any) {
304 dec := json.NewDecoder(strings.NewReader(s))
305 dec.DisallowUnknownFields()
307 ctl.xcheck(err, "parsing from ctl as json")
310func servectlcmd(ctx context.Context, ctl *ctl, shutdown func()) {
314 log.Info("ctl command", slog.String("cmd", cmd))
321 /* The protocol, double quoted are literals.
331 a, addr, err := store.OpenEmail(log, to)
332 ctl.xcheck(err, "lookup destination address")
334 msgFile, err := store.CreateMessageTemp(log, "ctl-deliver")
335 ctl.xcheck(err, "creating temporary message file")
336 defer store.CloseRemoveTempFile(log, msgFile, "deliver message")
337 mw := message.NewWriter(msgFile)
342 ctl.xcheck(err, "syncing message to storage")
345 Received: time.Now(),
350 err := a.DeliverDestination(log, addr, &m, msgFile)
351 ctl.xcheck(err, "delivering message")
352 log.Info("message delivered through ctl", slog.Any("to", to))
356 ctl.xcheck(err, "closing account")
359 case "setaccountpassword":
361 > "setaccountpassword"
367 account := ctl.xread()
370 acc, err := store.OpenAccount(log, account)
371 ctl.xcheck(err, "open account")
375 log.Check(err, "closing account after setting password")
379 err = acc.SetPassword(log, pw)
380 ctl.xcheck(err, "setting password")
382 ctl.xcheck(err, "closing account")
386 case "queueholdruleslist":
388 > "queueholdruleslist"
392 l, err := queue.HoldRuleList(ctx)
393 ctl.xcheck(err, "listing hold rules")
396 fmt.Fprintln(xw, "hold rules:")
397 for _, hr := range l {
399 if hr.Account != "" {
400 elems = append(elems, fmt.Sprintf("account %q", hr.Account))
402 var zerodom dns.Domain
403 if hr.SenderDomain != zerodom {
404 elems = append(elems, fmt.Sprintf("sender domain %q", hr.SenderDomain.Name()))
406 if hr.RecipientDomain != zerodom {
407 elems = append(elems, fmt.Sprintf("sender domain %q", hr.RecipientDomain.Name()))
410 fmt.Fprintf(xw, "id %d: all messages\n", hr.ID)
412 fmt.Fprintf(xw, "id %d: %s\n", hr.ID, strings.Join(elems, ", "))
416 fmt.Fprint(xw, "(none)\n")
420 case "queueholdrulesadd":
422 > "queueholdrulesadd"
428 var hr queue.HoldRule
429 hr.Account = ctl.xread()
430 senderdomstr := ctl.xread()
431 rcptdomstr := ctl.xread()
433 hr.SenderDomain, err = dns.ParseDomain(senderdomstr)
434 ctl.xcheck(err, "parsing sender domain")
435 hr.RecipientDomain, err = dns.ParseDomain(rcptdomstr)
436 ctl.xcheck(err, "parsing recipient domain")
437 hr, err = queue.HoldRuleAdd(ctx, log, hr)
438 ctl.xcheck(err, "add hold rule")
441 case "queueholdrulesremove":
443 > "queueholdrulesremove"
448 id, err := strconv.ParseInt(idstr, 10, 64)
449 ctl.xcheck(err, "parsing id")
450 err = queue.HoldRuleRemove(ctx, log, id)
451 ctl.xcheck(err, "remove hold rule")
462 filterline := ctl.xread()
463 sortline := ctl.xread()
465 xparseJSON(ctl, filterline, &f)
467 xparseJSON(ctl, sortline, &s)
468 qmsgs, err := queue.List(ctx, f, s)
469 ctl.xcheck(err, "listing queue")
473 fmt.Fprintln(xw, "messages:")
474 for _, qm := range qmsgs {
475 var lastAttempt string
476 if qm.LastAttempt != nil {
477 lastAttempt = time.Since(*qm.LastAttempt).Round(time.Second).String()
479 fmt.Fprintf(xw, "%5d %s from:%s to:%s next %s last %s error %q\n", qm.ID, qm.Queued.Format(time.RFC3339), qm.Sender().LogString(), qm.Recipient().LogString(), -time.Since(qm.NextAttempt).Round(time.Second), lastAttempt, qm.LastResult().Error)
482 fmt.Fprint(xw, "(none)\n")
489 > queuefilters as json
495 filterline := ctl.xread()
496 hold := ctl.xread() == "true"
498 xparseJSON(ctl, filterline, &f)
499 count, err := queue.HoldSet(ctx, f, hold)
500 ctl.xcheck(err, "setting on hold status for messages")
502 ctl.xwrite(fmt.Sprintf("%d", count))
504 case "queueschedule":
507 > queuefilters as json
514 filterline := ctl.xread()
515 relnow := ctl.xread()
516 duration := ctl.xread()
518 xparseJSON(ctl, filterline, &f)
519 d, err := time.ParseDuration(duration)
520 ctl.xcheck(err, "parsing duration for next delivery attempt")
523 count, err = queue.NextAttemptAdd(ctx, f, d)
525 count, err = queue.NextAttemptSet(ctx, f, time.Now().Add(d))
527 ctl.xcheck(err, "setting next delivery attempts in queue")
529 ctl.xwrite(fmt.Sprintf("%d", count))
531 case "queuetransport":
534 > queuefilters as json
540 filterline := ctl.xread()
541 transport := ctl.xread()
543 xparseJSON(ctl, filterline, &f)
544 count, err := queue.TransportSet(ctx, f, transport)
545 ctl.xcheck(err, "adding to next delivery attempts in queue")
547 ctl.xwrite(fmt.Sprintf("%d", count))
549 case "queuerequiretls":
552 > queuefilters as json
553 > reqtls (empty string, "true" or "false")
558 filterline := ctl.xread()
559 reqtls := ctl.xread()
570 ctl.xcheck(fmt.Errorf("unknown value %q", reqtls), "parsing value")
573 xparseJSON(ctl, filterline, &f)
574 count, err := queue.RequireTLSSet(ctx, f, req)
575 ctl.xcheck(err, "setting tls requirements on messages in queue")
577 ctl.xwrite(fmt.Sprintf("%d", count))
582 > queuefilters as json
587 filterline := ctl.xread()
589 xparseJSON(ctl, filterline, &f)
590 count, err := queue.Fail(ctx, log, f)
591 ctl.xcheck(err, "marking messages from queue as failed")
593 ctl.xwrite(fmt.Sprintf("%d", count))
598 > queuefilters as json
603 filterline := ctl.xread()
605 xparseJSON(ctl, filterline, &f)
606 count, err := queue.Drop(ctx, log, f)
607 ctl.xcheck(err, "dropping messages from queue")
609 ctl.xwrite(fmt.Sprintf("%d", count))
620 id, err := strconv.ParseInt(idstr, 10, 64)
622 ctl.xcheck(err, "parsing id")
624 mr, err := queue.OpenMessage(ctx, id)
625 ctl.xcheck(err, "opening message")
628 log.Check(err, "closing message from queue")
633 case "queueretiredlist":
641 filterline := ctl.xread()
642 sortline := ctl.xread()
643 var f queue.RetiredFilter
644 xparseJSON(ctl, filterline, &f)
645 var s queue.RetiredSort
646 xparseJSON(ctl, sortline, &s)
647 qmsgs, err := queue.RetiredList(ctx, f, s)
648 ctl.xcheck(err, "listing retired queue")
652 fmt.Fprintln(xw, "retired messages:")
653 for _, qm := range qmsgs {
654 var lastAttempt string
655 if qm.LastAttempt != nil {
656 lastAttempt = time.Since(*qm.LastAttempt).Round(time.Second).String()
662 sender, err := qm.Sender()
663 xcheckf(err, "parsing sender")
664 fmt.Fprintf(xw, "%5d %s %s from:%s to:%s last %s error %q\n", qm.ID, qm.Queued.Format(time.RFC3339), result, sender.LogString(), qm.Recipient().LogString(), lastAttempt, qm.LastResult().Error)
667 fmt.Fprint(xw, "(none)\n")
671 case "queueretiredprint":
673 > "queueretiredprint"
679 id, err := strconv.ParseInt(idstr, 10, 64)
681 ctl.xcheck(err, "parsing id")
683 l, err := queue.RetiredList(ctx, queue.RetiredFilter{IDs: []int64{id}}, queue.RetiredSort{})
684 ctl.xcheck(err, "getting retired messages")
686 ctl.xcheck(errors.New("not found"), "getting retired message")
691 enc := json.NewEncoder(xw)
692 enc.SetIndent("", "\t")
694 ctl.xcheck(err, "encode retired message")
697 case "queuehooklist":
705 filterline := ctl.xread()
706 sortline := ctl.xread()
707 var f queue.HookFilter
708 xparseJSON(ctl, filterline, &f)
710 xparseJSON(ctl, sortline, &s)
711 hooks, err := queue.HookList(ctx, f, s)
712 ctl.xcheck(err, "listing webhooks")
716 fmt.Fprintln(xw, "webhooks:")
717 for _, h := range hooks {
718 var lastAttempt string
719 if len(h.Results) > 0 {
720 lastAttempt = time.Since(h.LastResult().Start).Round(time.Second).String()
722 fmt.Fprintf(xw, "%5d %s account:%s next %s last %s error %q url %s\n", h.ID, h.Submitted.Format(time.RFC3339), h.Account, time.Until(h.NextAttempt).Round(time.Second), lastAttempt, h.LastResult().Error, h.URL)
725 fmt.Fprint(xw, "(none)\n")
729 case "queuehookschedule":
731 > "queuehookschedule"
732 > hookfilters as json
739 filterline := ctl.xread()
740 relnow := ctl.xread()
741 duration := ctl.xread()
742 var f queue.HookFilter
743 xparseJSON(ctl, filterline, &f)
744 d, err := time.ParseDuration(duration)
745 ctl.xcheck(err, "parsing duration for next delivery attempt")
748 count, err = queue.HookNextAttemptAdd(ctx, f, d)
750 count, err = queue.HookNextAttemptSet(ctx, f, time.Now().Add(d))
752 ctl.xcheck(err, "setting next delivery attempts in queue")
754 ctl.xwrite(fmt.Sprintf("%d", count))
756 case "queuehookcancel":
759 > hookfilters as json
764 filterline := ctl.xread()
765 var f queue.HookFilter
766 xparseJSON(ctl, filterline, &f)
767 count, err := queue.HookCancel(ctx, log, f)
768 ctl.xcheck(err, "canceling webhooks in queue")
770 ctl.xwrite(fmt.Sprintf("%d", count))
772 case "queuehookprint":
780 id, err := strconv.ParseInt(idstr, 10, 64)
782 ctl.xcheck(err, "parsing id")
784 l, err := queue.HookList(ctx, queue.HookFilter{IDs: []int64{id}}, queue.HookSort{})
785 ctl.xcheck(err, "getting webhooks")
787 ctl.xcheck(errors.New("not found"), "getting webhook")
792 enc := json.NewEncoder(xw)
793 enc.SetIndent("", "\t")
795 ctl.xcheck(err, "encode webhook")
798 case "queuehookretiredlist":
800 > "queuehookretiredlist"
806 filterline := ctl.xread()
807 sortline := ctl.xread()
808 var f queue.HookRetiredFilter
809 xparseJSON(ctl, filterline, &f)
810 var s queue.HookRetiredSort
811 xparseJSON(ctl, sortline, &s)
812 l, err := queue.HookRetiredList(ctx, f, s)
813 ctl.xcheck(err, "listing retired webhooks")
817 fmt.Fprintln(xw, "retired webhooks:")
818 for _, h := range l {
819 var lastAttempt string
820 if len(h.Results) > 0 {
821 lastAttempt = time.Since(h.LastResult().Start).Round(time.Second).String()
827 fmt.Fprintf(xw, "%5d %s %s account:%s last %s error %q url %s\n", h.ID, h.Submitted.Format(time.RFC3339), result, h.Account, lastAttempt, h.LastResult().Error, h.URL)
830 fmt.Fprint(xw, "(none)\n")
834 case "queuehookretiredprint":
836 > "queuehookretiredprint"
842 id, err := strconv.ParseInt(idstr, 10, 64)
844 ctl.xcheck(err, "parsing id")
846 l, err := queue.HookRetiredList(ctx, queue.HookRetiredFilter{IDs: []int64{id}}, queue.HookRetiredSort{})
847 ctl.xcheck(err, "getting retired webhooks")
849 ctl.xcheck(errors.New("not found"), "getting retired webhook")
854 enc := json.NewEncoder(xw)
855 enc.SetIndent("", "\t")
857 ctl.xcheck(err, "encode retired webhook")
860 case "queuesuppresslist":
862 > "queuesuppresslist"
868 account := ctl.xread()
869 l, err := queue.SuppressionList(ctx, account)
870 ctl.xcheck(err, "listing suppressions")
873 fmt.Fprintln(xw, "suppressions (account, address, manual, time added, base adddress, reason):")
874 for _, sup := range l {
879 fmt.Fprintf(xw, "%q\t%q\t%s\t%s\t%q\t%q\n", sup.Account, sup.OriginalAddress, manual, sup.Created.Round(time.Second), sup.BaseAddress, sup.Reason)
882 fmt.Fprintln(xw, "(none)")
886 case "queuesuppressadd":
894 account := ctl.xread()
895 address := ctl.xread()
896 _, ok := mox.Conf.Account(account)
898 ctl.xcheck(errors.New("unknown account"), "looking up account")
900 addr, err := smtp.ParseAddress(address)
901 ctl.xcheck(err, "parsing address")
902 sup := webapi.Suppression{
905 Reason: "added through mox cli",
907 err = queue.SuppressionAdd(ctx, addr.Path(), &sup)
908 ctl.xcheck(err, "adding suppression")
911 case "queuesuppressremove":
913 > "queuesuppressremove"
919 account := ctl.xread()
920 address := ctl.xread()
921 addr, err := smtp.ParseAddress(address)
922 ctl.xcheck(err, "parsing address")
923 err = queue.SuppressionRemove(ctx, account, addr.Path())
924 ctl.xcheck(err, "removing suppression")
927 case "queuesuppresslookup":
929 > "queuesuppresslookup"
936 account := ctl.xread()
937 address := ctl.xread()
939 _, ok := mox.Conf.Account(account)
941 ctl.xcheck(errors.New("unknown account"), "looking up account")
944 addr, err := smtp.ParseAddress(address)
945 ctl.xcheck(err, "parsing address")
946 sup, err := queue.SuppressionLookup(ctx, account, addr.Path())
947 ctl.xcheck(err, "looking up suppression")
951 fmt.Fprintln(xw, "not present")
957 fmt.Fprintf(xw, "present\nadded: %s\nmanual: %s\nbase address: %s\nreason: %q\n", sup.Created.Round(time.Second), manual, sup.BaseAddress, sup.Reason)
961 case "importmaildir", "importmbox":
962 mbox := cmd == "importmbox"
963 importctl(ctx, ctl, mbox)
973 domain := ctl.xread()
974 account := ctl.xread()
975 localpart := ctl.xread()
976 d, err := dns.ParseDomain(domain)
977 ctl.xcheck(err, "parsing domain")
978 err = admin.DomainAdd(ctx, d, account, smtp.Localpart(localpart))
979 ctl.xcheck(err, "adding domain")
988 domain := ctl.xread()
989 d, err := dns.ParseDomain(domain)
990 ctl.xcheck(err, "parsing domain")
991 err = admin.DomainRemove(ctx, d)
992 ctl.xcheck(err, "removing domain")
1002 account := ctl.xread()
1003 address := ctl.xread()
1004 err := admin.AccountAdd(ctx, account, address)
1005 ctl.xcheck(err, "adding account")
1014 account := ctl.xread()
1015 err := admin.AccountRemove(ctx, account)
1016 ctl.xcheck(err, "removing account")
1019 case "tlspubkeylist":
1022 > account (or empty)
1026 accountOpt := ctl.xread()
1027 tlspubkeys, err := store.TLSPublicKeyList(ctx, accountOpt)
1028 ctl.xcheck(err, "list tls public keys")
1031 fmt.Fprintf(xw, "# fingerprint, type, name, account, login address, no imap preauth (%d)\n", len(tlspubkeys))
1032 for _, k := range tlspubkeys {
1033 fmt.Fprintf(xw, "%s\t%s\t%q\t%s\t%s\t%v\n", k.Fingerprint, k.Type, k.Name, k.Account, k.LoginAddress, k.NoIMAPPreauth)
1037 case "tlspubkeyget":
1046 < noimappreauth (true/false)
1050 tlspubkey, err := store.TLSPublicKeyGet(ctx, fp)
1051 ctl.xcheck(err, "looking tls public key")
1053 ctl.xwrite(tlspubkey.Type)
1054 ctl.xwrite(tlspubkey.Name)
1055 ctl.xwrite(tlspubkey.Account)
1056 ctl.xwrite(tlspubkey.LoginAddress)
1057 ctl.xwrite(fmt.Sprintf("%v", tlspubkey.NoIMAPPreauth))
1058 ctl.xstreamfrom(bytes.NewReader(tlspubkey.CertDER))
1060 case "tlspubkeyadd":
1065 > noimappreauth (true/false)
1069 loginAddress := ctl.xread()
1071 noimappreauth := ctl.xread()
1072 if noimappreauth != "true" && noimappreauth != "false" {
1073 ctl.xcheck(fmt.Errorf("bad value %q", noimappreauth), "parsing noimappreauth")
1077 tlspubkey, err := store.ParseTLSPublicKeyCert(b.Bytes())
1078 ctl.xcheck(err, "parsing certificate")
1080 tlspubkey.Name = name
1082 acc, _, err := store.OpenEmail(ctl.log, loginAddress)
1083 ctl.xcheck(err, "open account for address")
1086 ctl.log.Check(err, "close account")
1088 tlspubkey.Account = acc.Name
1089 tlspubkey.LoginAddress = loginAddress
1090 tlspubkey.NoIMAPPreauth = noimappreauth == "true"
1092 err = store.TLSPublicKeyAdd(ctx, &tlspubkey)
1093 ctl.xcheck(err, "adding tls public key")
1103 err := store.TLSPublicKeyRemove(ctx, fp)
1104 ctl.xcheck(err, "removing tls public key")
1114 address := ctl.xread()
1115 account := ctl.xread()
1116 err := admin.AddressAdd(ctx, address, account)
1117 ctl.xcheck(err, "adding address")
1126 address := ctl.xread()
1127 err := admin.AddressRemove(ctx, address)
1128 ctl.xcheck(err, "removing address")
1138 domain := ctl.xread()
1139 d, err := dns.ParseDomain(domain)
1140 ctl.xcheck(err, "parsing domain")
1141 dc, ok := mox.Conf.Domain(d)
1143 ctl.xcheck(errors.New("no such domain"), "listing aliases")
1147 for _, a := range dc.Aliases {
1148 lp, err := smtp.ParseLocalpart(a.LocalpartStr)
1149 ctl.xcheck(err, "parsing alias localpart")
1150 fmt.Fprintln(w, smtp.NewAddress(lp, a.Domain).Pack(true))
1161 address := ctl.xread()
1162 _, alias, ok := mox.Conf.AccountDestination(address)
1164 ctl.xcheck(errors.New("no such address"), "looking up alias")
1165 } else if alias == nil {
1166 ctl.xcheck(errors.New("address not an alias"), "looking up alias")
1170 fmt.Fprintf(w, "# postpublic %v\n", alias.PostPublic)
1171 fmt.Fprintf(w, "# listmembers %v\n", alias.ListMembers)
1172 fmt.Fprintf(w, "# allowmsgfrom %v\n", alias.AllowMsgFrom)
1173 fmt.Fprintln(w, "# members:")
1174 for _, a := range alias.Addresses {
1186 address := ctl.xread()
1188 addr, err := smtp.ParseAddress(address)
1189 ctl.xcheck(err, "parsing address")
1190 var alias config.Alias
1191 xparseJSON(ctl, line, &alias)
1192 err = admin.AliasAdd(ctx, addr, alias)
1193 ctl.xcheck(err, "adding alias")
1200 > "true" or "false" for postpublic
1201 > "true" or "false" for listmembers
1202 > "true" or "false" for allowmsgfrom
1205 address := ctl.xread()
1206 postpublic := ctl.xread()
1207 listmembers := ctl.xread()
1208 allowmsgfrom := ctl.xread()
1209 addr, err := smtp.ParseAddress(address)
1210 ctl.xcheck(err, "parsing address")
1211 err = admin.DomainSave(ctx, addr.Domain.Name(), func(d *config.Domain) error {
1212 a, ok := d.Aliases[addr.Localpart.String()]
1214 return fmt.Errorf("alias does not exist")
1219 a.PostPublic = false
1223 switch listmembers {
1225 a.ListMembers = false
1227 a.ListMembers = true
1229 switch allowmsgfrom {
1231 a.AllowMsgFrom = false
1233 a.AllowMsgFrom = true
1236 d.Aliases = maps.Clone(d.Aliases)
1237 d.Aliases[addr.Localpart.String()] = a
1240 ctl.xcheck(err, "saving alias")
1249 address := ctl.xread()
1250 addr, err := smtp.ParseAddress(address)
1251 ctl.xcheck(err, "parsing address")
1252 err = admin.AliasRemove(ctx, addr)
1253 ctl.xcheck(err, "removing alias")
1256 case "aliasaddaddr":
1263 address := ctl.xread()
1265 addr, err := smtp.ParseAddress(address)
1266 ctl.xcheck(err, "parsing address")
1267 var addresses []string
1268 xparseJSON(ctl, line, &addresses)
1269 err = admin.AliasAddressesAdd(ctx, addr, addresses)
1270 ctl.xcheck(err, "adding addresses to alias")
1280 address := ctl.xread()
1282 addr, err := smtp.ParseAddress(address)
1283 ctl.xcheck(err, "parsing address")
1284 var addresses []string
1285 xparseJSON(ctl, line, &addresses)
1286 err = admin.AliasAddressesRemove(ctx, addr, addresses)
1287 ctl.xcheck(err, "removing addresses to alias")
1297 l := mox.Conf.LogLevels()
1300 keys = append(keys, k)
1302 sort.Slice(keys, func(i, j int) bool {
1303 return keys[i] < keys[j]
1306 for _, k := range keys {
1311 s += ks + ": " + mlog.LevelStrings[l[k]] + "\n"
1313 ctl.xstreamfrom(strings.NewReader(s))
1315 case "setloglevels":
1319 > level (if empty, log level for pkg will be unset)
1323 levelstr := ctl.xread()
1325 mox.Conf.LogLevelRemove(log, pkg)
1327 level, ok := mlog.Levels[levelstr]
1329 ctl.xerror("bad level")
1331 mox.Conf.LogLevelSet(log, pkg, level)
1341 account := ctl.xread()
1343 xretrain := func(name string) {
1344 acc, err := store.OpenAccount(log, name)
1345 ctl.xcheck(err, "open account")
1349 log.Check(err, "closing account after retraining")
1353 // todo: can we retrain an account without holding a write lock? perhaps by writing a junkfilter to a new location, and staying informed of message changes while we go through all messages in the account?
1355 acc.WithWLock(func() {
1356 conf, _ := acc.Conf()
1357 if conf.JunkFilter == nil {
1358 ctl.xcheck(store.ErrNoJunkFilter, "looking for junk filter")
1361 // Remove existing junk filter files.
1362 basePath := mox.DataDirPath("accounts")
1363 dbPath := filepath.Join(basePath, acc.Name, "junkfilter.db")
1364 bloomPath := filepath.Join(basePath, acc.Name, "junkfilter.bloom")
1365 err := os.Remove(dbPath)
1366 log.Check(err, "removing old junkfilter database file", slog.String("path", dbPath))
1367 err = os.Remove(bloomPath)
1368 log.Check(err, "removing old junkfilter bloom filter file", slog.String("path", bloomPath))
1370 // Open junk filter, this creates new files.
1371 jf, _, err := acc.OpenJunkFilter(ctx, log)
1372 ctl.xcheck(err, "open new junk filter")
1378 log.Check(err, "closing junk filter during cleanup")
1381 // Read through messages with junk or nonjunk flag set, and train them.
1382 var total, trained int
1383 q := bstore.QueryDB[store.Message](ctx, acc.DB)
1384 q.FilterEqual("Expunged", false)
1385 err = q.ForEach(func(m store.Message) error {
1387 ok, err := acc.TrainMessage(ctx, log, jf, m)
1393 ctl.xcheck(err, "training messages")
1394 log.Info("retrained messages", slog.Int("total", total), slog.Int("trained", trained))
1396 // Close junk filter, marking success.
1399 ctl.xcheck(err, "closing junk filter")
1404 for _, name := range mox.Conf.Accounts() {
1412 case "recalculatemailboxcounts":
1414 > "recalculatemailboxcounts"
1419 account := ctl.xread()
1420 acc, err := store.OpenAccount(log, account)
1421 ctl.xcheck(err, "open account")
1425 log.Check(err, "closing account after recalculating mailbox counts")
1432 acc.WithWLock(func() {
1433 var changes []store.Change
1434 err = acc.DB.Write(ctx, func(tx *bstore.Tx) error {
1436 err := bstore.QueryTx[store.Mailbox](tx).ForEach(func(mb store.Mailbox) error {
1437 mc, err := mb.CalculateCounts(tx)
1439 return fmt.Errorf("calculating counts for mailbox %q: %w", mb.Name, err)
1441 totalSize += mc.Size
1443 if !mb.HaveCounts || mc != mb.MailboxCounts {
1444 _, err := fmt.Fprintf(w, "for %s setting new counts %s (was %s)\n", mb.Name, mc, mb.MailboxCounts)
1445 ctl.xcheck(err, "write")
1446 mb.HaveCounts = true
1447 mb.MailboxCounts = mc
1448 if err := tx.Update(&mb); err != nil {
1449 return fmt.Errorf("storing new counts for %q: %v", mb.Name, err)
1451 changes = append(changes, mb.ChangeCounts())
1459 du := store.DiskUsage{ID: 1}
1460 if err := tx.Get(&du); err != nil {
1461 return fmt.Errorf("get disk usage: %v", err)
1463 if du.MessageSize != totalSize {
1464 _, err := fmt.Fprintf(w, "setting new total message size %d (was %d)\n", totalSize, du.MessageSize)
1465 ctl.xcheck(err, "write")
1466 du.MessageSize = totalSize
1467 if err := tx.Update(&du); err != nil {
1468 return fmt.Errorf("update disk usage: %v", err)
1473 ctl.xcheck(err, "write transaction for mailbox counts")
1475 store.BroadcastChanges(acc, changes)
1487 accountOpt := ctl.xread()
1491 var foundProblem bool
1492 const batchSize = 10000
1494 xfixmsgsize := func(accName string) {
1495 acc, err := store.OpenAccount(log, accName)
1496 ctl.xcheck(err, "open account")
1499 log.Check(err, "closing account after fixing message sizes")
1507 acc.WithRLock(func() {
1508 mailboxCounts := map[int64]store.Mailbox{} // For broadcasting.
1510 // Don't process all message in one transaction, we could block the account for too long.
1511 err := acc.DB.Write(ctx, func(tx *bstore.Tx) error {
1512 q := bstore.QueryTx[store.Message](tx)
1513 q.FilterEqual("Expunged", false)
1514 q.FilterGreater("ID", lastID)
1517 return q.ForEach(func(m store.Message) error {
1521 p := acc.MessagePath(m.ID)
1522 st, err := os.Stat(p)
1524 mb := store.Mailbox{ID: m.MailboxID}
1525 if xerr := tx.Get(&mb); xerr != nil {
1526 _, werr := fmt.Fprintf(w, "get mailbox id %d for message with file error: %v\n", mb.ID, xerr)
1527 ctl.xcheck(werr, "write")
1529 _, werr := fmt.Fprintf(w, "checking file %s for message %d in mailbox %q (id %d): %v (continuing)\n", p, m.ID, mb.Name, mb.ID, err)
1530 ctl.xcheck(werr, "write")
1533 filesize := st.Size()
1534 correctSize := int64(len(m.MsgPrefix)) + filesize
1535 if m.Size == correctSize {
1541 mb := store.Mailbox{ID: m.MailboxID}
1542 if err := tx.Get(&mb); err != nil {
1543 _, werr := fmt.Fprintf(w, "get mailbox id %d for message with file size mismatch: %v\n", mb.ID, err)
1544 ctl.xcheck(werr, "write")
1546 _, err = fmt.Fprintf(w, "fixing message %d in mailbox %q (id %d) with incorrect size %d, should be %d (len msg prefix %d + on-disk file %s size %d)\n", m.ID, mb.Name, mb.ID, m.Size, correctSize, len(m.MsgPrefix), p, filesize)
1547 ctl.xcheck(err, "write")
1549 // We assume that the original message size was accounted as stored in the mailbox
1550 // total size. If this isn't correct, the user can always run
1551 // recalculatemailboxcounts.
1553 mb.Size += correctSize
1554 if err := tx.Update(&mb); err != nil {
1555 return fmt.Errorf("update mailbox counts: %v", err)
1557 mailboxCounts[mb.ID] = mb
1559 m.Size = correctSize
1561 mr := acc.MessageReader(m)
1562 part, err := message.EnsurePart(log.Logger, false, mr, m.Size)
1564 _, werr := fmt.Fprintf(w, "parsing message %d again: %v (continuing)\n", m.ID, err)
1565 ctl.xcheck(werr, "write")
1567 m.ParsedBuf, err = json.Marshal(part)
1569 return fmt.Errorf("marshal parsed message: %v", err)
1572 if err := tx.Update(&m); err != nil {
1573 return fmt.Errorf("update message: %v", err)
1579 ctl.xcheck(err, "find and fix wrong message sizes")
1581 var changes []store.Change
1582 for _, mb := range mailboxCounts {
1583 changes = append(changes, mb.ChangeCounts())
1585 store.BroadcastChanges(acc, changes)
1591 _, err = fmt.Fprintf(w, "%d message size(s) fixed for account %s\n", total, accName)
1592 ctl.xcheck(err, "write")
1595 if accountOpt != "" {
1596 xfixmsgsize(accountOpt)
1598 for i, accName := range mox.Conf.Accounts() {
1603 _, err := fmt.Fprintf(w, "%sFixing message sizes in account %s...\n", line, accName)
1604 ctl.xcheck(err, "write")
1605 xfixmsgsize(accName)
1609 _, err := fmt.Fprintf(w, "\nProblems were found and fixed. You should invalidate messages stored at imap clients with the \"mox bumpuidvalidity account [mailbox]\" command.\n")
1610 ctl.xcheck(err, "write")
1623 accountOpt := ctl.xread()
1627 const batchSize = 100
1629 xreparseAccount := func(accName string) {
1630 acc, err := store.OpenAccount(log, accName)
1631 ctl.xcheck(err, "open account")
1634 log.Check(err, "closing account after reparsing messages")
1641 // Don't process all message in one transaction, we could block the account for too long.
1642 err := acc.DB.Write(ctx, func(tx *bstore.Tx) error {
1643 q := bstore.QueryTx[store.Message](tx)
1644 q.FilterEqual("Expunged", false)
1645 q.FilterGreater("ID", lastID)
1648 return q.ForEach(func(m store.Message) error {
1650 mr := acc.MessageReader(m)
1651 p, err := message.EnsurePart(log.Logger, false, mr, m.Size)
1653 _, err := fmt.Fprintf(w, "parsing message %d: %v (continuing)\n", m.ID, err)
1654 ctl.xcheck(err, "write")
1656 m.ParsedBuf, err = json.Marshal(p)
1658 return fmt.Errorf("marshal parsed message: %v", err)
1662 if err := tx.Update(&m); err != nil {
1663 return fmt.Errorf("update message: %v", err)
1669 ctl.xcheck(err, "update messages with parsed mime structure")
1674 _, err = fmt.Fprintf(w, "%d message(s) reparsed for account %s\n", total, accName)
1675 ctl.xcheck(err, "write")
1678 if accountOpt != "" {
1679 xreparseAccount(accountOpt)
1681 for i, accName := range mox.Conf.Accounts() {
1686 _, err := fmt.Fprintf(w, "%sReparsing account %s...\n", line, accName)
1687 ctl.xcheck(err, "write")
1688 xreparseAccount(accName)
1693 case "reassignthreads":
1701 accountOpt := ctl.xread()
1705 xreassignThreads := func(accName string) {
1706 acc, err := store.OpenAccount(log, accName)
1707 ctl.xcheck(err, "open account")
1710 log.Check(err, "closing account after reassigning threads")
1713 // We don't want to step on an existing upgrade process.
1714 err = acc.ThreadingWait(log)
1715 ctl.xcheck(err, "waiting for threading upgrade to finish")
1716 // todo: should we try to continue if the threading upgrade failed? only if there is a chance it will succeed this time...
1718 // todo: reassigning isn't atomic (in a single transaction), ideally it would be (bstore would need to be able to handle large updates).
1719 const batchSize = 50000
1720 total, err := acc.ResetThreading(ctx, log, batchSize, true)
1721 ctl.xcheck(err, "resetting threading fields")
1722 _, err = fmt.Fprintf(w, "New thread base subject assigned to %d message(s), starting to reassign threads...\n", total)
1723 ctl.xcheck(err, "write")
1725 // Assign threads again. Ideally we would do this in a single transaction, but
1726 // bstore/boltdb cannot handle so many pending changes, so we set a high batchsize.
1727 err = acc.AssignThreads(ctx, log, nil, 0, 50000, w)
1728 ctl.xcheck(err, "reassign threads")
1730 _, err = fmt.Fprintf(w, "Threads reassigned. You should invalidate messages stored at imap clients with the \"mox bumpuidvalidity account [mailbox]\" command.\n")
1731 ctl.xcheck(err, "write")
1734 if accountOpt != "" {
1735 xreassignThreads(accountOpt)
1737 for i, accName := range mox.Conf.Accounts() {
1742 _, err := fmt.Fprintf(w, "%sReassigning threads for account %s...\n", line, accName)
1743 ctl.xcheck(err, "write")
1744 xreassignThreads(accName)
1753 log.Info("unrecognized command", slog.String("cmd", cmd))
1754 ctl.xwrite("unrecognized command")