22 "github.com/mjl-/bstore"
24 "github.com/mjl-/mox/config"
25 "github.com/mjl-/mox/dns"
26 "github.com/mjl-/mox/message"
27 "github.com/mjl-/mox/metrics"
28 "github.com/mjl-/mox/mlog"
29 "github.com/mjl-/mox/mox-"
30 "github.com/mjl-/mox/queue"
31 "github.com/mjl-/mox/smtp"
32 "github.com/mjl-/mox/store"
33 "github.com/mjl-/mox/webapi"
36// ctl represents a connection to the ctl unix domain socket of a running mox instance.
37// ctl provides functions to read/write commands/responses/data streams.
39 cmd string // Set for server-side of commands.
41 r *bufio.Reader // Set for first reader.
42 x any // If set, errors are handled by calling panic(x) instead of log.Fatal.
43 log mlog.Log // If set, along with x, logging is done here.
46// xctl opens a ctl connection.
48 p := mox.DataDirPath("ctl")
49 conn, err := net.Dial("unix", p)
51 log.Fatalf("connecting to control socket at %q: %v", p, err)
53 ctl := &ctl{conn: conn}
54 version := ctl.xread()
55 if version != "ctlv0" {
56 log.Fatalf("ctl protocol mismatch, got %q, expected ctlv0", version)
61// Interpret msg as an error.
62// If ctl.x is set, the string is also written to the ctl to be interpreted as error by the other party.
63func (c *ctl) xerror(msg string) {
67 c.log.Debugx("ctl error", fmt.Errorf("%s", msg), slog.String("cmd", c.cmd))
72// Check if err is not nil. If so, handle error through ctl.x or log.Fatal. If
73// ctl.x is set, the error string is written to ctl, to be interpreted as an error
74// by the command reading from ctl.
75func (c *ctl) xcheck(err error, msg string) {
80 log.Fatalf("%s: %s", msg, err)
82 c.log.Debugx(msg, err, slog.String("cmd", c.cmd))
83 fmt.Fprintf(c.conn, "%s: %s\n", msg, err)
87// Read a line and return it without trailing newline.
88func (c *ctl) xread() string {
90 c.r = bufio.NewReader(c.conn)
92 line, err := c.r.ReadString('\n')
93 c.xcheck(err, "read from ctl")
94 return strings.TrimSuffix(line, "\n")
97// Read a line. If not "ok", the string is interpreted as an error.
98func (c *ctl) xreadok() {
105// Write a string, typically a command or parameter.
106func (c *ctl) xwrite(text string) {
107 _, err := fmt.Fprintln(c.conn, text)
108 c.xcheck(err, "write")
111// Write "ok" to indicate success.
112func (c *ctl) xwriteok() {
116// Copy data from a stream from ctl to dst.
117func (c *ctl) xstreamto(dst io.Writer) {
118 _, err := io.Copy(dst, c.reader())
119 c.xcheck(err, "reading message")
122// Copy data from src to a stream to ctl.
123func (c *ctl) xstreamfrom(src io.Reader) {
125 _, err := io.Copy(w, src)
126 c.xcheck(err, "copying")
130// Writer returns an io.Writer for a data stream to ctl.
131// When done writing, caller must call xclose to signal the end of the stream.
132// Behaviour of "x" is copied from ctl.
133func (c *ctl) writer() *ctlwriter {
134 return &ctlwriter{cmd: c.cmd, conn: c.conn, x: c.x, log: c.log}
137// Reader returns an io.Reader for a data stream from ctl.
138// Behaviour of "x" is copied from ctl.
139func (c *ctl) reader() *ctlreader {
141 c.r = bufio.NewReader(c.conn)
143 return &ctlreader{cmd: c.cmd, conn: c.conn, r: c.r, x: c.x, log: c.log}
147Ctlwriter and ctlreader implement the writing and reading a data stream. They
148implement the io.Writer and io.Reader interface. In the protocol below each
149non-data message ends with a newline that is typically stripped when
152Zero or more data transactions:
154 > "123" (for data size) or an error message
156 < "ok" or an error message
158Followed by a end of stream indicated by zero data bytes message:
163type ctlwriter struct {
164 cmd string // Set for server-side of commands.
165 conn net.Conn // Ctl socket from which messages are read.
166 buf []byte // Scratch buffer, for reading response.
167 x any // If not nil, errors in Write and xcheckf are handled with panic(x), otherwise with a log.Fatal.
171func (s *ctlwriter) Write(buf []byte) (int, error) {
172 _, err := fmt.Fprintf(s.conn, "%d\n", len(buf))
173 s.xcheck(err, "write count")
174 _, err = s.conn.Write(buf)
175 s.xcheck(err, "write data")
177 s.buf = make([]byte, 512)
179 n, err := s.conn.Read(s.buf)
180 s.xcheck(err, "reading response to write")
181 line := strings.TrimSuffix(string(s.buf[:n]), "\n")
188func (s *ctlwriter) xerror(msg string) {
192 s.log.Debugx("error", fmt.Errorf("%s", msg), slog.String("cmd", s.cmd))
197func (s *ctlwriter) xcheck(err error, msg string) {
202 log.Fatalf("%s: %s", msg, err)
204 s.log.Debugx(msg, err, slog.String("cmd", s.cmd))
209func (s *ctlwriter) xclose() {
210 _, err := fmt.Fprintf(s.conn, "0\n")
211 s.xcheck(err, "write eof")
214type ctlreader struct {
215 cmd string // Set for server-side of command.
216 conn net.Conn // For writing "ok" after reading.
217 r *bufio.Reader // Buffered ctl socket.
218 err error // If set, returned for each read. can also be io.EOF.
219 npending int // Number of bytes that can still be read until a new count line must be read.
220 x any // If set, errors are handled with panic(x) instead of log.Fatal.
221 log mlog.Log // If x is set, logging goes to log.
224func (s *ctlreader) Read(buf []byte) (N int, Err error) {
229 line, err := s.r.ReadString('\n')
230 s.xcheck(err, "reading count")
231 line = strings.TrimSuffix(line, "\n")
232 n, err := strconv.ParseInt(line, 10, 32)
246 n, err := s.r.Read(buf[:rn])
247 s.xcheck(err, "read from ctl")
250 _, err = fmt.Fprintln(s.conn, "ok")
251 s.xcheck(err, "writing ok after reading")
256func (s *ctlreader) xerror(msg string) {
260 s.log.Debugx("error", fmt.Errorf("%s", msg), slog.String("cmd", s.cmd))
265func (s *ctlreader) xcheck(err error, msg string) {
270 log.Fatalf("%s: %s", msg, err)
272 s.log.Debugx(msg, err, slog.String("cmd", s.cmd))
277// servectl handles requests on the unix domain socket "ctl", e.g. for graceful shutdown, local mail delivery.
278func servectl(ctx context.Context, log mlog.Log, conn net.Conn, shutdown func()) {
279 log.Debug("ctl connection")
281 var stop = struct{}{} // Sentinel value for panic and recover.
282 ctl := &ctl{conn: conn, x: stop, log: log}
285 if x == nil || x == stop {
288 log.Error("servectl panic", slog.Any("err", x), slog.String("cmd", ctl.cmd))
290 metrics.PanicInc(metrics.Ctl)
297 servectlcmd(ctx, ctl, shutdown)
301func xparseJSON(ctl *ctl, s string, v any) {
302 dec := json.NewDecoder(strings.NewReader(s))
303 dec.DisallowUnknownFields()
305 ctl.xcheck(err, "parsing from ctl as json")
308func servectlcmd(ctx context.Context, ctl *ctl, shutdown func()) {
312 log.Info("ctl command", slog.String("cmd", cmd))
319 /* The protocol, double quoted are literals.
329 a, addr, err := store.OpenEmail(log, to)
330 ctl.xcheck(err, "lookup destination address")
332 msgFile, err := store.CreateMessageTemp(log, "ctl-deliver")
333 ctl.xcheck(err, "creating temporary message file")
334 defer store.CloseRemoveTempFile(log, msgFile, "deliver message")
335 mw := message.NewWriter(msgFile)
340 ctl.xcheck(err, "syncing message to storage")
343 Received: time.Now(),
348 err := a.DeliverDestination(log, addr, &m, msgFile)
349 ctl.xcheck(err, "delivering message")
350 log.Info("message delivered through ctl", slog.Any("to", to))
354 ctl.xcheck(err, "closing account")
357 case "setaccountpassword":
359 > "setaccountpassword"
365 account := ctl.xread()
368 acc, err := store.OpenAccount(log, account)
369 ctl.xcheck(err, "open account")
373 log.Check(err, "closing account after setting password")
377 err = acc.SetPassword(log, pw)
378 ctl.xcheck(err, "setting password")
380 ctl.xcheck(err, "closing account")
384 case "queueholdruleslist":
386 > "queueholdruleslist"
390 l, err := queue.HoldRuleList(ctx)
391 ctl.xcheck(err, "listing hold rules")
394 fmt.Fprintln(xw, "hold rules:")
395 for _, hr := range l {
397 if hr.Account != "" {
398 elems = append(elems, fmt.Sprintf("account %q", hr.Account))
400 var zerodom dns.Domain
401 if hr.SenderDomain != zerodom {
402 elems = append(elems, fmt.Sprintf("sender domain %q", hr.SenderDomain.Name()))
404 if hr.RecipientDomain != zerodom {
405 elems = append(elems, fmt.Sprintf("sender domain %q", hr.RecipientDomain.Name()))
408 fmt.Fprintf(xw, "id %d: all messages\n", hr.ID)
410 fmt.Fprintf(xw, "id %d: %s\n", hr.ID, strings.Join(elems, ", "))
414 fmt.Fprint(xw, "(none)\n")
418 case "queueholdrulesadd":
420 > "queueholdrulesadd"
426 var hr queue.HoldRule
427 hr.Account = ctl.xread()
428 senderdomstr := ctl.xread()
429 rcptdomstr := ctl.xread()
431 hr.SenderDomain, err = dns.ParseDomain(senderdomstr)
432 ctl.xcheck(err, "parsing sender domain")
433 hr.RecipientDomain, err = dns.ParseDomain(rcptdomstr)
434 ctl.xcheck(err, "parsing recipient domain")
435 hr, err = queue.HoldRuleAdd(ctx, log, hr)
436 ctl.xcheck(err, "add hold rule")
439 case "queueholdrulesremove":
441 > "queueholdrulesremove"
445 id, err := strconv.ParseInt(ctl.xread(), 10, 64)
446 ctl.xcheck(err, "parsing id")
447 err = queue.HoldRuleRemove(ctx, log, id)
448 ctl.xcheck(err, "remove hold rule")
460 xparseJSON(ctl, ctl.xread(), &f)
462 xparseJSON(ctl, ctl.xread(), &s)
463 qmsgs, err := queue.List(ctx, f, s)
464 ctl.xcheck(err, "listing queue")
468 fmt.Fprintln(xw, "messages:")
469 for _, qm := range qmsgs {
470 var lastAttempt string
471 if qm.LastAttempt != nil {
472 lastAttempt = time.Since(*qm.LastAttempt).Round(time.Second).String()
474 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)
477 fmt.Fprint(xw, "(none)\n")
484 > queuefilters as json
491 xparseJSON(ctl, ctl.xread(), &f)
492 hold := ctl.xread() == "true"
493 count, err := queue.HoldSet(ctx, f, hold)
494 ctl.xcheck(err, "setting on hold status for messages")
496 ctl.xwrite(fmt.Sprintf("%d", count))
498 case "queueschedule":
501 > queuefilters as json
509 xparseJSON(ctl, ctl.xread(), &f)
510 relnow := ctl.xread()
511 d, err := time.ParseDuration(ctl.xread())
512 ctl.xcheck(err, "parsing duration for next delivery attempt")
515 count, err = queue.NextAttemptAdd(ctx, f, d)
517 count, err = queue.NextAttemptSet(ctx, f, time.Now().Add(d))
519 ctl.xcheck(err, "setting next delivery attempts in queue")
521 ctl.xwrite(fmt.Sprintf("%d", count))
523 case "queuetransport":
526 > queuefilters as json
533 xparseJSON(ctl, ctl.xread(), &f)
534 transport := ctl.xread()
535 count, err := queue.TransportSet(ctx, f, transport)
536 ctl.xcheck(err, "adding to next delivery attempts in queue")
538 ctl.xwrite(fmt.Sprintf("%d", count))
540 case "queuerequiretls":
543 > queuefilters as json
544 > reqtls (empty string, "true" or "false")
550 xparseJSON(ctl, ctl.xread(), &f)
551 reqtls := ctl.xread()
562 ctl.xcheck(fmt.Errorf("unknown value %q", reqtls), "parsing value")
564 count, err := queue.RequireTLSSet(ctx, f, req)
565 ctl.xcheck(err, "setting tls requirements on messages in queue")
567 ctl.xwrite(fmt.Sprintf("%d", count))
572 > queuefilters as json
578 xparseJSON(ctl, ctl.xread(), &f)
579 count, err := queue.Fail(ctx, log, f)
580 ctl.xcheck(err, "marking messages from queue as failed")
582 ctl.xwrite(fmt.Sprintf("%d", count))
587 > queuefilters as json
593 xparseJSON(ctl, ctl.xread(), &f)
594 count, err := queue.Drop(ctx, log, f)
595 ctl.xcheck(err, "dropping messages from queue")
597 ctl.xwrite(fmt.Sprintf("%d", count))
608 id, err := strconv.ParseInt(idstr, 10, 64)
610 ctl.xcheck(err, "parsing id")
612 mr, err := queue.OpenMessage(ctx, id)
613 ctl.xcheck(err, "opening message")
616 log.Check(err, "closing message from queue")
621 case "queueretiredlist":
629 var f queue.RetiredFilter
630 xparseJSON(ctl, ctl.xread(), &f)
631 var s queue.RetiredSort
632 xparseJSON(ctl, ctl.xread(), &s)
633 qmsgs, err := queue.RetiredList(ctx, f, s)
634 ctl.xcheck(err, "listing retired queue")
638 fmt.Fprintln(xw, "retired messages:")
639 for _, qm := range qmsgs {
640 var lastAttempt string
641 if qm.LastAttempt != nil {
642 lastAttempt = time.Since(*qm.LastAttempt).Round(time.Second).String()
648 sender, err := qm.Sender()
649 xcheckf(err, "parsing sender")
650 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)
653 fmt.Fprint(xw, "(none)\n")
657 case "queueretiredprint":
659 > "queueretiredprint"
665 id, err := strconv.ParseInt(idstr, 10, 64)
667 ctl.xcheck(err, "parsing id")
669 l, err := queue.RetiredList(ctx, queue.RetiredFilter{IDs: []int64{id}}, queue.RetiredSort{})
670 ctl.xcheck(err, "getting retired messages")
672 ctl.xcheck(errors.New("not found"), "getting retired message")
677 enc := json.NewEncoder(xw)
678 enc.SetIndent("", "\t")
680 ctl.xcheck(err, "encode retired message")
683 case "queuehooklist":
691 var f queue.HookFilter
692 xparseJSON(ctl, ctl.xread(), &f)
694 xparseJSON(ctl, ctl.xread(), &s)
695 hooks, err := queue.HookList(ctx, f, s)
696 ctl.xcheck(err, "listing webhooks")
700 fmt.Fprintln(xw, "webhooks:")
701 for _, h := range hooks {
702 var lastAttempt string
703 if len(h.Results) > 0 {
704 lastAttempt = time.Since(h.LastResult().Start).Round(time.Second).String()
706 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)
709 fmt.Fprint(xw, "(none)\n")
713 case "queuehookschedule":
715 > "queuehookschedule"
716 > hookfilters as json
723 var f queue.HookFilter
724 xparseJSON(ctl, ctl.xread(), &f)
725 relnow := ctl.xread()
726 d, err := time.ParseDuration(ctl.xread())
727 ctl.xcheck(err, "parsing duration for next delivery attempt")
730 count, err = queue.HookNextAttemptAdd(ctx, f, d)
732 count, err = queue.HookNextAttemptSet(ctx, f, time.Now().Add(d))
734 ctl.xcheck(err, "setting next delivery attempts in queue")
736 ctl.xwrite(fmt.Sprintf("%d", count))
738 case "queuehookcancel":
741 > hookfilters as json
746 var f queue.HookFilter
747 xparseJSON(ctl, ctl.xread(), &f)
748 count, err := queue.HookCancel(ctx, log, f)
749 ctl.xcheck(err, "canceling webhooks in queue")
751 ctl.xwrite(fmt.Sprintf("%d", count))
753 case "queuehookprint":
761 id, err := strconv.ParseInt(idstr, 10, 64)
763 ctl.xcheck(err, "parsing id")
765 l, err := queue.HookList(ctx, queue.HookFilter{IDs: []int64{id}}, queue.HookSort{})
766 ctl.xcheck(err, "getting webhooks")
768 ctl.xcheck(errors.New("not found"), "getting webhook")
773 enc := json.NewEncoder(xw)
774 enc.SetIndent("", "\t")
776 ctl.xcheck(err, "encode webhook")
779 case "queuehookretiredlist":
781 > "queuehookretiredlist"
787 var f queue.HookRetiredFilter
788 xparseJSON(ctl, ctl.xread(), &f)
789 var s queue.HookRetiredSort
790 xparseJSON(ctl, ctl.xread(), &s)
791 l, err := queue.HookRetiredList(ctx, f, s)
792 ctl.xcheck(err, "listing retired webhooks")
796 fmt.Fprintln(xw, "retired webhooks:")
797 for _, h := range l {
798 var lastAttempt string
799 if len(h.Results) > 0 {
800 lastAttempt = time.Since(h.LastResult().Start).Round(time.Second).String()
806 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)
809 fmt.Fprint(xw, "(none)\n")
813 case "queuehookretiredprint":
815 > "queuehookretiredprint"
821 id, err := strconv.ParseInt(idstr, 10, 64)
823 ctl.xcheck(err, "parsing id")
825 l, err := queue.HookRetiredList(ctx, queue.HookRetiredFilter{IDs: []int64{id}}, queue.HookRetiredSort{})
826 ctl.xcheck(err, "getting retired webhooks")
828 ctl.xcheck(errors.New("not found"), "getting retired webhook")
833 enc := json.NewEncoder(xw)
834 enc.SetIndent("", "\t")
836 ctl.xcheck(err, "encode retired webhook")
839 case "queuesuppresslist":
841 > "queuesuppresslist"
847 account := ctl.xread()
848 l, err := queue.SuppressionList(ctx, account)
849 ctl.xcheck(err, "listing suppressions")
852 fmt.Fprintln(xw, "suppressions (account, address, manual, time added, base adddress, reason):")
853 for _, sup := range l {
858 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)
861 fmt.Fprintln(xw, "(none)")
865 case "queuesuppressadd":
873 account := ctl.xread()
874 address := ctl.xread()
875 _, ok := mox.Conf.Account(account)
877 ctl.xcheck(errors.New("unknown account"), "looking up account")
879 addr, err := smtp.ParseAddress(address)
880 ctl.xcheck(err, "parsing address")
881 sup := webapi.Suppression{
884 Reason: "added through mox cli",
886 err = queue.SuppressionAdd(ctx, addr.Path(), &sup)
887 ctl.xcheck(err, "adding suppression")
890 case "queuesuppressremove":
892 > "queuesuppressremove"
898 account := ctl.xread()
899 address := ctl.xread()
900 addr, err := smtp.ParseAddress(address)
901 ctl.xcheck(err, "parsing address")
902 err = queue.SuppressionRemove(ctx, account, addr.Path())
903 ctl.xcheck(err, "removing suppression")
906 case "queuesuppresslookup":
908 > "queuesuppresslookup"
915 account := ctl.xread()
916 address := ctl.xread()
918 _, ok := mox.Conf.Account(account)
920 ctl.xcheck(errors.New("unknown account"), "looking up account")
923 addr, err := smtp.ParseAddress(address)
924 ctl.xcheck(err, "parsing address")
925 sup, err := queue.SuppressionLookup(ctx, account, addr.Path())
926 ctl.xcheck(err, "looking up suppression")
930 fmt.Fprintln(xw, "not present")
936 fmt.Fprintf(xw, "present\nadded: %s\nmanual: %s\nbase address: %s\nreason: %q\n", sup.Created.Round(time.Second), manual, sup.BaseAddress, sup.Reason)
940 case "importmaildir", "importmbox":
941 mbox := cmd == "importmbox"
942 importctl(ctx, ctl, mbox)
952 domain := ctl.xread()
953 account := ctl.xread()
954 localpart := ctl.xread()
955 d, err := dns.ParseDomain(domain)
956 ctl.xcheck(err, "parsing domain")
957 err = mox.DomainAdd(ctx, d, account, smtp.Localpart(localpart))
958 ctl.xcheck(err, "adding domain")
967 domain := ctl.xread()
968 d, err := dns.ParseDomain(domain)
969 ctl.xcheck(err, "parsing domain")
970 err = mox.DomainRemove(ctx, d)
971 ctl.xcheck(err, "removing domain")
981 account := ctl.xread()
982 address := ctl.xread()
983 err := mox.AccountAdd(ctx, account, address)
984 ctl.xcheck(err, "adding account")
993 account := ctl.xread()
994 err := mox.AccountRemove(ctx, account)
995 ctl.xcheck(err, "removing account")
1005 address := ctl.xread()
1006 account := ctl.xread()
1007 err := mox.AddressAdd(ctx, address, account)
1008 ctl.xcheck(err, "adding address")
1017 address := ctl.xread()
1018 err := mox.AddressRemove(ctx, address)
1019 ctl.xcheck(err, "removing address")
1029 domain := ctl.xread()
1030 d, err := dns.ParseDomain(domain)
1031 ctl.xcheck(err, "parsing domain")
1032 dc, ok := mox.Conf.Domain(d)
1034 ctl.xcheck(errors.New("no such domain"), "listing aliases")
1038 for _, a := range dc.Aliases {
1039 lp, err := smtp.ParseLocalpart(a.LocalpartStr)
1040 ctl.xcheck(err, "parsing alias localpart")
1041 fmt.Fprintln(w, smtp.NewAddress(lp, a.Domain).Pack(true))
1052 address := ctl.xread()
1053 _, alias, ok := mox.Conf.AccountDestination(address)
1055 ctl.xcheck(errors.New("no such address"), "looking up alias")
1056 } else if alias == nil {
1057 ctl.xcheck(errors.New("address not an alias"), "looking up alias")
1061 fmt.Fprintf(w, "# postpublic %v\n", alias.PostPublic)
1062 fmt.Fprintf(w, "# listmembers %v\n", alias.ListMembers)
1063 fmt.Fprintf(w, "# allowmsgfrom %v\n", alias.AllowMsgFrom)
1064 fmt.Fprintln(w, "# members:")
1065 for _, a := range alias.Addresses {
1077 address := ctl.xread()
1079 addr, err := smtp.ParseAddress(address)
1080 ctl.xcheck(err, "parsing address")
1081 var alias config.Alias
1082 xparseJSON(ctl, line, &alias)
1083 err = mox.AliasAdd(ctx, addr, alias)
1084 ctl.xcheck(err, "adding alias")
1091 > "true" or "false" for postpublic
1092 > "true" or "false" for listmembers
1093 > "true" or "false" for allowmsgfrom
1096 address := ctl.xread()
1097 postpublic := ctl.xread()
1098 listmembers := ctl.xread()
1099 allowmsgfrom := ctl.xread()
1100 addr, err := smtp.ParseAddress(address)
1101 ctl.xcheck(err, "parsing address")
1102 err = mox.DomainSave(ctx, addr.Domain.Name(), func(d *config.Domain) error {
1103 a, ok := d.Aliases[addr.Localpart.String()]
1105 return fmt.Errorf("alias does not exist")
1110 a.PostPublic = false
1114 switch listmembers {
1116 a.ListMembers = false
1118 a.ListMembers = true
1120 switch allowmsgfrom {
1122 a.AllowMsgFrom = false
1124 a.AllowMsgFrom = true
1127 d.Aliases = maps.Clone(d.Aliases)
1128 d.Aliases[addr.Localpart.String()] = a
1131 ctl.xcheck(err, "saving alias")
1140 address := ctl.xread()
1141 addr, err := smtp.ParseAddress(address)
1142 ctl.xcheck(err, "parsing address")
1143 err = mox.AliasRemove(ctx, addr)
1144 ctl.xcheck(err, "removing alias")
1147 case "aliasaddaddr":
1154 address := ctl.xread()
1156 addr, err := smtp.ParseAddress(address)
1157 ctl.xcheck(err, "parsing address")
1158 var addresses []string
1159 xparseJSON(ctl, line, &addresses)
1160 err = mox.AliasAddressesAdd(ctx, addr, addresses)
1161 ctl.xcheck(err, "adding addresses to alias")
1171 address := ctl.xread()
1173 addr, err := smtp.ParseAddress(address)
1174 ctl.xcheck(err, "parsing address")
1175 var addresses []string
1176 xparseJSON(ctl, line, &addresses)
1177 err = mox.AliasAddressesRemove(ctx, addr, addresses)
1178 ctl.xcheck(err, "removing addresses to alias")
1188 l := mox.Conf.LogLevels()
1191 keys = append(keys, k)
1193 sort.Slice(keys, func(i, j int) bool {
1194 return keys[i] < keys[j]
1197 for _, k := range keys {
1202 s += ks + ": " + mlog.LevelStrings[l[k]] + "\n"
1204 ctl.xstreamfrom(strings.NewReader(s))
1206 case "setloglevels":
1210 > level (if empty, log level for pkg will be unset)
1214 levelstr := ctl.xread()
1216 mox.Conf.LogLevelRemove(log, pkg)
1218 level, ok := mlog.Levels[levelstr]
1220 ctl.xerror("bad level")
1222 mox.Conf.LogLevelSet(log, pkg, level)
1232 account := ctl.xread()
1233 acc, err := store.OpenAccount(log, account)
1234 ctl.xcheck(err, "open account")
1238 log.Check(err, "closing account after retraining")
1242 acc.WithWLock(func() {
1243 conf, _ := acc.Conf()
1244 if conf.JunkFilter == nil {
1245 ctl.xcheck(store.ErrNoJunkFilter, "looking for junk filter")
1248 // Remove existing junk filter files.
1249 basePath := mox.DataDirPath("accounts")
1250 dbPath := filepath.Join(basePath, acc.Name, "junkfilter.db")
1251 bloomPath := filepath.Join(basePath, acc.Name, "junkfilter.bloom")
1252 err := os.Remove(dbPath)
1253 log.Check(err, "removing old junkfilter database file", slog.String("path", dbPath))
1254 err = os.Remove(bloomPath)
1255 log.Check(err, "removing old junkfilter bloom filter file", slog.String("path", bloomPath))
1257 // Open junk filter, this creates new files.
1258 jf, _, err := acc.OpenJunkFilter(ctx, log)
1259 ctl.xcheck(err, "open new junk filter")
1265 log.Check(err, "closing junk filter during cleanup")
1268 // Read through messages with junk or nonjunk flag set, and train them.
1269 var total, trained int
1270 q := bstore.QueryDB[store.Message](ctx, acc.DB)
1271 q.FilterEqual("Expunged", false)
1272 err = q.ForEach(func(m store.Message) error {
1274 ok, err := acc.TrainMessage(ctx, log, jf, m)
1280 ctl.xcheck(err, "training messages")
1281 log.Info("retrained messages", slog.Int("total", total), slog.Int("trained", trained))
1283 // Close junk filter, marking success.
1286 ctl.xcheck(err, "closing junk filter")
1290 case "recalculatemailboxcounts":
1292 > "recalculatemailboxcounts"
1297 account := ctl.xread()
1298 acc, err := store.OpenAccount(log, account)
1299 ctl.xcheck(err, "open account")
1303 log.Check(err, "closing account after recalculating mailbox counts")
1310 acc.WithWLock(func() {
1311 var changes []store.Change
1312 err = acc.DB.Write(ctx, func(tx *bstore.Tx) error {
1314 err := bstore.QueryTx[store.Mailbox](tx).ForEach(func(mb store.Mailbox) error {
1315 mc, err := mb.CalculateCounts(tx)
1317 return fmt.Errorf("calculating counts for mailbox %q: %w", mb.Name, err)
1319 totalSize += mc.Size
1321 if !mb.HaveCounts || mc != mb.MailboxCounts {
1322 _, err := fmt.Fprintf(w, "for %s setting new counts %s (was %s)\n", mb.Name, mc, mb.MailboxCounts)
1323 ctl.xcheck(err, "write")
1324 mb.HaveCounts = true
1325 mb.MailboxCounts = mc
1326 if err := tx.Update(&mb); err != nil {
1327 return fmt.Errorf("storing new counts for %q: %v", mb.Name, err)
1329 changes = append(changes, mb.ChangeCounts())
1337 du := store.DiskUsage{ID: 1}
1338 if err := tx.Get(&du); err != nil {
1339 return fmt.Errorf("get disk usage: %v", err)
1341 if du.MessageSize != totalSize {
1342 _, err := fmt.Fprintf(w, "setting new total message size %d (was %d)\n", totalSize, du.MessageSize)
1343 ctl.xcheck(err, "write")
1344 du.MessageSize = totalSize
1345 if err := tx.Update(&du); err != nil {
1346 return fmt.Errorf("update disk usage: %v", err)
1351 ctl.xcheck(err, "write transaction for mailbox counts")
1353 store.BroadcastChanges(acc, changes)
1365 accountOpt := ctl.xread()
1369 var foundProblem bool
1370 const batchSize = 10000
1372 xfixmsgsize := func(accName string) {
1373 acc, err := store.OpenAccount(log, accName)
1374 ctl.xcheck(err, "open account")
1377 log.Check(err, "closing account after fixing message sizes")
1385 acc.WithRLock(func() {
1386 mailboxCounts := map[int64]store.Mailbox{} // For broadcasting.
1388 // Don't process all message in one transaction, we could block the account for too long.
1389 err := acc.DB.Write(ctx, func(tx *bstore.Tx) error {
1390 q := bstore.QueryTx[store.Message](tx)
1391 q.FilterEqual("Expunged", false)
1392 q.FilterGreater("ID", lastID)
1395 return q.ForEach(func(m store.Message) error {
1399 p := acc.MessagePath(m.ID)
1400 st, err := os.Stat(p)
1402 mb := store.Mailbox{ID: m.MailboxID}
1403 if xerr := tx.Get(&mb); xerr != nil {
1404 _, werr := fmt.Fprintf(w, "get mailbox id %d for message with file error: %v\n", mb.ID, xerr)
1405 ctl.xcheck(werr, "write")
1407 _, 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)
1408 ctl.xcheck(werr, "write")
1411 filesize := st.Size()
1412 correctSize := int64(len(m.MsgPrefix)) + filesize
1413 if m.Size == correctSize {
1419 mb := store.Mailbox{ID: m.MailboxID}
1420 if err := tx.Get(&mb); err != nil {
1421 _, werr := fmt.Fprintf(w, "get mailbox id %d for message with file size mismatch: %v\n", mb.ID, err)
1422 ctl.xcheck(werr, "write")
1424 _, 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)
1425 ctl.xcheck(err, "write")
1427 // We assume that the original message size was accounted as stored in the mailbox
1428 // total size. If this isn't correct, the user can always run
1429 // recalculatemailboxcounts.
1431 mb.Size += correctSize
1432 if err := tx.Update(&mb); err != nil {
1433 return fmt.Errorf("update mailbox counts: %v", err)
1435 mailboxCounts[mb.ID] = mb
1437 m.Size = correctSize
1439 mr := acc.MessageReader(m)
1440 part, err := message.EnsurePart(log.Logger, false, mr, m.Size)
1442 _, werr := fmt.Fprintf(w, "parsing message %d again: %v (continuing)\n", m.ID, err)
1443 ctl.xcheck(werr, "write")
1445 m.ParsedBuf, err = json.Marshal(part)
1447 return fmt.Errorf("marshal parsed message: %v", err)
1450 if err := tx.Update(&m); err != nil {
1451 return fmt.Errorf("update message: %v", err)
1457 ctl.xcheck(err, "find and fix wrong message sizes")
1459 var changes []store.Change
1460 for _, mb := range mailboxCounts {
1461 changes = append(changes, mb.ChangeCounts())
1463 store.BroadcastChanges(acc, changes)
1469 _, err = fmt.Fprintf(w, "%d message size(s) fixed for account %s\n", total, accName)
1470 ctl.xcheck(err, "write")
1473 if accountOpt != "" {
1474 xfixmsgsize(accountOpt)
1476 for i, accName := range mox.Conf.Accounts() {
1481 _, err := fmt.Fprintf(w, "%sFixing message sizes in account %s...\n", line, accName)
1482 ctl.xcheck(err, "write")
1483 xfixmsgsize(accName)
1487 _, 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")
1488 ctl.xcheck(err, "write")
1501 accountOpt := ctl.xread()
1505 const batchSize = 100
1507 xreparseAccount := func(accName string) {
1508 acc, err := store.OpenAccount(log, accName)
1509 ctl.xcheck(err, "open account")
1512 log.Check(err, "closing account after reparsing messages")
1519 // Don't process all message in one transaction, we could block the account for too long.
1520 err := acc.DB.Write(ctx, func(tx *bstore.Tx) error {
1521 q := bstore.QueryTx[store.Message](tx)
1522 q.FilterEqual("Expunged", false)
1523 q.FilterGreater("ID", lastID)
1526 return q.ForEach(func(m store.Message) error {
1528 mr := acc.MessageReader(m)
1529 p, err := message.EnsurePart(log.Logger, false, mr, m.Size)
1531 _, err := fmt.Fprintf(w, "parsing message %d: %v (continuing)\n", m.ID, err)
1532 ctl.xcheck(err, "write")
1534 m.ParsedBuf, err = json.Marshal(p)
1536 return fmt.Errorf("marshal parsed message: %v", err)
1540 if err := tx.Update(&m); err != nil {
1541 return fmt.Errorf("update message: %v", err)
1547 ctl.xcheck(err, "update messages with parsed mime structure")
1552 _, err = fmt.Fprintf(w, "%d message(s) reparsed for account %s\n", total, accName)
1553 ctl.xcheck(err, "write")
1556 if accountOpt != "" {
1557 xreparseAccount(accountOpt)
1559 for i, accName := range mox.Conf.Accounts() {
1564 _, err := fmt.Fprintf(w, "%sReparsing account %s...\n", line, accName)
1565 ctl.xcheck(err, "write")
1566 xreparseAccount(accName)
1571 case "reassignthreads":
1579 accountOpt := ctl.xread()
1583 xreassignThreads := func(accName string) {
1584 acc, err := store.OpenAccount(log, accName)
1585 ctl.xcheck(err, "open account")
1588 log.Check(err, "closing account after reassigning threads")
1591 // We don't want to step on an existing upgrade process.
1592 err = acc.ThreadingWait(log)
1593 ctl.xcheck(err, "waiting for threading upgrade to finish")
1594 // todo: should we try to continue if the threading upgrade failed? only if there is a chance it will succeed this time...
1596 // todo: reassigning isn't atomic (in a single transaction), ideally it would be (bstore would need to be able to handle large updates).
1597 const batchSize = 50000
1598 total, err := acc.ResetThreading(ctx, log, batchSize, true)
1599 ctl.xcheck(err, "resetting threading fields")
1600 _, err = fmt.Fprintf(w, "New thread base subject assigned to %d message(s), starting to reassign threads...\n", total)
1601 ctl.xcheck(err, "write")
1603 // Assign threads again. Ideally we would do this in a single transaction, but
1604 // bstore/boltdb cannot handle so many pending changes, so we set a high batchsize.
1605 err = acc.AssignThreads(ctx, log, nil, 0, 50000, w)
1606 ctl.xcheck(err, "reassign threads")
1608 _, err = fmt.Fprintf(w, "Threads reassigned. You should invalidate messages stored at imap clients with the \"mox bumpuidvalidity account [mailbox]\" command.\n")
1609 ctl.xcheck(err, "write")
1612 if accountOpt != "" {
1613 xreassignThreads(accountOpt)
1615 for i, accName := range mox.Conf.Accounts() {
1620 _, err := fmt.Fprintf(w, "%sReassigning threads for account %s...\n", line, accName)
1621 ctl.xcheck(err, "write")
1622 xreassignThreads(accName)
1631 log.Info("unrecognized command", slog.String("cmd", cmd))
1632 ctl.xwrite("unrecognized command")