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/imapserver"
29 "github.com/mjl-/mox/message"
30 "github.com/mjl-/mox/metrics"
31 "github.com/mjl-/mox/mlog"
32 "github.com/mjl-/mox/mox-"
33 "github.com/mjl-/mox/queue"
34 "github.com/mjl-/mox/smtp"
35 "github.com/mjl-/mox/store"
36 "github.com/mjl-/mox/webapi"
39// ctl represents a connection to the ctl unix domain socket of a running mox instance.
40// ctl provides functions to read/write commands/responses/data streams.
42 cmd string // Set for server-side of commands.
44 r *bufio.Reader // Set for first reader.
45 x any // If set, errors are handled by calling panic(x) instead of log.Fatal.
46 log mlog.Log // If set, along with x, logging is done here.
49// xctl opens a ctl connection.
51 p := mox.DataDirPath("ctl")
52 conn, err := net.Dial("unix", p)
54 log.Fatalf("connecting to control socket at %q: %v", p, err)
56 ctl := &ctl{conn: conn}
57 version := ctl.xread()
58 if version != "ctlv0" {
59 log.Fatalf("ctl protocol mismatch, got %q, expected ctlv0", version)
64// Interpret msg as an error.
65// If ctl.x is set, the string is also written to the ctl to be interpreted as error by the other party.
66func (c *ctl) xerror(msg string) {
70 c.log.Debugx("ctl error", fmt.Errorf("%s", msg), slog.String("cmd", c.cmd))
75// Check if err is not nil. If so, handle error through ctl.x or log.Fatal. If
76// ctl.x is set, the error string is written to ctl, to be interpreted as an error
77// by the command reading from ctl.
78func (c *ctl) xcheck(err error, msg string) {
83 log.Fatalf("%s: %s", msg, err)
85 c.log.Debugx(msg, err, slog.String("cmd", c.cmd))
86 fmt.Fprintf(c.conn, "%s: %s\n", msg, err)
90// Read a line and return it without trailing newline.
91func (c *ctl) xread() string {
93 c.r = bufio.NewReader(c.conn)
95 line, err := c.r.ReadString('\n')
96 c.xcheck(err, "read from ctl")
97 return strings.TrimSuffix(line, "\n")
100// Read a line. If not "ok", the string is interpreted as an error.
101func (c *ctl) xreadok() {
108// Write a string, typically a command or parameter.
109func (c *ctl) xwrite(text string) {
110 _, err := fmt.Fprintln(c.conn, text)
111 c.xcheck(err, "write")
114// Write "ok" to indicate success.
115func (c *ctl) xwriteok() {
119// Copy data from a stream from ctl to dst.
120func (c *ctl) xstreamto(dst io.Writer) {
121 _, err := io.Copy(dst, c.reader())
122 c.xcheck(err, "reading message")
125// Copy data from src to a stream to ctl.
126func (c *ctl) xstreamfrom(src io.Reader) {
128 _, err := io.Copy(w, src)
129 c.xcheck(err, "copying")
133// Writer returns an io.Writer for a data stream to ctl.
134// When done writing, caller must call xclose to signal the end of the stream.
135// Behaviour of "x" is copied from ctl.
136func (c *ctl) writer() *ctlwriter {
137 return &ctlwriter{cmd: c.cmd, conn: c.conn, x: c.x, log: c.log}
140// Reader returns an io.Reader for a data stream from ctl.
141// Behaviour of "x" is copied from ctl.
142func (c *ctl) reader() *ctlreader {
144 c.r = bufio.NewReader(c.conn)
146 return &ctlreader{cmd: c.cmd, conn: c.conn, r: c.r, x: c.x, log: c.log}
150Ctlwriter and ctlreader implement the writing and reading a data stream. They
151implement the io.Writer and io.Reader interface. In the protocol below each
152non-data message ends with a newline that is typically stripped when
155Zero or more data transactions:
157 > "123" (for data size) or an error message
159 < "ok" or an error message
161Followed by a end of stream indicated by zero data bytes message:
166type ctlwriter struct {
167 cmd string // Set for server-side of commands.
168 conn net.Conn // Ctl socket from which messages are read.
169 buf []byte // Scratch buffer, for reading response.
170 x any // If not nil, errors in Write and xcheckf are handled with panic(x), otherwise with a log.Fatal.
174func (s *ctlwriter) Write(buf []byte) (int, error) {
175 _, err := fmt.Fprintf(s.conn, "%d\n", len(buf))
176 s.xcheck(err, "write count")
177 _, err = s.conn.Write(buf)
178 s.xcheck(err, "write data")
180 s.buf = make([]byte, 512)
182 n, err := s.conn.Read(s.buf)
183 s.xcheck(err, "reading response to write")
184 line := strings.TrimSuffix(string(s.buf[:n]), "\n")
191func (s *ctlwriter) xerror(msg string) {
195 s.log.Debugx("error", fmt.Errorf("%s", msg), slog.String("cmd", s.cmd))
200func (s *ctlwriter) xcheck(err error, msg string) {
205 log.Fatalf("%s: %s", msg, err)
207 s.log.Debugx(msg, err, slog.String("cmd", s.cmd))
212func (s *ctlwriter) xclose() {
213 _, err := fmt.Fprintf(s.conn, "0\n")
214 s.xcheck(err, "write eof")
217type ctlreader struct {
218 cmd string // Set for server-side of command.
219 conn net.Conn // For writing "ok" after reading.
220 r *bufio.Reader // Buffered ctl socket.
221 err error // If set, returned for each read. can also be io.EOF.
222 npending int // Number of bytes that can still be read until a new count line must be read.
223 x any // If set, errors are handled with panic(x) instead of log.Fatal.
224 log mlog.Log // If x is set, logging goes to log.
227func (s *ctlreader) Read(buf []byte) (N int, Err error) {
232 line, err := s.r.ReadString('\n')
233 s.xcheck(err, "reading count")
234 line = strings.TrimSuffix(line, "\n")
235 n, err := strconv.ParseInt(line, 10, 32)
249 n, err := s.r.Read(buf[:rn])
250 s.xcheck(err, "read from ctl")
253 _, err = fmt.Fprintln(s.conn, "ok")
254 s.xcheck(err, "writing ok after reading")
259func (s *ctlreader) xerror(msg string) {
263 s.log.Debugx("error", fmt.Errorf("%s", msg), slog.String("cmd", s.cmd))
268func (s *ctlreader) xcheck(err error, msg string) {
273 log.Fatalf("%s: %s", msg, err)
275 s.log.Debugx(msg, err, slog.String("cmd", s.cmd))
280// servectl handles requests on the unix domain socket "ctl", e.g. for graceful shutdown, local mail delivery.
281func servectl(ctx context.Context, cid int64, log mlog.Log, conn net.Conn, shutdown func()) {
282 log.Debug("ctl connection")
284 var stop = struct{}{} // Sentinel value for panic and recover.
285 ctl := &ctl{conn: conn, x: stop, log: log}
288 if x == nil || x == stop {
291 log.Error("servectl panic", slog.Any("err", x), slog.String("cmd", ctl.cmd))
293 metrics.PanicInc(metrics.Ctl)
300 servectlcmd(ctx, ctl, cid, shutdown)
304func xparseJSON(ctl *ctl, s string, v any) {
305 dec := json.NewDecoder(strings.NewReader(s))
306 dec.DisallowUnknownFields()
308 ctl.xcheck(err, "parsing from ctl as json")
311func servectlcmd(ctx context.Context, ctl *ctl, cid int64, shutdown func()) {
315 log.Info("ctl command", slog.String("cmd", cmd))
322 /* The protocol, double quoted are literals.
332 a, _, addr, err := store.OpenEmail(log, to, false)
333 ctl.xcheck(err, "lookup destination address")
335 msgFile, err := store.CreateMessageTemp(log, "ctl-deliver")
336 ctl.xcheck(err, "creating temporary message file")
337 defer store.CloseRemoveTempFile(log, msgFile, "deliver message")
338 mw := message.NewWriter(msgFile)
343 ctl.xcheck(err, "syncing message to storage")
346 Received: time.Now(),
351 err := a.DeliverDestination(log, addr, &m, msgFile)
352 ctl.xcheck(err, "delivering message")
353 log.Info("message delivered through ctl", slog.Any("to", to))
357 ctl.xcheck(err, "closing account")
360 case "setaccountpassword":
362 > "setaccountpassword"
368 account := ctl.xread()
371 acc, err := store.OpenAccount(log, account, false)
372 ctl.xcheck(err, "open account")
376 log.Check(err, "closing account after setting password")
380 err = acc.SetPassword(log, pw)
381 ctl.xcheck(err, "setting password")
383 ctl.xcheck(err, "closing account")
387 case "queueholdruleslist":
389 > "queueholdruleslist"
393 l, err := queue.HoldRuleList(ctx)
394 ctl.xcheck(err, "listing hold rules")
397 fmt.Fprintln(xw, "hold rules:")
398 for _, hr := range l {
400 if hr.Account != "" {
401 elems = append(elems, fmt.Sprintf("account %q", hr.Account))
403 var zerodom dns.Domain
404 if hr.SenderDomain != zerodom {
405 elems = append(elems, fmt.Sprintf("sender domain %q", hr.SenderDomain.Name()))
407 if hr.RecipientDomain != zerodom {
408 elems = append(elems, fmt.Sprintf("sender domain %q", hr.RecipientDomain.Name()))
411 fmt.Fprintf(xw, "id %d: all messages\n", hr.ID)
413 fmt.Fprintf(xw, "id %d: %s\n", hr.ID, strings.Join(elems, ", "))
417 fmt.Fprint(xw, "(none)\n")
421 case "queueholdrulesadd":
423 > "queueholdrulesadd"
429 var hr queue.HoldRule
430 hr.Account = ctl.xread()
431 senderdomstr := ctl.xread()
432 rcptdomstr := ctl.xread()
434 hr.SenderDomain, err = dns.ParseDomain(senderdomstr)
435 ctl.xcheck(err, "parsing sender domain")
436 hr.RecipientDomain, err = dns.ParseDomain(rcptdomstr)
437 ctl.xcheck(err, "parsing recipient domain")
438 hr, err = queue.HoldRuleAdd(ctx, log, hr)
439 ctl.xcheck(err, "add hold rule")
442 case "queueholdrulesremove":
444 > "queueholdrulesremove"
449 id, err := strconv.ParseInt(idstr, 10, 64)
450 ctl.xcheck(err, "parsing id")
451 err = queue.HoldRuleRemove(ctx, log, id)
452 ctl.xcheck(err, "remove hold rule")
463 filterline := ctl.xread()
464 sortline := ctl.xread()
466 xparseJSON(ctl, filterline, &f)
468 xparseJSON(ctl, sortline, &s)
469 qmsgs, err := queue.List(ctx, f, s)
470 ctl.xcheck(err, "listing queue")
474 fmt.Fprintln(xw, "messages:")
475 for _, qm := range qmsgs {
476 var lastAttempt string
477 if qm.LastAttempt != nil {
478 lastAttempt = time.Since(*qm.LastAttempt).Round(time.Second).String()
480 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)
483 fmt.Fprint(xw, "(none)\n")
490 > queuefilters as json
496 filterline := ctl.xread()
497 hold := ctl.xread() == "true"
499 xparseJSON(ctl, filterline, &f)
500 count, err := queue.HoldSet(ctx, f, hold)
501 ctl.xcheck(err, "setting on hold status for messages")
503 ctl.xwrite(fmt.Sprintf("%d", count))
505 case "queueschedule":
508 > queuefilters as json
515 filterline := ctl.xread()
516 relnow := ctl.xread()
517 duration := ctl.xread()
519 xparseJSON(ctl, filterline, &f)
520 d, err := time.ParseDuration(duration)
521 ctl.xcheck(err, "parsing duration for next delivery attempt")
524 count, err = queue.NextAttemptAdd(ctx, f, d)
526 count, err = queue.NextAttemptSet(ctx, f, time.Now().Add(d))
528 ctl.xcheck(err, "setting next delivery attempts in queue")
530 ctl.xwrite(fmt.Sprintf("%d", count))
532 case "queuetransport":
535 > queuefilters as json
541 filterline := ctl.xread()
542 transport := ctl.xread()
544 xparseJSON(ctl, filterline, &f)
545 count, err := queue.TransportSet(ctx, f, transport)
546 ctl.xcheck(err, "adding to next delivery attempts in queue")
548 ctl.xwrite(fmt.Sprintf("%d", count))
550 case "queuerequiretls":
553 > queuefilters as json
554 > reqtls (empty string, "true" or "false")
559 filterline := ctl.xread()
560 reqtls := ctl.xread()
571 ctl.xcheck(fmt.Errorf("unknown value %q", reqtls), "parsing value")
574 xparseJSON(ctl, filterline, &f)
575 count, err := queue.RequireTLSSet(ctx, f, req)
576 ctl.xcheck(err, "setting tls requirements on messages in queue")
578 ctl.xwrite(fmt.Sprintf("%d", count))
583 > queuefilters as json
588 filterline := ctl.xread()
590 xparseJSON(ctl, filterline, &f)
591 count, err := queue.Fail(ctx, log, f)
592 ctl.xcheck(err, "marking messages from queue as failed")
594 ctl.xwrite(fmt.Sprintf("%d", count))
599 > queuefilters as json
604 filterline := ctl.xread()
606 xparseJSON(ctl, filterline, &f)
607 count, err := queue.Drop(ctx, log, f)
608 ctl.xcheck(err, "dropping messages from queue")
610 ctl.xwrite(fmt.Sprintf("%d", count))
621 id, err := strconv.ParseInt(idstr, 10, 64)
623 ctl.xcheck(err, "parsing id")
625 mr, err := queue.OpenMessage(ctx, id)
626 ctl.xcheck(err, "opening message")
629 log.Check(err, "closing message from queue")
634 case "queueretiredlist":
642 filterline := ctl.xread()
643 sortline := ctl.xread()
644 var f queue.RetiredFilter
645 xparseJSON(ctl, filterline, &f)
646 var s queue.RetiredSort
647 xparseJSON(ctl, sortline, &s)
648 qmsgs, err := queue.RetiredList(ctx, f, s)
649 ctl.xcheck(err, "listing retired queue")
653 fmt.Fprintln(xw, "retired messages:")
654 for _, qm := range qmsgs {
655 var lastAttempt string
656 if qm.LastAttempt != nil {
657 lastAttempt = time.Since(*qm.LastAttempt).Round(time.Second).String()
663 sender, err := qm.Sender()
664 xcheckf(err, "parsing sender")
665 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)
668 fmt.Fprint(xw, "(none)\n")
672 case "queueretiredprint":
674 > "queueretiredprint"
680 id, err := strconv.ParseInt(idstr, 10, 64)
682 ctl.xcheck(err, "parsing id")
684 l, err := queue.RetiredList(ctx, queue.RetiredFilter{IDs: []int64{id}}, queue.RetiredSort{})
685 ctl.xcheck(err, "getting retired messages")
687 ctl.xcheck(errors.New("not found"), "getting retired message")
692 enc := json.NewEncoder(xw)
693 enc.SetIndent("", "\t")
695 ctl.xcheck(err, "encode retired message")
698 case "queuehooklist":
706 filterline := ctl.xread()
707 sortline := ctl.xread()
708 var f queue.HookFilter
709 xparseJSON(ctl, filterline, &f)
711 xparseJSON(ctl, sortline, &s)
712 hooks, err := queue.HookList(ctx, f, s)
713 ctl.xcheck(err, "listing webhooks")
717 fmt.Fprintln(xw, "webhooks:")
718 for _, h := range hooks {
719 var lastAttempt string
720 if len(h.Results) > 0 {
721 lastAttempt = time.Since(h.LastResult().Start).Round(time.Second).String()
723 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)
726 fmt.Fprint(xw, "(none)\n")
730 case "queuehookschedule":
732 > "queuehookschedule"
733 > hookfilters as json
740 filterline := ctl.xread()
741 relnow := ctl.xread()
742 duration := ctl.xread()
743 var f queue.HookFilter
744 xparseJSON(ctl, filterline, &f)
745 d, err := time.ParseDuration(duration)
746 ctl.xcheck(err, "parsing duration for next delivery attempt")
749 count, err = queue.HookNextAttemptAdd(ctx, f, d)
751 count, err = queue.HookNextAttemptSet(ctx, f, time.Now().Add(d))
753 ctl.xcheck(err, "setting next delivery attempts in queue")
755 ctl.xwrite(fmt.Sprintf("%d", count))
757 case "queuehookcancel":
760 > hookfilters as json
765 filterline := ctl.xread()
766 var f queue.HookFilter
767 xparseJSON(ctl, filterline, &f)
768 count, err := queue.HookCancel(ctx, log, f)
769 ctl.xcheck(err, "canceling webhooks in queue")
771 ctl.xwrite(fmt.Sprintf("%d", count))
773 case "queuehookprint":
781 id, err := strconv.ParseInt(idstr, 10, 64)
783 ctl.xcheck(err, "parsing id")
785 l, err := queue.HookList(ctx, queue.HookFilter{IDs: []int64{id}}, queue.HookSort{})
786 ctl.xcheck(err, "getting webhooks")
788 ctl.xcheck(errors.New("not found"), "getting webhook")
793 enc := json.NewEncoder(xw)
794 enc.SetIndent("", "\t")
796 ctl.xcheck(err, "encode webhook")
799 case "queuehookretiredlist":
801 > "queuehookretiredlist"
807 filterline := ctl.xread()
808 sortline := ctl.xread()
809 var f queue.HookRetiredFilter
810 xparseJSON(ctl, filterline, &f)
811 var s queue.HookRetiredSort
812 xparseJSON(ctl, sortline, &s)
813 l, err := queue.HookRetiredList(ctx, f, s)
814 ctl.xcheck(err, "listing retired webhooks")
818 fmt.Fprintln(xw, "retired webhooks:")
819 for _, h := range l {
820 var lastAttempt string
821 if len(h.Results) > 0 {
822 lastAttempt = time.Since(h.LastResult().Start).Round(time.Second).String()
828 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)
831 fmt.Fprint(xw, "(none)\n")
835 case "queuehookretiredprint":
837 > "queuehookretiredprint"
843 id, err := strconv.ParseInt(idstr, 10, 64)
845 ctl.xcheck(err, "parsing id")
847 l, err := queue.HookRetiredList(ctx, queue.HookRetiredFilter{IDs: []int64{id}}, queue.HookRetiredSort{})
848 ctl.xcheck(err, "getting retired webhooks")
850 ctl.xcheck(errors.New("not found"), "getting retired webhook")
855 enc := json.NewEncoder(xw)
856 enc.SetIndent("", "\t")
858 ctl.xcheck(err, "encode retired webhook")
861 case "queuesuppresslist":
863 > "queuesuppresslist"
869 account := ctl.xread()
870 l, err := queue.SuppressionList(ctx, account)
871 ctl.xcheck(err, "listing suppressions")
874 fmt.Fprintln(xw, "suppressions (account, address, manual, time added, base adddress, reason):")
875 for _, sup := range l {
880 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)
883 fmt.Fprintln(xw, "(none)")
887 case "queuesuppressadd":
895 account := ctl.xread()
896 address := ctl.xread()
897 _, ok := mox.Conf.Account(account)
899 ctl.xcheck(errors.New("unknown account"), "looking up account")
901 addr, err := smtp.ParseAddress(address)
902 ctl.xcheck(err, "parsing address")
903 sup := webapi.Suppression{
906 Reason: "added through mox cli",
908 err = queue.SuppressionAdd(ctx, addr.Path(), &sup)
909 ctl.xcheck(err, "adding suppression")
912 case "queuesuppressremove":
914 > "queuesuppressremove"
920 account := ctl.xread()
921 address := ctl.xread()
922 addr, err := smtp.ParseAddress(address)
923 ctl.xcheck(err, "parsing address")
924 err = queue.SuppressionRemove(ctx, account, addr.Path())
925 ctl.xcheck(err, "removing suppression")
928 case "queuesuppresslookup":
930 > "queuesuppresslookup"
937 account := ctl.xread()
938 address := ctl.xread()
940 _, ok := mox.Conf.Account(account)
942 ctl.xcheck(errors.New("unknown account"), "looking up account")
945 addr, err := smtp.ParseAddress(address)
946 ctl.xcheck(err, "parsing address")
947 sup, err := queue.SuppressionLookup(ctx, account, addr.Path())
948 ctl.xcheck(err, "looking up suppression")
952 fmt.Fprintln(xw, "not present")
958 fmt.Fprintf(xw, "present\nadded: %s\nmanual: %s\nbase address: %s\nreason: %q\n", sup.Created.Round(time.Second), manual, sup.BaseAddress, sup.Reason)
962 case "importmaildir", "importmbox":
963 mbox := cmd == "importmbox"
964 importctl(ctx, ctl, mbox)
969 > disabled as "true" or "false"
976 switch s := ctl.xread(); s {
982 ctl.xcheck(fmt.Errorf("invalid value %q", s), "parsing disabled boolean")
985 domain := ctl.xread()
986 account := ctl.xread()
987 localpart := ctl.xread()
988 d, err := dns.ParseDomain(domain)
989 ctl.xcheck(err, "parsing domain")
990 err = admin.DomainAdd(ctx, disabled, d, account, smtp.Localpart(localpart))
991 ctl.xcheck(err, "adding domain")
1000 domain := ctl.xread()
1001 d, err := dns.ParseDomain(domain)
1002 ctl.xcheck(err, "parsing domain")
1003 err = admin.DomainRemove(ctx, d)
1004 ctl.xcheck(err, "removing domain")
1007 case "domaindisabled":
1014 domain := ctl.xread()
1016 switch s := ctl.xread(); s {
1022 ctl.xerror("bad boolean value")
1024 err := admin.DomainSave(ctx, domain, func(d *config.Domain) error {
1025 d.Disabled = disabled
1028 ctl.xcheck(err, "saving domain")
1038 account := ctl.xread()
1039 address := ctl.xread()
1040 err := admin.AccountAdd(ctx, account, address)
1041 ctl.xcheck(err, "adding account")
1050 account := ctl.xread()
1051 err := admin.AccountRemove(ctx, account)
1052 ctl.xcheck(err, "removing account")
1055 case "accountdisabled":
1059 > message (if empty, then enabled)
1062 account := ctl.xread()
1063 message := ctl.xread()
1065 acc, err := store.OpenAccount(log, account, false)
1066 ctl.xcheck(err, "open account")
1069 log.Check(err, "closing account")
1072 err = admin.AccountSave(ctx, account, func(acc *config.Account) {
1073 acc.LoginDisabled = message
1075 ctl.xcheck(err, "saving account")
1077 err = acc.SessionsClear(ctx, ctl.log)
1078 ctl.xcheck(err, "clearing active web sessions")
1082 case "accountenable":
1088 account := ctl.xread()
1089 err := admin.AccountSave(ctx, account, func(acc *config.Account) {
1090 acc.LoginDisabled = ""
1092 ctl.xcheck(err, "enabling account")
1095 case "tlspubkeylist":
1098 > account (or empty)
1102 accountOpt := ctl.xread()
1103 tlspubkeys, err := store.TLSPublicKeyList(ctx, accountOpt)
1104 ctl.xcheck(err, "list tls public keys")
1107 fmt.Fprintf(xw, "# fingerprint, type, name, account, login address, no imap preauth (%d)\n", len(tlspubkeys))
1108 for _, k := range tlspubkeys {
1109 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)
1113 case "tlspubkeyget":
1122 < noimappreauth (true/false)
1126 tlspubkey, err := store.TLSPublicKeyGet(ctx, fp)
1127 ctl.xcheck(err, "looking tls public key")
1129 ctl.xwrite(tlspubkey.Type)
1130 ctl.xwrite(tlspubkey.Name)
1131 ctl.xwrite(tlspubkey.Account)
1132 ctl.xwrite(tlspubkey.LoginAddress)
1133 ctl.xwrite(fmt.Sprintf("%v", tlspubkey.NoIMAPPreauth))
1134 ctl.xstreamfrom(bytes.NewReader(tlspubkey.CertDER))
1136 case "tlspubkeyadd":
1141 > noimappreauth (true/false)
1145 loginAddress := ctl.xread()
1147 noimappreauth := ctl.xread()
1148 if noimappreauth != "true" && noimappreauth != "false" {
1149 ctl.xcheck(fmt.Errorf("bad value %q", noimappreauth), "parsing noimappreauth")
1153 tlspubkey, err := store.ParseTLSPublicKeyCert(b.Bytes())
1154 ctl.xcheck(err, "parsing certificate")
1156 tlspubkey.Name = name
1158 acc, _, _, err := store.OpenEmail(ctl.log, loginAddress, false)
1159 ctl.xcheck(err, "open account for address")
1162 ctl.log.Check(err, "close account")
1164 tlspubkey.Account = acc.Name
1165 tlspubkey.LoginAddress = loginAddress
1166 tlspubkey.NoIMAPPreauth = noimappreauth == "true"
1168 err = store.TLSPublicKeyAdd(ctx, &tlspubkey)
1169 ctl.xcheck(err, "adding tls public key")
1179 err := store.TLSPublicKeyRemove(ctx, fp)
1180 ctl.xcheck(err, "removing tls public key")
1190 address := ctl.xread()
1191 account := ctl.xread()
1192 err := admin.AddressAdd(ctx, address, account)
1193 ctl.xcheck(err, "adding address")
1202 address := ctl.xread()
1203 err := admin.AddressRemove(ctx, address)
1204 ctl.xcheck(err, "removing address")
1214 domain := ctl.xread()
1215 d, err := dns.ParseDomain(domain)
1216 ctl.xcheck(err, "parsing domain")
1217 dc, ok := mox.Conf.Domain(d)
1219 ctl.xcheck(errors.New("no such domain"), "listing aliases")
1223 for _, a := range dc.Aliases {
1224 lp, err := smtp.ParseLocalpart(a.LocalpartStr)
1225 ctl.xcheck(err, "parsing alias localpart")
1226 fmt.Fprintln(w, smtp.NewAddress(lp, a.Domain).Pack(true))
1237 address := ctl.xread()
1238 _, alias, ok := mox.Conf.AccountDestination(address)
1240 ctl.xcheck(errors.New("no such address"), "looking up alias")
1241 } else if alias == nil {
1242 ctl.xcheck(errors.New("address not an alias"), "looking up alias")
1246 fmt.Fprintf(w, "# postpublic %v\n", alias.PostPublic)
1247 fmt.Fprintf(w, "# listmembers %v\n", alias.ListMembers)
1248 fmt.Fprintf(w, "# allowmsgfrom %v\n", alias.AllowMsgFrom)
1249 fmt.Fprintln(w, "# members:")
1250 for _, a := range alias.Addresses {
1262 address := ctl.xread()
1264 addr, err := smtp.ParseAddress(address)
1265 ctl.xcheck(err, "parsing address")
1266 var alias config.Alias
1267 xparseJSON(ctl, line, &alias)
1268 err = admin.AliasAdd(ctx, addr, alias)
1269 ctl.xcheck(err, "adding alias")
1276 > "true" or "false" for postpublic
1277 > "true" or "false" for listmembers
1278 > "true" or "false" for allowmsgfrom
1281 address := ctl.xread()
1282 postpublic := ctl.xread()
1283 listmembers := ctl.xread()
1284 allowmsgfrom := ctl.xread()
1285 addr, err := smtp.ParseAddress(address)
1286 ctl.xcheck(err, "parsing address")
1287 err = admin.DomainSave(ctx, addr.Domain.Name(), func(d *config.Domain) error {
1288 a, ok := d.Aliases[addr.Localpart.String()]
1290 return fmt.Errorf("alias does not exist")
1295 a.PostPublic = false
1299 switch listmembers {
1301 a.ListMembers = false
1303 a.ListMembers = true
1305 switch allowmsgfrom {
1307 a.AllowMsgFrom = false
1309 a.AllowMsgFrom = true
1312 d.Aliases = maps.Clone(d.Aliases)
1313 d.Aliases[addr.Localpart.String()] = a
1316 ctl.xcheck(err, "saving alias")
1325 address := ctl.xread()
1326 addr, err := smtp.ParseAddress(address)
1327 ctl.xcheck(err, "parsing address")
1328 err = admin.AliasRemove(ctx, addr)
1329 ctl.xcheck(err, "removing alias")
1332 case "aliasaddaddr":
1339 address := ctl.xread()
1341 addr, err := smtp.ParseAddress(address)
1342 ctl.xcheck(err, "parsing address")
1343 var addresses []string
1344 xparseJSON(ctl, line, &addresses)
1345 err = admin.AliasAddressesAdd(ctx, addr, addresses)
1346 ctl.xcheck(err, "adding addresses to alias")
1356 address := ctl.xread()
1358 addr, err := smtp.ParseAddress(address)
1359 ctl.xcheck(err, "parsing address")
1360 var addresses []string
1361 xparseJSON(ctl, line, &addresses)
1362 err = admin.AliasAddressesRemove(ctx, addr, addresses)
1363 ctl.xcheck(err, "removing addresses to alias")
1373 l := mox.Conf.LogLevels()
1376 keys = append(keys, k)
1378 sort.Slice(keys, func(i, j int) bool {
1379 return keys[i] < keys[j]
1382 for _, k := range keys {
1387 s += ks + ": " + mlog.LevelStrings[l[k]] + "\n"
1389 ctl.xstreamfrom(strings.NewReader(s))
1391 case "setloglevels":
1395 > level (if empty, log level for pkg will be unset)
1399 levelstr := ctl.xread()
1401 mox.Conf.LogLevelRemove(log, pkg)
1403 level, ok := mlog.Levels[levelstr]
1405 ctl.xerror("bad level")
1407 mox.Conf.LogLevelSet(log, pkg, level)
1417 account := ctl.xread()
1419 xretrain := func(name string) {
1420 acc, err := store.OpenAccount(log, name, false)
1421 ctl.xcheck(err, "open account")
1425 log.Check(err, "closing account after retraining")
1429 // 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?
1431 acc.WithWLock(func() {
1432 conf, _ := acc.Conf()
1433 if conf.JunkFilter == nil {
1434 ctl.xcheck(store.ErrNoJunkFilter, "looking for junk filter")
1437 // Remove existing junk filter files.
1438 basePath := mox.DataDirPath("accounts")
1439 dbPath := filepath.Join(basePath, acc.Name, "junkfilter.db")
1440 bloomPath := filepath.Join(basePath, acc.Name, "junkfilter.bloom")
1441 err := os.Remove(dbPath)
1442 log.Check(err, "removing old junkfilter database file", slog.String("path", dbPath))
1443 err = os.Remove(bloomPath)
1444 log.Check(err, "removing old junkfilter bloom filter file", slog.String("path", bloomPath))
1446 // Open junk filter, this creates new files.
1447 jf, _, err := acc.OpenJunkFilter(ctx, log)
1448 ctl.xcheck(err, "open new junk filter")
1454 log.Check(err, "closing junk filter during cleanup")
1457 // Read through messages with junk or nonjunk flag set, and train them.
1458 var total, trained int
1459 q := bstore.QueryDB[store.Message](ctx, acc.DB)
1460 q.FilterEqual("Expunged", false)
1461 err = q.ForEach(func(m store.Message) error {
1463 ok, err := acc.TrainMessage(ctx, log, jf, m)
1469 ctl.xcheck(err, "training messages")
1470 log.Info("retrained messages", slog.Int("total", total), slog.Int("trained", trained))
1472 // Close junk filter, marking success.
1475 ctl.xcheck(err, "closing junk filter")
1480 for _, name := range mox.Conf.Accounts() {
1488 case "recalculatemailboxcounts":
1490 > "recalculatemailboxcounts"
1495 account := ctl.xread()
1496 acc, err := store.OpenAccount(log, account, false)
1497 ctl.xcheck(err, "open account")
1501 log.Check(err, "closing account after recalculating mailbox counts")
1508 acc.WithWLock(func() {
1509 var changes []store.Change
1510 err = acc.DB.Write(ctx, func(tx *bstore.Tx) error {
1512 err := bstore.QueryTx[store.Mailbox](tx).ForEach(func(mb store.Mailbox) error {
1513 mc, err := mb.CalculateCounts(tx)
1515 return fmt.Errorf("calculating counts for mailbox %q: %w", mb.Name, err)
1517 totalSize += mc.Size
1519 if !mb.HaveCounts || mc != mb.MailboxCounts {
1520 _, err := fmt.Fprintf(w, "for %s setting new counts %s (was %s)\n", mb.Name, mc, mb.MailboxCounts)
1521 ctl.xcheck(err, "write")
1522 mb.HaveCounts = true
1523 mb.MailboxCounts = mc
1524 if err := tx.Update(&mb); err != nil {
1525 return fmt.Errorf("storing new counts for %q: %v", mb.Name, err)
1527 changes = append(changes, mb.ChangeCounts())
1535 du := store.DiskUsage{ID: 1}
1536 if err := tx.Get(&du); err != nil {
1537 return fmt.Errorf("get disk usage: %v", err)
1539 if du.MessageSize != totalSize {
1540 _, err := fmt.Fprintf(w, "setting new total message size %d (was %d)\n", totalSize, du.MessageSize)
1541 ctl.xcheck(err, "write")
1542 du.MessageSize = totalSize
1543 if err := tx.Update(&du); err != nil {
1544 return fmt.Errorf("update disk usage: %v", err)
1549 ctl.xcheck(err, "write transaction for mailbox counts")
1551 store.BroadcastChanges(acc, changes)
1563 accountOpt := ctl.xread()
1567 var foundProblem bool
1568 const batchSize = 10000
1570 xfixmsgsize := func(accName string) {
1571 acc, err := store.OpenAccount(log, accName, false)
1572 ctl.xcheck(err, "open account")
1575 log.Check(err, "closing account after fixing message sizes")
1583 acc.WithRLock(func() {
1584 mailboxCounts := map[int64]store.Mailbox{} // For broadcasting.
1586 // Don't process all message in one transaction, we could block the account for too long.
1587 err := acc.DB.Write(ctx, func(tx *bstore.Tx) error {
1588 q := bstore.QueryTx[store.Message](tx)
1589 q.FilterEqual("Expunged", false)
1590 q.FilterGreater("ID", lastID)
1593 return q.ForEach(func(m store.Message) error {
1597 p := acc.MessagePath(m.ID)
1598 st, err := os.Stat(p)
1600 mb := store.Mailbox{ID: m.MailboxID}
1601 if xerr := tx.Get(&mb); xerr != nil {
1602 _, werr := fmt.Fprintf(w, "get mailbox id %d for message with file error: %v\n", mb.ID, xerr)
1603 ctl.xcheck(werr, "write")
1605 _, 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)
1606 ctl.xcheck(werr, "write")
1609 filesize := st.Size()
1610 correctSize := int64(len(m.MsgPrefix)) + filesize
1611 if m.Size == correctSize {
1617 mb := store.Mailbox{ID: m.MailboxID}
1618 if err := tx.Get(&mb); err != nil {
1619 _, werr := fmt.Fprintf(w, "get mailbox id %d for message with file size mismatch: %v\n", mb.ID, err)
1620 ctl.xcheck(werr, "write")
1622 _, 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)
1623 ctl.xcheck(err, "write")
1625 // We assume that the original message size was accounted as stored in the mailbox
1626 // total size. If this isn't correct, the user can always run
1627 // recalculatemailboxcounts.
1629 mb.Size += correctSize
1630 if err := tx.Update(&mb); err != nil {
1631 return fmt.Errorf("update mailbox counts: %v", err)
1633 mailboxCounts[mb.ID] = mb
1635 m.Size = correctSize
1637 mr := acc.MessageReader(m)
1638 part, err := message.EnsurePart(log.Logger, false, mr, m.Size)
1640 _, werr := fmt.Fprintf(w, "parsing message %d again: %v (continuing)\n", m.ID, err)
1641 ctl.xcheck(werr, "write")
1643 m.ParsedBuf, err = json.Marshal(part)
1645 return fmt.Errorf("marshal parsed message: %v", err)
1648 if err := tx.Update(&m); err != nil {
1649 return fmt.Errorf("update message: %v", err)
1655 ctl.xcheck(err, "find and fix wrong message sizes")
1657 var changes []store.Change
1658 for _, mb := range mailboxCounts {
1659 changes = append(changes, mb.ChangeCounts())
1661 store.BroadcastChanges(acc, changes)
1667 _, err = fmt.Fprintf(w, "%d message size(s) fixed for account %s\n", total, accName)
1668 ctl.xcheck(err, "write")
1671 if accountOpt != "" {
1672 xfixmsgsize(accountOpt)
1674 for i, accName := range mox.Conf.Accounts() {
1679 _, err := fmt.Fprintf(w, "%sFixing message sizes in account %s...\n", line, accName)
1680 ctl.xcheck(err, "write")
1681 xfixmsgsize(accName)
1685 _, 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")
1686 ctl.xcheck(err, "write")
1699 accountOpt := ctl.xread()
1703 const batchSize = 100
1705 xreparseAccount := func(accName string) {
1706 acc, err := store.OpenAccount(log, accName, false)
1707 ctl.xcheck(err, "open account")
1710 log.Check(err, "closing account after reparsing messages")
1717 // Don't process all message in one transaction, we could block the account for too long.
1718 err := acc.DB.Write(ctx, func(tx *bstore.Tx) error {
1719 q := bstore.QueryTx[store.Message](tx)
1720 q.FilterEqual("Expunged", false)
1721 q.FilterGreater("ID", lastID)
1724 return q.ForEach(func(m store.Message) error {
1726 mr := acc.MessageReader(m)
1727 p, err := message.EnsurePart(log.Logger, false, mr, m.Size)
1729 _, err := fmt.Fprintf(w, "parsing message %d: %v (continuing)\n", m.ID, err)
1730 ctl.xcheck(err, "write")
1732 m.ParsedBuf, err = json.Marshal(p)
1734 return fmt.Errorf("marshal parsed message: %v", err)
1738 if err := tx.Update(&m); err != nil {
1739 return fmt.Errorf("update message: %v", err)
1745 ctl.xcheck(err, "update messages with parsed mime structure")
1750 _, err = fmt.Fprintf(w, "%d message(s) reparsed for account %s\n", total, accName)
1751 ctl.xcheck(err, "write")
1754 if accountOpt != "" {
1755 xreparseAccount(accountOpt)
1757 for i, accName := range mox.Conf.Accounts() {
1762 _, err := fmt.Fprintf(w, "%sReparsing account %s...\n", line, accName)
1763 ctl.xcheck(err, "write")
1764 xreparseAccount(accName)
1769 case "reassignthreads":
1777 accountOpt := ctl.xread()
1781 xreassignThreads := func(accName string) {
1782 acc, err := store.OpenAccount(log, accName, false)
1783 ctl.xcheck(err, "open account")
1786 log.Check(err, "closing account after reassigning threads")
1789 // We don't want to step on an existing upgrade process.
1790 err = acc.ThreadingWait(log)
1791 ctl.xcheck(err, "waiting for threading upgrade to finish")
1792 // todo: should we try to continue if the threading upgrade failed? only if there is a chance it will succeed this time...
1794 // todo: reassigning isn't atomic (in a single transaction), ideally it would be (bstore would need to be able to handle large updates).
1795 const batchSize = 50000
1796 total, err := acc.ResetThreading(ctx, log, batchSize, true)
1797 ctl.xcheck(err, "resetting threading fields")
1798 _, err = fmt.Fprintf(w, "New thread base subject assigned to %d message(s), starting to reassign threads...\n", total)
1799 ctl.xcheck(err, "write")
1801 // Assign threads again. Ideally we would do this in a single transaction, but
1802 // bstore/boltdb cannot handle so many pending changes, so we set a high batchsize.
1803 err = acc.AssignThreads(ctx, log, nil, 0, 50000, w)
1804 ctl.xcheck(err, "reassign threads")
1806 _, err = fmt.Fprintf(w, "Threads reassigned. You should invalidate messages stored at imap clients with the \"mox bumpuidvalidity account [mailbox]\" command.\n")
1807 ctl.xcheck(err, "write")
1810 if accountOpt != "" {
1811 xreassignThreads(accountOpt)
1813 for i, accName := range mox.Conf.Accounts() {
1818 _, err := fmt.Fprintf(w, "%sReassigning threads for account %s...\n", line, accName)
1819 ctl.xcheck(err, "write")
1820 xreassignThreads(accName)
1835 address := ctl.xread()
1837 imapserver.ServeConnPreauth("(imapserve)", cid, ctl.conn, address)
1838 ctl.log.Debug("imap connection finished")
1841 log.Info("unrecognized command", slog.String("cmd", cmd))
1842 ctl.xwrite("unrecognized command")