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"
446 id, err := strconv.ParseInt(idstr, 10, 64)
447 ctl.xcheck(err, "parsing id")
448 err = queue.HoldRuleRemove(ctx, log, id)
449 ctl.xcheck(err, "remove hold rule")
460 filterline := ctl.xread()
461 sortline := ctl.xread()
463 xparseJSON(ctl, filterline, &f)
465 xparseJSON(ctl, sortline, &s)
466 qmsgs, err := queue.List(ctx, f, s)
467 ctl.xcheck(err, "listing queue")
471 fmt.Fprintln(xw, "messages:")
472 for _, qm := range qmsgs {
473 var lastAttempt string
474 if qm.LastAttempt != nil {
475 lastAttempt = time.Since(*qm.LastAttempt).Round(time.Second).String()
477 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)
480 fmt.Fprint(xw, "(none)\n")
487 > queuefilters as json
493 filterline := ctl.xread()
494 hold := ctl.xread() == "true"
496 xparseJSON(ctl, filterline, &f)
497 count, err := queue.HoldSet(ctx, f, hold)
498 ctl.xcheck(err, "setting on hold status for messages")
500 ctl.xwrite(fmt.Sprintf("%d", count))
502 case "queueschedule":
505 > queuefilters as json
512 filterline := ctl.xread()
513 relnow := ctl.xread()
514 duration := ctl.xread()
516 xparseJSON(ctl, filterline, &f)
517 d, err := time.ParseDuration(duration)
518 ctl.xcheck(err, "parsing duration for next delivery attempt")
521 count, err = queue.NextAttemptAdd(ctx, f, d)
523 count, err = queue.NextAttemptSet(ctx, f, time.Now().Add(d))
525 ctl.xcheck(err, "setting next delivery attempts in queue")
527 ctl.xwrite(fmt.Sprintf("%d", count))
529 case "queuetransport":
532 > queuefilters as json
538 filterline := ctl.xread()
539 transport := ctl.xread()
541 xparseJSON(ctl, filterline, &f)
542 count, err := queue.TransportSet(ctx, f, transport)
543 ctl.xcheck(err, "adding to next delivery attempts in queue")
545 ctl.xwrite(fmt.Sprintf("%d", count))
547 case "queuerequiretls":
550 > queuefilters as json
551 > reqtls (empty string, "true" or "false")
556 filterline := ctl.xread()
557 reqtls := ctl.xread()
568 ctl.xcheck(fmt.Errorf("unknown value %q", reqtls), "parsing value")
571 xparseJSON(ctl, filterline, &f)
572 count, err := queue.RequireTLSSet(ctx, f, req)
573 ctl.xcheck(err, "setting tls requirements on messages in queue")
575 ctl.xwrite(fmt.Sprintf("%d", count))
580 > queuefilters as json
585 filterline := ctl.xread()
587 xparseJSON(ctl, filterline, &f)
588 count, err := queue.Fail(ctx, log, f)
589 ctl.xcheck(err, "marking messages from queue as failed")
591 ctl.xwrite(fmt.Sprintf("%d", count))
596 > queuefilters as json
601 filterline := ctl.xread()
603 xparseJSON(ctl, filterline, &f)
604 count, err := queue.Drop(ctx, log, f)
605 ctl.xcheck(err, "dropping messages from queue")
607 ctl.xwrite(fmt.Sprintf("%d", count))
618 id, err := strconv.ParseInt(idstr, 10, 64)
620 ctl.xcheck(err, "parsing id")
622 mr, err := queue.OpenMessage(ctx, id)
623 ctl.xcheck(err, "opening message")
626 log.Check(err, "closing message from queue")
631 case "queueretiredlist":
639 filterline := ctl.xread()
640 sortline := ctl.xread()
641 var f queue.RetiredFilter
642 xparseJSON(ctl, filterline, &f)
643 var s queue.RetiredSort
644 xparseJSON(ctl, sortline, &s)
645 qmsgs, err := queue.RetiredList(ctx, f, s)
646 ctl.xcheck(err, "listing retired queue")
650 fmt.Fprintln(xw, "retired messages:")
651 for _, qm := range qmsgs {
652 var lastAttempt string
653 if qm.LastAttempt != nil {
654 lastAttempt = time.Since(*qm.LastAttempt).Round(time.Second).String()
660 sender, err := qm.Sender()
661 xcheckf(err, "parsing sender")
662 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)
665 fmt.Fprint(xw, "(none)\n")
669 case "queueretiredprint":
671 > "queueretiredprint"
677 id, err := strconv.ParseInt(idstr, 10, 64)
679 ctl.xcheck(err, "parsing id")
681 l, err := queue.RetiredList(ctx, queue.RetiredFilter{IDs: []int64{id}}, queue.RetiredSort{})
682 ctl.xcheck(err, "getting retired messages")
684 ctl.xcheck(errors.New("not found"), "getting retired message")
689 enc := json.NewEncoder(xw)
690 enc.SetIndent("", "\t")
692 ctl.xcheck(err, "encode retired message")
695 case "queuehooklist":
703 filterline := ctl.xread()
704 sortline := ctl.xread()
705 var f queue.HookFilter
706 xparseJSON(ctl, filterline, &f)
708 xparseJSON(ctl, sortline, &s)
709 hooks, err := queue.HookList(ctx, f, s)
710 ctl.xcheck(err, "listing webhooks")
714 fmt.Fprintln(xw, "webhooks:")
715 for _, h := range hooks {
716 var lastAttempt string
717 if len(h.Results) > 0 {
718 lastAttempt = time.Since(h.LastResult().Start).Round(time.Second).String()
720 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)
723 fmt.Fprint(xw, "(none)\n")
727 case "queuehookschedule":
729 > "queuehookschedule"
730 > hookfilters as json
737 filterline := ctl.xread()
738 relnow := ctl.xread()
739 duration := ctl.xread()
740 var f queue.HookFilter
741 xparseJSON(ctl, filterline, &f)
742 d, err := time.ParseDuration(duration)
743 ctl.xcheck(err, "parsing duration for next delivery attempt")
746 count, err = queue.HookNextAttemptAdd(ctx, f, d)
748 count, err = queue.HookNextAttemptSet(ctx, f, time.Now().Add(d))
750 ctl.xcheck(err, "setting next delivery attempts in queue")
752 ctl.xwrite(fmt.Sprintf("%d", count))
754 case "queuehookcancel":
757 > hookfilters as json
762 filterline := ctl.xread()
763 var f queue.HookFilter
764 xparseJSON(ctl, filterline, &f)
765 count, err := queue.HookCancel(ctx, log, f)
766 ctl.xcheck(err, "canceling webhooks in queue")
768 ctl.xwrite(fmt.Sprintf("%d", count))
770 case "queuehookprint":
778 id, err := strconv.ParseInt(idstr, 10, 64)
780 ctl.xcheck(err, "parsing id")
782 l, err := queue.HookList(ctx, queue.HookFilter{IDs: []int64{id}}, queue.HookSort{})
783 ctl.xcheck(err, "getting webhooks")
785 ctl.xcheck(errors.New("not found"), "getting webhook")
790 enc := json.NewEncoder(xw)
791 enc.SetIndent("", "\t")
793 ctl.xcheck(err, "encode webhook")
796 case "queuehookretiredlist":
798 > "queuehookretiredlist"
804 filterline := ctl.xread()
805 sortline := ctl.xread()
806 var f queue.HookRetiredFilter
807 xparseJSON(ctl, filterline, &f)
808 var s queue.HookRetiredSort
809 xparseJSON(ctl, sortline, &s)
810 l, err := queue.HookRetiredList(ctx, f, s)
811 ctl.xcheck(err, "listing retired webhooks")
815 fmt.Fprintln(xw, "retired webhooks:")
816 for _, h := range l {
817 var lastAttempt string
818 if len(h.Results) > 0 {
819 lastAttempt = time.Since(h.LastResult().Start).Round(time.Second).String()
825 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)
828 fmt.Fprint(xw, "(none)\n")
832 case "queuehookretiredprint":
834 > "queuehookretiredprint"
840 id, err := strconv.ParseInt(idstr, 10, 64)
842 ctl.xcheck(err, "parsing id")
844 l, err := queue.HookRetiredList(ctx, queue.HookRetiredFilter{IDs: []int64{id}}, queue.HookRetiredSort{})
845 ctl.xcheck(err, "getting retired webhooks")
847 ctl.xcheck(errors.New("not found"), "getting retired webhook")
852 enc := json.NewEncoder(xw)
853 enc.SetIndent("", "\t")
855 ctl.xcheck(err, "encode retired webhook")
858 case "queuesuppresslist":
860 > "queuesuppresslist"
866 account := ctl.xread()
867 l, err := queue.SuppressionList(ctx, account)
868 ctl.xcheck(err, "listing suppressions")
871 fmt.Fprintln(xw, "suppressions (account, address, manual, time added, base adddress, reason):")
872 for _, sup := range l {
877 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)
880 fmt.Fprintln(xw, "(none)")
884 case "queuesuppressadd":
892 account := ctl.xread()
893 address := ctl.xread()
894 _, ok := mox.Conf.Account(account)
896 ctl.xcheck(errors.New("unknown account"), "looking up account")
898 addr, err := smtp.ParseAddress(address)
899 ctl.xcheck(err, "parsing address")
900 sup := webapi.Suppression{
903 Reason: "added through mox cli",
905 err = queue.SuppressionAdd(ctx, addr.Path(), &sup)
906 ctl.xcheck(err, "adding suppression")
909 case "queuesuppressremove":
911 > "queuesuppressremove"
917 account := ctl.xread()
918 address := ctl.xread()
919 addr, err := smtp.ParseAddress(address)
920 ctl.xcheck(err, "parsing address")
921 err = queue.SuppressionRemove(ctx, account, addr.Path())
922 ctl.xcheck(err, "removing suppression")
925 case "queuesuppresslookup":
927 > "queuesuppresslookup"
934 account := ctl.xread()
935 address := ctl.xread()
937 _, ok := mox.Conf.Account(account)
939 ctl.xcheck(errors.New("unknown account"), "looking up account")
942 addr, err := smtp.ParseAddress(address)
943 ctl.xcheck(err, "parsing address")
944 sup, err := queue.SuppressionLookup(ctx, account, addr.Path())
945 ctl.xcheck(err, "looking up suppression")
949 fmt.Fprintln(xw, "not present")
955 fmt.Fprintf(xw, "present\nadded: %s\nmanual: %s\nbase address: %s\nreason: %q\n", sup.Created.Round(time.Second), manual, sup.BaseAddress, sup.Reason)
959 case "importmaildir", "importmbox":
960 mbox := cmd == "importmbox"
961 importctl(ctx, ctl, mbox)
971 domain := ctl.xread()
972 account := ctl.xread()
973 localpart := ctl.xread()
974 d, err := dns.ParseDomain(domain)
975 ctl.xcheck(err, "parsing domain")
976 err = mox.DomainAdd(ctx, d, account, smtp.Localpart(localpart))
977 ctl.xcheck(err, "adding domain")
986 domain := ctl.xread()
987 d, err := dns.ParseDomain(domain)
988 ctl.xcheck(err, "parsing domain")
989 err = mox.DomainRemove(ctx, d)
990 ctl.xcheck(err, "removing domain")
1000 account := ctl.xread()
1001 address := ctl.xread()
1002 err := mox.AccountAdd(ctx, account, address)
1003 ctl.xcheck(err, "adding account")
1012 account := ctl.xread()
1013 err := mox.AccountRemove(ctx, account)
1014 ctl.xcheck(err, "removing account")
1024 address := ctl.xread()
1025 account := ctl.xread()
1026 err := mox.AddressAdd(ctx, address, account)
1027 ctl.xcheck(err, "adding address")
1036 address := ctl.xread()
1037 err := mox.AddressRemove(ctx, address)
1038 ctl.xcheck(err, "removing address")
1048 domain := ctl.xread()
1049 d, err := dns.ParseDomain(domain)
1050 ctl.xcheck(err, "parsing domain")
1051 dc, ok := mox.Conf.Domain(d)
1053 ctl.xcheck(errors.New("no such domain"), "listing aliases")
1057 for _, a := range dc.Aliases {
1058 lp, err := smtp.ParseLocalpart(a.LocalpartStr)
1059 ctl.xcheck(err, "parsing alias localpart")
1060 fmt.Fprintln(w, smtp.NewAddress(lp, a.Domain).Pack(true))
1071 address := ctl.xread()
1072 _, alias, ok := mox.Conf.AccountDestination(address)
1074 ctl.xcheck(errors.New("no such address"), "looking up alias")
1075 } else if alias == nil {
1076 ctl.xcheck(errors.New("address not an alias"), "looking up alias")
1080 fmt.Fprintf(w, "# postpublic %v\n", alias.PostPublic)
1081 fmt.Fprintf(w, "# listmembers %v\n", alias.ListMembers)
1082 fmt.Fprintf(w, "# allowmsgfrom %v\n", alias.AllowMsgFrom)
1083 fmt.Fprintln(w, "# members:")
1084 for _, a := range alias.Addresses {
1096 address := ctl.xread()
1098 addr, err := smtp.ParseAddress(address)
1099 ctl.xcheck(err, "parsing address")
1100 var alias config.Alias
1101 xparseJSON(ctl, line, &alias)
1102 err = mox.AliasAdd(ctx, addr, alias)
1103 ctl.xcheck(err, "adding alias")
1110 > "true" or "false" for postpublic
1111 > "true" or "false" for listmembers
1112 > "true" or "false" for allowmsgfrom
1115 address := ctl.xread()
1116 postpublic := ctl.xread()
1117 listmembers := ctl.xread()
1118 allowmsgfrom := ctl.xread()
1119 addr, err := smtp.ParseAddress(address)
1120 ctl.xcheck(err, "parsing address")
1121 err = mox.DomainSave(ctx, addr.Domain.Name(), func(d *config.Domain) error {
1122 a, ok := d.Aliases[addr.Localpart.String()]
1124 return fmt.Errorf("alias does not exist")
1129 a.PostPublic = false
1133 switch listmembers {
1135 a.ListMembers = false
1137 a.ListMembers = true
1139 switch allowmsgfrom {
1141 a.AllowMsgFrom = false
1143 a.AllowMsgFrom = true
1146 d.Aliases = maps.Clone(d.Aliases)
1147 d.Aliases[addr.Localpart.String()] = a
1150 ctl.xcheck(err, "saving alias")
1159 address := ctl.xread()
1160 addr, err := smtp.ParseAddress(address)
1161 ctl.xcheck(err, "parsing address")
1162 err = mox.AliasRemove(ctx, addr)
1163 ctl.xcheck(err, "removing alias")
1166 case "aliasaddaddr":
1173 address := ctl.xread()
1175 addr, err := smtp.ParseAddress(address)
1176 ctl.xcheck(err, "parsing address")
1177 var addresses []string
1178 xparseJSON(ctl, line, &addresses)
1179 err = mox.AliasAddressesAdd(ctx, addr, addresses)
1180 ctl.xcheck(err, "adding addresses to alias")
1190 address := ctl.xread()
1192 addr, err := smtp.ParseAddress(address)
1193 ctl.xcheck(err, "parsing address")
1194 var addresses []string
1195 xparseJSON(ctl, line, &addresses)
1196 err = mox.AliasAddressesRemove(ctx, addr, addresses)
1197 ctl.xcheck(err, "removing addresses to alias")
1207 l := mox.Conf.LogLevels()
1210 keys = append(keys, k)
1212 sort.Slice(keys, func(i, j int) bool {
1213 return keys[i] < keys[j]
1216 for _, k := range keys {
1221 s += ks + ": " + mlog.LevelStrings[l[k]] + "\n"
1223 ctl.xstreamfrom(strings.NewReader(s))
1225 case "setloglevels":
1229 > level (if empty, log level for pkg will be unset)
1233 levelstr := ctl.xread()
1235 mox.Conf.LogLevelRemove(log, pkg)
1237 level, ok := mlog.Levels[levelstr]
1239 ctl.xerror("bad level")
1241 mox.Conf.LogLevelSet(log, pkg, level)
1251 account := ctl.xread()
1252 acc, err := store.OpenAccount(log, account)
1253 ctl.xcheck(err, "open account")
1257 log.Check(err, "closing account after retraining")
1261 acc.WithWLock(func() {
1262 conf, _ := acc.Conf()
1263 if conf.JunkFilter == nil {
1264 ctl.xcheck(store.ErrNoJunkFilter, "looking for junk filter")
1267 // Remove existing junk filter files.
1268 basePath := mox.DataDirPath("accounts")
1269 dbPath := filepath.Join(basePath, acc.Name, "junkfilter.db")
1270 bloomPath := filepath.Join(basePath, acc.Name, "junkfilter.bloom")
1271 err := os.Remove(dbPath)
1272 log.Check(err, "removing old junkfilter database file", slog.String("path", dbPath))
1273 err = os.Remove(bloomPath)
1274 log.Check(err, "removing old junkfilter bloom filter file", slog.String("path", bloomPath))
1276 // Open junk filter, this creates new files.
1277 jf, _, err := acc.OpenJunkFilter(ctx, log)
1278 ctl.xcheck(err, "open new junk filter")
1284 log.Check(err, "closing junk filter during cleanup")
1287 // Read through messages with junk or nonjunk flag set, and train them.
1288 var total, trained int
1289 q := bstore.QueryDB[store.Message](ctx, acc.DB)
1290 q.FilterEqual("Expunged", false)
1291 err = q.ForEach(func(m store.Message) error {
1293 ok, err := acc.TrainMessage(ctx, log, jf, m)
1299 ctl.xcheck(err, "training messages")
1300 log.Info("retrained messages", slog.Int("total", total), slog.Int("trained", trained))
1302 // Close junk filter, marking success.
1305 ctl.xcheck(err, "closing junk filter")
1309 case "recalculatemailboxcounts":
1311 > "recalculatemailboxcounts"
1316 account := ctl.xread()
1317 acc, err := store.OpenAccount(log, account)
1318 ctl.xcheck(err, "open account")
1322 log.Check(err, "closing account after recalculating mailbox counts")
1329 acc.WithWLock(func() {
1330 var changes []store.Change
1331 err = acc.DB.Write(ctx, func(tx *bstore.Tx) error {
1333 err := bstore.QueryTx[store.Mailbox](tx).ForEach(func(mb store.Mailbox) error {
1334 mc, err := mb.CalculateCounts(tx)
1336 return fmt.Errorf("calculating counts for mailbox %q: %w", mb.Name, err)
1338 totalSize += mc.Size
1340 if !mb.HaveCounts || mc != mb.MailboxCounts {
1341 _, err := fmt.Fprintf(w, "for %s setting new counts %s (was %s)\n", mb.Name, mc, mb.MailboxCounts)
1342 ctl.xcheck(err, "write")
1343 mb.HaveCounts = true
1344 mb.MailboxCounts = mc
1345 if err := tx.Update(&mb); err != nil {
1346 return fmt.Errorf("storing new counts for %q: %v", mb.Name, err)
1348 changes = append(changes, mb.ChangeCounts())
1356 du := store.DiskUsage{ID: 1}
1357 if err := tx.Get(&du); err != nil {
1358 return fmt.Errorf("get disk usage: %v", err)
1360 if du.MessageSize != totalSize {
1361 _, err := fmt.Fprintf(w, "setting new total message size %d (was %d)\n", totalSize, du.MessageSize)
1362 ctl.xcheck(err, "write")
1363 du.MessageSize = totalSize
1364 if err := tx.Update(&du); err != nil {
1365 return fmt.Errorf("update disk usage: %v", err)
1370 ctl.xcheck(err, "write transaction for mailbox counts")
1372 store.BroadcastChanges(acc, changes)
1384 accountOpt := ctl.xread()
1388 var foundProblem bool
1389 const batchSize = 10000
1391 xfixmsgsize := func(accName string) {
1392 acc, err := store.OpenAccount(log, accName)
1393 ctl.xcheck(err, "open account")
1396 log.Check(err, "closing account after fixing message sizes")
1404 acc.WithRLock(func() {
1405 mailboxCounts := map[int64]store.Mailbox{} // For broadcasting.
1407 // Don't process all message in one transaction, we could block the account for too long.
1408 err := acc.DB.Write(ctx, func(tx *bstore.Tx) error {
1409 q := bstore.QueryTx[store.Message](tx)
1410 q.FilterEqual("Expunged", false)
1411 q.FilterGreater("ID", lastID)
1414 return q.ForEach(func(m store.Message) error {
1418 p := acc.MessagePath(m.ID)
1419 st, err := os.Stat(p)
1421 mb := store.Mailbox{ID: m.MailboxID}
1422 if xerr := tx.Get(&mb); xerr != nil {
1423 _, werr := fmt.Fprintf(w, "get mailbox id %d for message with file error: %v\n", mb.ID, xerr)
1424 ctl.xcheck(werr, "write")
1426 _, 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)
1427 ctl.xcheck(werr, "write")
1430 filesize := st.Size()
1431 correctSize := int64(len(m.MsgPrefix)) + filesize
1432 if m.Size == correctSize {
1438 mb := store.Mailbox{ID: m.MailboxID}
1439 if err := tx.Get(&mb); err != nil {
1440 _, werr := fmt.Fprintf(w, "get mailbox id %d for message with file size mismatch: %v\n", mb.ID, err)
1441 ctl.xcheck(werr, "write")
1443 _, 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)
1444 ctl.xcheck(err, "write")
1446 // We assume that the original message size was accounted as stored in the mailbox
1447 // total size. If this isn't correct, the user can always run
1448 // recalculatemailboxcounts.
1450 mb.Size += correctSize
1451 if err := tx.Update(&mb); err != nil {
1452 return fmt.Errorf("update mailbox counts: %v", err)
1454 mailboxCounts[mb.ID] = mb
1456 m.Size = correctSize
1458 mr := acc.MessageReader(m)
1459 part, err := message.EnsurePart(log.Logger, false, mr, m.Size)
1461 _, werr := fmt.Fprintf(w, "parsing message %d again: %v (continuing)\n", m.ID, err)
1462 ctl.xcheck(werr, "write")
1464 m.ParsedBuf, err = json.Marshal(part)
1466 return fmt.Errorf("marshal parsed message: %v", err)
1469 if err := tx.Update(&m); err != nil {
1470 return fmt.Errorf("update message: %v", err)
1476 ctl.xcheck(err, "find and fix wrong message sizes")
1478 var changes []store.Change
1479 for _, mb := range mailboxCounts {
1480 changes = append(changes, mb.ChangeCounts())
1482 store.BroadcastChanges(acc, changes)
1488 _, err = fmt.Fprintf(w, "%d message size(s) fixed for account %s\n", total, accName)
1489 ctl.xcheck(err, "write")
1492 if accountOpt != "" {
1493 xfixmsgsize(accountOpt)
1495 for i, accName := range mox.Conf.Accounts() {
1500 _, err := fmt.Fprintf(w, "%sFixing message sizes in account %s...\n", line, accName)
1501 ctl.xcheck(err, "write")
1502 xfixmsgsize(accName)
1506 _, 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")
1507 ctl.xcheck(err, "write")
1520 accountOpt := ctl.xread()
1524 const batchSize = 100
1526 xreparseAccount := func(accName string) {
1527 acc, err := store.OpenAccount(log, accName)
1528 ctl.xcheck(err, "open account")
1531 log.Check(err, "closing account after reparsing messages")
1538 // Don't process all message in one transaction, we could block the account for too long.
1539 err := acc.DB.Write(ctx, func(tx *bstore.Tx) error {
1540 q := bstore.QueryTx[store.Message](tx)
1541 q.FilterEqual("Expunged", false)
1542 q.FilterGreater("ID", lastID)
1545 return q.ForEach(func(m store.Message) error {
1547 mr := acc.MessageReader(m)
1548 p, err := message.EnsurePart(log.Logger, false, mr, m.Size)
1550 _, err := fmt.Fprintf(w, "parsing message %d: %v (continuing)\n", m.ID, err)
1551 ctl.xcheck(err, "write")
1553 m.ParsedBuf, err = json.Marshal(p)
1555 return fmt.Errorf("marshal parsed message: %v", err)
1559 if err := tx.Update(&m); err != nil {
1560 return fmt.Errorf("update message: %v", err)
1566 ctl.xcheck(err, "update messages with parsed mime structure")
1571 _, err = fmt.Fprintf(w, "%d message(s) reparsed for account %s\n", total, accName)
1572 ctl.xcheck(err, "write")
1575 if accountOpt != "" {
1576 xreparseAccount(accountOpt)
1578 for i, accName := range mox.Conf.Accounts() {
1583 _, err := fmt.Fprintf(w, "%sReparsing account %s...\n", line, accName)
1584 ctl.xcheck(err, "write")
1585 xreparseAccount(accName)
1590 case "reassignthreads":
1598 accountOpt := ctl.xread()
1602 xreassignThreads := func(accName string) {
1603 acc, err := store.OpenAccount(log, accName)
1604 ctl.xcheck(err, "open account")
1607 log.Check(err, "closing account after reassigning threads")
1610 // We don't want to step on an existing upgrade process.
1611 err = acc.ThreadingWait(log)
1612 ctl.xcheck(err, "waiting for threading upgrade to finish")
1613 // todo: should we try to continue if the threading upgrade failed? only if there is a chance it will succeed this time...
1615 // todo: reassigning isn't atomic (in a single transaction), ideally it would be (bstore would need to be able to handle large updates).
1616 const batchSize = 50000
1617 total, err := acc.ResetThreading(ctx, log, batchSize, true)
1618 ctl.xcheck(err, "resetting threading fields")
1619 _, err = fmt.Fprintf(w, "New thread base subject assigned to %d message(s), starting to reassign threads...\n", total)
1620 ctl.xcheck(err, "write")
1622 // Assign threads again. Ideally we would do this in a single transaction, but
1623 // bstore/boltdb cannot handle so many pending changes, so we set a high batchsize.
1624 err = acc.AssignThreads(ctx, log, nil, 0, 50000, w)
1625 ctl.xcheck(err, "reassign threads")
1627 _, err = fmt.Fprintf(w, "Threads reassigned. You should invalidate messages stored at imap clients with the \"mox bumpuidvalidity account [mailbox]\" command.\n")
1628 ctl.xcheck(err, "write")
1631 if accountOpt != "" {
1632 xreassignThreads(accountOpt)
1634 for i, accName := range mox.Conf.Accounts() {
1639 _, err := fmt.Fprintf(w, "%sReassigning threads for account %s...\n", line, accName)
1640 ctl.xcheck(err, "write")
1641 xreassignThreads(accName)
1650 log.Info("unrecognized command", slog.String("cmd", cmd))
1651 ctl.xwrite("unrecognized command")