1// Package queue is in charge of outgoing messages, queueing them when submitted,
2// attempting a first delivery over SMTP, retrying with backoff and sending DSNs
3// for delayed or failed deliveries.
21 "golang.org/x/net/proxy"
23 "github.com/prometheus/client_golang/prometheus"
24 "github.com/prometheus/client_golang/prometheus/promauto"
26 "github.com/mjl-/bstore"
28 "github.com/mjl-/mox/config"
29 "github.com/mjl-/mox/dns"
30 "github.com/mjl-/mox/dsn"
31 "github.com/mjl-/mox/metrics"
32 "github.com/mjl-/mox/mlog"
33 "github.com/mjl-/mox/mox-"
34 "github.com/mjl-/mox/moxio"
35 "github.com/mjl-/mox/smtp"
36 "github.com/mjl-/mox/smtpclient"
37 "github.com/mjl-/mox/store"
38 "github.com/mjl-/mox/tlsrpt"
39 "github.com/mjl-/mox/tlsrptdb"
40 "github.com/mjl-/mox/webapi"
41 "github.com/mjl-/mox/webhook"
44// ErrFromID indicate a fromid was present when adding a message to the queue, but
46var ErrFromID = errors.New("fromid not unique")
49 metricConnection = promauto.NewCounterVec(
50 prometheus.CounterOpts{
51 Name: "mox_queue_connection_total",
52 Help: "Queue client connections, outgoing.",
55 "result", // "ok", "timeout", "canceled", "error"
58 metricDelivery = promauto.NewHistogramVec(
59 prometheus.HistogramOpts{
60 Name: "mox_queue_delivery_duration_seconds",
61 Help: "SMTP client delivery attempt to single host.",
62 Buckets: []float64{0.01, 0.05, 0.100, 0.5, 1, 5, 10, 20, 30, 60, 120},
65 "attempt", // Number of attempts.
66 "transport", // empty for default direct delivery.
67 "tlsmode", // immediate, requiredstarttls, opportunistic, skip (from smtpclient.TLSMode), with optional +mtasts and/or +dane.
68 "result", // ok, timeout, canceled, temperror, permerror, error
71 metricHold = promauto.NewGauge(
73 Name: "mox_queue_hold",
74 Help: "Messages in queue that are on hold.",
79var jitter = mox.NewPseudoRand()
81var DBTypes = []any{Msg{}, HoldRule{}, MsgRetired{}, webapi.Suppression{}, Hook{}, HookRetired{}} // Types stored in DB.
82var DB *bstore.DB // Exported for making backups.
84// Allow requesting delivery starting from up to this interval from time of submission.
85const FutureReleaseIntervalMax = 60 * 24 * time.Hour
87// Set for mox localserve, to prevent queueing.
90// HoldRule is a set of conditions that cause a matching message to be marked as on
91// hold when it is queued. All-empty conditions matches all messages, effectively
92// pausing the entire queue.
96 SenderDomain dns.Domain
97 RecipientDomain dns.Domain
98 SenderDomainStr string // Unicode.
99 RecipientDomainStr string // Unicode.
102func (pr HoldRule) All() bool {
104 return pr == HoldRule{}
107func (pr HoldRule) matches(m Msg) bool {
108 return pr.All() || pr.Account == m.SenderAccount || pr.SenderDomainStr == m.SenderDomainStr || pr.RecipientDomainStr == m.RecipientDomainStr
111// Msg is a message in the queue.
113// Use MakeMsg to make a message with fields that Add needs. Add will further set
114// queueing related fields.
118 // A message for multiple recipients will get a BaseID that is identical to the
119 // first Msg.ID queued. The message contents will be identical for each recipient,
120 // including MsgPrefix. If other properties are identical too, including recipient
121 // domain, multiple Msgs may be delivered in a single SMTP transaction. For
122 // messages with a single recipient, this field will be 0.
123 BaseID int64 `bstore:"index"`
125 Queued time.Time `bstore:"default now"`
126 Hold bool // If set, delivery won't be attempted.
127 SenderAccount string // Failures are delivered back to this local account. Also used for routing.
128 SenderLocalpart smtp.Localpart // Should be a local user and domain.
129 SenderDomain dns.IPDomain
130 SenderDomainStr string // For filtering, unicode.
131 FromID string // For transactional messages, used to match later DSNs.
132 RecipientLocalpart smtp.Localpart // Typically a remote user and domain.
133 RecipientDomain dns.IPDomain
134 RecipientDomainStr string // For filtering, unicode domain. Can also contain ip enclosed in [].
135 Attempts int // Next attempt is based on last attempt and exponential back off based on attempts.
136 MaxAttempts int // Max number of attempts before giving up. If 0, then the default of 8 attempts is used instead.
137 DialedIPs map[string][]net.IP // For each host, the IPs that were dialed. Used for IP selection for later attempts.
138 NextAttempt time.Time // For scheduling.
139 LastAttempt *time.Time
142 Has8bit bool // Whether message contains bytes with high bit set, determines whether 8BITMIME SMTP extension is needed.
143 SMTPUTF8 bool // Whether message requires use of SMTPUTF8.
144 IsDMARCReport bool // Delivery failures for DMARC reports are handled differently.
145 IsTLSReport bool // Delivery failures for TLS reports are handled differently.
146 Size int64 // Full size of message, combined MsgPrefix with contents of message file.
147 MessageID string // Message-ID header, including <>. Used when composing a DSN, in its References header.
148 MsgPrefix []byte // Data to send before the contents from the file, typically with headers like DKIM-Signature.
149 Subject string // For context about delivery.
151 // If set, this message is a DSN and this is a version using utf-8, for the case
152 // the remote MTA supports smtputf8. In this case, Size and MsgPrefix are not
156 // If non-empty, the transport to use for this message. Can be set through cli or
157 // admin interface. If empty (the default for a submitted message), regular routing
161 // RequireTLS influences TLS verification during delivery.
163 // If nil, the recipient domain policy is followed (MTA-STS and/or DANE), falling
164 // back to optional opportunistic non-verified STARTTLS.
166 // If RequireTLS is true (through SMTP REQUIRETLS extension or webmail submit),
167 // MTA-STS or DANE is required, as well as REQUIRETLS support by the next hop
170 // If RequireTLS is false (through messag header "TLS-Required: No"), the recipient
171 // domain's policy is ignored if it does not lead to a successful TLS connection,
172 // i.e. falling back to SMTP delivery with unverified STARTTLS or plain text.
176 // For DSNs, where the original FUTURERELEASE value must be included as per-message
177 // field. This field should be of the form "for;" plus interval, or "until;" plus
179 FutureReleaseRequest string
182 Extra map[string]string // Extra information, for transactional email.
185// MsgResult is the result (or work in progress) of a delivery attempt.
186type MsgResult struct {
188 Duration time.Duration
193 // todo: store smtp trace for failed deliveries for debugging, perhaps also for successful deliveries.
196// Stored in MsgResult.Error while delivery is in progress. Replaced after success/error.
197const resultErrorDelivering = "delivering..."
199// markResult updates/adds a delivery result.
200func (m *Msg) markResult(code int, secode string, errmsg string, success bool) {
201 if len(m.Results) == 0 || m.Results[len(m.Results)-1].Error != resultErrorDelivering {
202 m.Results = append(m.Results, MsgResult{Start: time.Now()})
204 result := &m.Results[len(m.Results)-1]
205 result.Duration = time.Since(result.Start)
207 result.Secode = secode
208 result.Error = errmsg
209 result.Success = success
212// LastResult returns the last result entry, or an empty result.
213func (m *Msg) LastResult() MsgResult {
214 if len(m.Results) == 0 {
215 return MsgResult{Start: time.Now()}
217 return m.Results[len(m.Results)-1]
220// Sender of message as used in MAIL FROM.
221func (m Msg) Sender() smtp.Path {
222 return smtp.Path{Localpart: m.SenderLocalpart, IPDomain: m.SenderDomain}
225// Recipient of message as used in RCPT TO.
226func (m Msg) Recipient() smtp.Path {
227 return smtp.Path{Localpart: m.RecipientLocalpart, IPDomain: m.RecipientDomain}
230// MessagePath returns the path where the message is stored.
231func (m Msg) MessagePath() string {
232 return mox.DataDirPath(filepath.Join("queue", store.MessagePath(m.ID)))
235// todo: store which transport (if any) was actually used in MsgResult, based on routes.
237// Retired returns a MsgRetired for the message, for history of deliveries.
238func (m Msg) Retired(success bool, t, keepUntil time.Time) MsgRetired {
243 SenderAccount: m.SenderAccount,
244 SenderLocalpart: m.SenderLocalpart,
245 SenderDomainStr: m.SenderDomainStr,
247 RecipientLocalpart: m.RecipientLocalpart,
248 RecipientDomain: m.RecipientDomain,
249 RecipientDomainStr: m.RecipientDomainStr,
250 Attempts: m.Attempts,
251 MaxAttempts: m.MaxAttempts,
252 DialedIPs: m.DialedIPs,
253 LastAttempt: m.LastAttempt,
256 SMTPUTF8: m.SMTPUTF8,
257 IsDMARCReport: m.IsDMARCReport,
258 IsTLSReport: m.IsTLSReport,
260 MessageID: m.MessageID,
262 Transport: m.Transport,
263 RequireTLS: m.RequireTLS,
264 FutureReleaseRequest: m.FutureReleaseRequest,
267 RecipientAddress: smtp.Path{Localpart: m.RecipientLocalpart, IPDomain: m.RecipientDomain}.XString(true),
270 KeepUntil: keepUntil,
274// MsgRetired is a message for which delivery completed, either successful,
275// failed/canceled. Retired messages are only stored if so configured, and will be
276// cleaned up after the configured period.
277type MsgRetired struct {
278 ID int64 // Same ID as it was as Msg.ID.
282 SenderAccount string // Failures are delivered back to this local account. Also used for routing.
283 SenderLocalpart smtp.Localpart // Should be a local user and domain.
284 SenderDomainStr string // For filtering, unicode.
285 FromID string `bstore:"index"` // Used to match DSNs.
286 RecipientLocalpart smtp.Localpart // Typically a remote user and domain.
287 RecipientDomain dns.IPDomain
288 RecipientDomainStr string // For filtering, unicode.
289 Attempts int // Next attempt is based on last attempt and exponential back off based on attempts.
290 MaxAttempts int // Max number of attempts before giving up. If 0, then the default of 8 attempts is used instead.
291 DialedIPs map[string][]net.IP // For each host, the IPs that were dialed. Used for IP selection for later attempts.
292 LastAttempt *time.Time
295 Has8bit bool // Whether message contains bytes with high bit set, determines whether 8BITMIME SMTP extension is needed.
296 SMTPUTF8 bool // Whether message requires use of SMTPUTF8.
297 IsDMARCReport bool // Delivery failures for DMARC reports are handled differently.
298 IsTLSReport bool // Delivery failures for TLS reports are handled differently.
299 Size int64 // Full size of message, combined MsgPrefix with contents of message file.
300 MessageID string // Used when composing a DSN, in its References header.
301 Subject string // For context about delivery.
305 FutureReleaseRequest string
307 Extra map[string]string // Extra information, for transactional email.
309 LastActivity time.Time `bstore:"index"`
310 RecipientAddress string `bstore:"index RecipientAddress+LastActivity"`
311 Success bool // Whether delivery to next hop succeeded.
312 KeepUntil time.Time `bstore:"index"`
315// Sender of message as used in MAIL FROM.
316func (m MsgRetired) Sender() (path smtp.Path, err error) {
317 path.Localpart = m.RecipientLocalpart
318 if strings.HasPrefix(m.SenderDomainStr, "[") && strings.HasSuffix(m.SenderDomainStr, "]") {
319 s := m.SenderDomainStr[1 : len(m.SenderDomainStr)-1]
320 path.IPDomain.IP = net.ParseIP(s)
321 if path.IPDomain.IP == nil {
322 err = fmt.Errorf("parsing ip address %q: %v", s, err)
325 path.IPDomain.Domain, err = dns.ParseDomain(m.SenderDomainStr)
330// Recipient of message as used in RCPT TO.
331func (m MsgRetired) Recipient() smtp.Path {
332 return smtp.Path{Localpart: m.RecipientLocalpart, IPDomain: m.RecipientDomain}
335// LastResult returns the last result entry, or an empty result.
336func (m MsgRetired) LastResult() MsgResult {
337 if len(m.Results) == 0 {
340 return m.Results[len(m.Results)-1]
343// Init opens the queue database without starting delivery.
345 qpath := mox.DataDirPath(filepath.FromSlash("queue/index.db"))
346 os.MkdirAll(filepath.Dir(qpath), 0770)
348 if _, err := os.Stat(qpath); err != nil && os.IsNotExist(err) {
353 log := mlog.New("queue", nil)
354 opts := bstore.Options{Timeout: 5 * time.Second, Perm: 0660, RegisterLogger: log.Logger}
355 DB, err = bstore.Open(mox.Shutdown, qpath, &opts, DBTypes...)
357 err = DB.Read(mox.Shutdown, func(tx *bstore.Tx) error {
358 return metricHoldUpdate(tx)
365 return fmt.Errorf("open queue database: %s", err)
370// When we update the gauge, we just get the full current value, not try to account
372func metricHoldUpdate(tx *bstore.Tx) error {
373 count, err := bstore.QueryTx[Msg](tx).FilterNonzero(Msg{Hold: true}).Count()
375 return fmt.Errorf("querying messages on hold for metric: %v", err)
377 metricHold.Set(float64(count))
381// Shutdown closes the queue database. The delivery process isn't stopped. For tests only.
385 mlog.New("queue", nil).Errorx("closing queue db", err)
390// todo: the filtering & sorting can use improvements. too much duplicated code (variants between {Msg,Hook}{,Retired}. Sort has pagination fields, some untyped.
392// Filter filters messages to list or operate on. Used by admin web interface
395// Only non-empty/non-zero values are applied to the filter. Leaving all fields
396// empty/zero matches all messages.
404 Submitted string // Whether submitted before/after a time relative to now. ">$duration" or "<$duration", also with "now" for duration.
405 NextAttempt string // ">$duration" or "<$duration", also with "now" for duration.
409func (f Filter) apply(q *bstore.Query[Msg]) error {
413 applyTime := func(field string, s string) error {
416 if strings.HasPrefix(s, "<") {
418 } else if !strings.HasPrefix(s, ">") {
419 return fmt.Errorf(`must start with "<" for before or ">" for after a duration`)
421 s = strings.TrimSpace(s[1:])
425 } else if d, err := time.ParseDuration(s); err != nil {
426 return fmt.Errorf("parsing duration %q: %v", orig, err)
428 t = time.Now().Add(d)
431 q.FilterLess(field, t)
433 q.FilterGreater(field, t)
438 q.FilterEqual("Hold", *f.Hold)
440 if f.Submitted != "" {
441 if err := applyTime("Queued", f.Submitted); err != nil {
442 return fmt.Errorf("applying filter for submitted: %v", err)
445 if f.NextAttempt != "" {
446 if err := applyTime("NextAttempt", f.NextAttempt); err != nil {
447 return fmt.Errorf("applying filter for next attempt: %v", err)
451 q.FilterNonzero(Msg{SenderAccount: f.Account})
453 if f.Transport != nil {
454 q.FilterEqual("Transport", *f.Transport)
456 if f.From != "" || f.To != "" {
457 q.FilterFn(func(m Msg) bool {
458 return f.From != "" && strings.Contains(m.Sender().XString(true), f.From) || f.To != "" && strings.Contains(m.Recipient().XString(true), f.To)
468 Field string // "Queued" or "NextAttempt"/"".
469 LastID int64 // If > 0, we return objects beyond this, less/greater depending on Asc.
470 Last any // Value of Field for last object. Must be set iff LastID is set.
471 Asc bool // Ascending, or descending.
474func (s Sort) apply(q *bstore.Query[Msg]) error {
476 case "", "NextAttempt":
477 s.Field = "NextAttempt"
481 return fmt.Errorf("unknown sort order field %q", s.Field)
485 ls, ok := s.Last.(string)
487 return fmt.Errorf("last should be string with time, not %T %q", s.Last, s.Last)
489 last, err := time.Parse(time.RFC3339Nano, ls)
491 last, err = time.Parse(time.RFC3339, ls)
494 return fmt.Errorf("parsing last %q as time: %v", s.Last, err)
496 q.FilterNotEqual("ID", s.LastID)
497 var fieldEqual func(m Msg) bool
498 if s.Field == "NextAttempt" {
499 fieldEqual = func(m Msg) bool { return m.NextAttempt.Equal(last) }
501 fieldEqual = func(m Msg) bool { return m.Queued.Equal(last) }
504 q.FilterGreaterEqual(s.Field, last)
505 q.FilterFn(func(m Msg) bool {
506 return !fieldEqual(m) || m.ID > s.LastID
509 q.FilterLessEqual(s.Field, last)
510 q.FilterFn(func(m Msg) bool {
511 return !fieldEqual(m) || m.ID < s.LastID
516 q.SortAsc(s.Field, "ID")
518 q.SortDesc(s.Field, "ID")
523// List returns max 100 messages matching filter in the delivery queue.
524// By default, orders by next delivery attempt.
525func List(ctx context.Context, filter Filter, sort Sort) ([]Msg, error) {
526 q := bstore.QueryDB[Msg](ctx, DB)
527 if err := filter.apply(q); err != nil {
530 if err := sort.apply(q); err != nil {
533 qmsgs, err := q.List()
540// Count returns the number of messages in the delivery queue.
541func Count(ctx context.Context) (int, error) {
542 return bstore.QueryDB[Msg](ctx, DB).Count()
545// HoldRuleList returns all hold rules.
546func HoldRuleList(ctx context.Context) ([]HoldRule, error) {
547 return bstore.QueryDB[HoldRule](ctx, DB).List()
550// HoldRuleAdd adds a new hold rule causing newly submitted messages to be marked
551// as "on hold", and existing matching messages too.
552func HoldRuleAdd(ctx context.Context, log mlog.Log, hr HoldRule) (HoldRule, error) {
554 err := DB.Write(ctx, func(tx *bstore.Tx) error {
556 hr.SenderDomainStr = hr.SenderDomain.Name()
557 hr.RecipientDomainStr = hr.RecipientDomain.Name()
558 if err := tx.Insert(&hr); err != nil {
561 log.Info("adding hold rule", slog.Any("holdrule", hr))
563 q := bstore.QueryTx[Msg](tx)
566 SenderAccount: hr.Account,
567 SenderDomainStr: hr.SenderDomainStr,
568 RecipientDomainStr: hr.RecipientDomainStr,
572 n, err = q.UpdateField("Hold", true)
574 return fmt.Errorf("marking existing matching messages in queue on hold: %v", err)
576 return metricHoldUpdate(tx)
579 return HoldRule{}, err
581 log.Info("marked messages in queue as on hold", slog.Int("messages", n))
586// HoldRuleRemove removes a hold rule. The Hold field of existing messages are not
588func HoldRuleRemove(ctx context.Context, log mlog.Log, holdRuleID int64) error {
589 return DB.Write(ctx, func(tx *bstore.Tx) error {
590 hr := HoldRule{ID: holdRuleID}
591 if err := tx.Get(&hr); err != nil {
594 log.Info("removing hold rule", slog.Any("holdrule", hr))
595 return tx.Delete(HoldRule{ID: holdRuleID})
599// MakeMsg is a convenience function that sets the commonly used fields for a Msg.
600// messageID should include <>.
601func MakeMsg(sender, recipient smtp.Path, has8bit, smtputf8 bool, size int64, messageID string, prefix []byte, requireTLS *bool, next time.Time, subject string) Msg {
603 SenderLocalpart: sender.Localpart,
604 SenderDomain: sender.IPDomain,
605 RecipientLocalpart: recipient.Localpart,
606 RecipientDomain: recipient.IPDomain,
610 MessageID: messageID,
613 RequireTLS: requireTLS,
619// Add one or more new messages to the queue. If the sender paths and MsgPrefix are
620// identical, they'll get the same BaseID, so they can be delivered in a single
621// SMTP transaction, with a single DATA command, but may be split into multiple
622// transactions if errors/limits are encountered. The queue is kicked immediately
623// to start a first delivery attempt.
625// ID of the messagse must be 0 and will be set after inserting in the queue.
627// Add sets derived fields like SenderDomainStr and RecipientDomainStr, and fields
628// related to queueing, such as Queued, NextAttempt.
629func Add(ctx context.Context, log mlog.Log, senderAccount string, msgFile *os.File, qml ...Msg) error {
631 return fmt.Errorf("must queue at least one message")
636 for i, qm := range qml {
638 return fmt.Errorf("id of queued messages must be 0")
640 // Sanity check, internal consistency.
641 qml[i].SenderDomainStr = formatIPDomain(qm.SenderDomain)
642 qml[i].RecipientDomainStr = formatIPDomain(qm.RecipientDomain)
643 if base && i > 0 && qm.Sender().String() != qml[0].Sender().String() || !bytes.Equal(qm.MsgPrefix, qml[0].MsgPrefix) {
648 tx, err := DB.Begin(ctx, true)
650 return fmt.Errorf("begin transaction: %w", err)
654 if err := tx.Rollback(); err != nil {
655 log.Errorx("rollback for queue", err)
660 // Mark messages Hold if they match a hold rule.
661 holdRules, err := bstore.QueryTx[HoldRule](tx).List()
663 return fmt.Errorf("getting queue hold rules")
666 // Insert messages into queue. If multiple messages are to be delivered in a single
667 // transaction, they all get a non-zero BaseID that is the Msg.ID of the first
671 // FromIDs must be unique if present. We don't have a unique index because values
672 // can be the empty string. We check in both Msg and MsgRetired, both are relevant
673 // for uniquely identifying a message sent in the past.
674 if fromID := qml[i].FromID; fromID != "" {
675 if exists, err := bstore.QueryTx[Msg](tx).FilterNonzero(Msg{FromID: fromID}).Exists(); err != nil {
676 return fmt.Errorf("looking up fromid: %v", err)
678 return fmt.Errorf("%w: fromid %q already present in message queue", ErrFromID, fromID)
680 if exists, err := bstore.QueryTx[MsgRetired](tx).FilterNonzero(MsgRetired{FromID: fromID}).Exists(); err != nil {
681 return fmt.Errorf("looking up fromid: %v", err)
683 return fmt.Errorf("%w: fromid %q already present in retired message queue", ErrFromID, fromID)
687 qml[i].SenderAccount = senderAccount
688 qml[i].BaseID = baseID
689 for _, hr := range holdRules {
690 if hr.matches(qml[i]) {
695 if err := tx.Insert(&qml[i]); err != nil {
698 if base && i == 0 && len(qml) > 1 {
700 qml[i].BaseID = baseID
701 if err := tx.Update(&qml[i]); err != nil {
709 for _, p := range paths {
711 log.Check(err, "removing destination message file for queue", slog.String("path", p))
715 for _, qm := range qml {
716 dst := qm.MessagePath()
717 paths = append(paths, dst)
718 dstDir := filepath.Dir(dst)
719 os.MkdirAll(dstDir, 0770)
720 if err := moxio.LinkOrCopy(log, dst, msgFile.Name(), nil, true); err != nil {
721 return fmt.Errorf("linking/copying message to new file: %s", err)
722 } else if err := moxio.SyncDir(log, dstDir); err != nil {
723 return fmt.Errorf("sync directory: %v", err)
727 for _, m := range qml {
729 if err := metricHoldUpdate(tx); err != nil {
736 if err := tx.Commit(); err != nil {
737 return fmt.Errorf("commit transaction: %s", err)
747func formatIPDomain(d dns.IPDomain) string {
749 return "[" + d.IP.String() + "]"
751 return d.Domain.Name()
755 msgqueue = make(chan struct{}, 1)
756 deliveryResults = make(chan string, 1)
766 case msgqueue <- struct{}{}:
771// NextAttemptAdd adds a duration to the NextAttempt for all matching messages, and
773func NextAttemptAdd(ctx context.Context, filter Filter, d time.Duration) (affected int, err error) {
774 err = DB.Write(ctx, func(tx *bstore.Tx) error {
775 q := bstore.QueryTx[Msg](tx)
776 if err := filter.apply(q); err != nil {
779 msgs, err := q.List()
781 return fmt.Errorf("listing matching messages: %v", err)
783 for _, m := range msgs {
784 m.NextAttempt = m.NextAttempt.Add(d)
785 if err := tx.Update(&m); err != nil {
799// NextAttemptSet sets NextAttempt for all matching messages to a new time, and
801func NextAttemptSet(ctx context.Context, filter Filter, t time.Time) (affected int, err error) {
802 q := bstore.QueryDB[Msg](ctx, DB)
803 if err := filter.apply(q); err != nil {
806 n, err := q.UpdateNonzero(Msg{NextAttempt: t})
808 return 0, fmt.Errorf("selecting and updating messages in queue: %v", err)
814// HoldSet sets Hold for all matching messages and kicks the queue.
815func HoldSet(ctx context.Context, filter Filter, hold bool) (affected int, err error) {
816 err = DB.Write(ctx, func(tx *bstore.Tx) error {
817 q := bstore.QueryTx[Msg](tx)
818 if err := filter.apply(q); err != nil {
821 n, err := q.UpdateFields(map[string]any{"Hold": hold})
823 return fmt.Errorf("selecting and updating messages in queue: %v", err)
826 return metricHoldUpdate(tx)
835// TransportSet changes the transport to use for the matching messages.
836func TransportSet(ctx context.Context, filter Filter, transport string) (affected int, err error) {
837 q := bstore.QueryDB[Msg](ctx, DB)
838 if err := filter.apply(q); err != nil {
841 n, err := q.UpdateFields(map[string]any{"Transport": transport})
843 return 0, fmt.Errorf("selecting and updating messages in queue: %v", err)
849// Fail marks matching messages as failed for delivery, delivers a DSN to the
850// sender, and sends a webhook.
852// Returns number of messages removed, which can be non-zero even in case of an
854func Fail(ctx context.Context, log mlog.Log, f Filter) (affected int, err error) {
855 return failDrop(ctx, log, f, true)
858// Drop removes matching messages from the queue. Messages are added as retired
859// message, webhooks with the "canceled" event are queued.
861// Returns number of messages removed, which can be non-zero even in case of an
863func Drop(ctx context.Context, log mlog.Log, f Filter) (affected int, err error) {
864 return failDrop(ctx, log, f, false)
867func failDrop(ctx context.Context, log mlog.Log, filter Filter, fail bool) (affected int, err error) {
869 err = DB.Write(ctx, func(tx *bstore.Tx) error {
870 q := bstore.QueryTx[Msg](tx)
871 if err := filter.apply(q); err != nil {
877 return fmt.Errorf("getting messages to delete: %v", err)
885 var remoteMTA dsn.NameIP
886 for i := range msgs {
889 Error: "delivery canceled by admin",
891 msgs[i].Results = append(msgs[i].Results, result)
893 if msgs[i].LastAttempt == nil {
894 msgs[i].LastAttempt = &now
896 deliverDSNFailure(log, msgs[i], remoteMTA, "", result.Error, nil)
899 event := webhook.EventCanceled
901 event = webhook.EventFailed
903 if err := retireMsgs(log, tx, event, 0, "", nil, msgs...); err != nil {
904 return fmt.Errorf("removing queue messages from database: %w", err)
906 return metricHoldUpdate(tx)
912 if err := removeMsgsFS(log, msgs...); err != nil {
913 return len(msgs), fmt.Errorf("removing queue messages from file system: %w", err)
917 return len(msgs), nil
920// RequireTLSSet updates the RequireTLS field of matching messages.
921func RequireTLSSet(ctx context.Context, filter Filter, requireTLS *bool) (affected int, err error) {
922 q := bstore.QueryDB[Msg](ctx, DB)
923 if err := filter.apply(q); err != nil {
926 n, err := q.UpdateFields(map[string]any{"RequireTLS": requireTLS})
931// RetiredFilter filters messages to list or operate on. Used by admin web interface
934// Only non-empty/non-zero values are applied to the filter. Leaving all fields
935// empty/zero matches all messages.
936type RetiredFilter struct {
942 Submitted string // Whether submitted before/after a time relative to now. ">$duration" or "<$duration", also with "now" for duration.
943 LastActivity string // ">$duration" or "<$duration", also with "now" for duration.
948func (f RetiredFilter) apply(q *bstore.Query[MsgRetired]) error {
952 applyTime := func(field string, s string) error {
955 if strings.HasPrefix(s, "<") {
957 } else if !strings.HasPrefix(s, ">") {
958 return fmt.Errorf(`must start with "<" for before or ">" for after a duration`)
960 s = strings.TrimSpace(s[1:])
964 } else if d, err := time.ParseDuration(s); err != nil {
965 return fmt.Errorf("parsing duration %q: %v", orig, err)
967 t = time.Now().Add(d)
970 q.FilterLess(field, t)
972 q.FilterGreater(field, t)
976 if f.Submitted != "" {
977 if err := applyTime("Queued", f.Submitted); err != nil {
978 return fmt.Errorf("applying filter for submitted: %v", err)
981 if f.LastActivity != "" {
982 if err := applyTime("LastActivity", f.LastActivity); err != nil {
983 return fmt.Errorf("applying filter for last activity: %v", err)
987 q.FilterNonzero(MsgRetired{SenderAccount: f.Account})
989 if f.Transport != nil {
990 q.FilterEqual("Transport", *f.Transport)
992 if f.From != "" || f.To != "" {
993 q.FilterFn(func(m MsgRetired) bool {
994 return f.From != "" && strings.Contains(m.SenderLocalpart.String()+"@"+m.SenderDomainStr, f.From) || f.To != "" && strings.Contains(m.Recipient().XString(true), f.To)
997 if f.Success != nil {
998 q.FilterEqual("Success", *f.Success)
1006type RetiredSort struct {
1007 Field string // "Queued" or "LastActivity"/"".
1008 LastID int64 // If > 0, we return objects beyond this, less/greater depending on Asc.
1009 Last any // Value of Field for last object. Must be set iff LastID is set.
1010 Asc bool // Ascending, or descending.
1013func (s RetiredSort) apply(q *bstore.Query[MsgRetired]) error {
1015 case "", "LastActivity":
1016 s.Field = "LastActivity"
1020 return fmt.Errorf("unknown sort order field %q", s.Field)
1024 ls, ok := s.Last.(string)
1026 return fmt.Errorf("last should be string with time, not %T %q", s.Last, s.Last)
1028 last, err := time.Parse(time.RFC3339Nano, ls)
1030 last, err = time.Parse(time.RFC3339, ls)
1033 return fmt.Errorf("parsing last %q as time: %v", s.Last, err)
1035 q.FilterNotEqual("ID", s.LastID)
1036 var fieldEqual func(m MsgRetired) bool
1037 if s.Field == "LastActivity" {
1038 fieldEqual = func(m MsgRetired) bool { return m.LastActivity.Equal(last) }
1040 fieldEqual = func(m MsgRetired) bool { return m.Queued.Equal(last) }
1043 q.FilterGreaterEqual(s.Field, last)
1044 q.FilterFn(func(mr MsgRetired) bool {
1045 return !fieldEqual(mr) || mr.ID > s.LastID
1048 q.FilterLessEqual(s.Field, last)
1049 q.FilterFn(func(mr MsgRetired) bool {
1050 return !fieldEqual(mr) || mr.ID < s.LastID
1055 q.SortAsc(s.Field, "ID")
1057 q.SortDesc(s.Field, "ID")
1062// RetiredList returns retired messages.
1063func RetiredList(ctx context.Context, filter RetiredFilter, sort RetiredSort) ([]MsgRetired, error) {
1064 q := bstore.QueryDB[MsgRetired](ctx, DB)
1065 if err := filter.apply(q); err != nil {
1068 if err := sort.apply(q); err != nil {
1074type ReadReaderAtCloser interface {
1079// OpenMessage opens a message present in the queue.
1080func OpenMessage(ctx context.Context, id int64) (ReadReaderAtCloser, error) {
1082 err := DB.Get(ctx, &qm)
1086 f, err := os.Open(qm.MessagePath())
1088 return nil, fmt.Errorf("open message file: %s", err)
1090 r := store.FileMsgReader(qm.MsgPrefix, f)
1094const maxConcurrentDeliveries = 10
1095const maxConcurrentHookDeliveries = 10
1097// Start opens the database by calling Init, then starts the delivery and cleanup
1099func Start(resolver dns.Resolver, done chan struct{}) error {
1100 if err := Init(); err != nil {
1104 go startQueue(resolver, done)
1105 go startHookQueue(done)
1107 go cleanupMsgRetired(done)
1108 go cleanupHookRetired(done)
1113func cleanupMsgRetired(done chan struct{}) {
1114 log := mlog.New("queue", nil)
1119 log.Error("unhandled panic in cleanupMsgRetired", slog.Any("x", x))
1121 metrics.PanicInc(metrics.Queue)
1125 timer := time.NewTimer(3 * time.Second)
1128 case <-mox.Shutdown.Done():
1134 cleanupMsgRetiredSingle(log)
1135 timer.Reset(time.Hour)
1139func cleanupMsgRetiredSingle(log mlog.Log) {
1140 n, err := bstore.QueryDB[MsgRetired](mox.Shutdown, DB).FilterLess("KeepUntil", time.Now()).Delete()
1141 log.Check(err, "removing old retired messages")
1143 log.Debug("cleaned up retired messages", slog.Int("count", n))
1147func startQueue(resolver dns.Resolver, done chan struct{}) {
1149 log := mlog.New("queue", nil)
1151 // Map keys are either dns.Domain.Name()'s, or string-formatted IP addresses.
1152 busyDomains := map[string]struct{}{}
1154 timer := time.NewTimer(0)
1158 case <-mox.Shutdown.Done():
1159 for len(busyDomains) > 0 {
1160 domain := <-deliveryResults
1161 delete(busyDomains, domain)
1167 case domain := <-deliveryResults:
1168 delete(busyDomains, domain)
1171 if len(busyDomains) >= maxConcurrentDeliveries {
1175 launchWork(log, resolver, busyDomains)
1176 timer.Reset(nextWork(mox.Shutdown, log, busyDomains))
1180func nextWork(ctx context.Context, log mlog.Log, busyDomains map[string]struct{}) time.Duration {
1181 q := bstore.QueryDB[Msg](ctx, DB)
1182 if len(busyDomains) > 0 {
1184 for d := range busyDomains {
1185 doms = append(doms, d)
1187 q.FilterNotEqual("RecipientDomainStr", doms...)
1189 q.FilterEqual("Hold", false)
1190 q.SortAsc("NextAttempt")
1193 if err == bstore.ErrAbsent {
1194 return 24 * time.Hour
1195 } else if err != nil {
1196 log.Errorx("finding time for next delivery attempt", err)
1197 return 1 * time.Minute
1199 return time.Until(qm.NextAttempt)
1202func launchWork(log mlog.Log, resolver dns.Resolver, busyDomains map[string]struct{}) int {
1203 q := bstore.QueryDB[Msg](mox.Shutdown, DB)
1204 q.FilterLessEqual("NextAttempt", time.Now())
1205 q.FilterEqual("Hold", false)
1206 q.SortAsc("NextAttempt")
1207 q.Limit(maxConcurrentDeliveries)
1208 if len(busyDomains) > 0 {
1210 for d := range busyDomains {
1211 doms = append(doms, d)
1213 q.FilterNotEqual("RecipientDomainStr", doms...)
1216 seen := map[string]bool{}
1217 err := q.ForEach(func(m Msg) error {
1218 dom := m.RecipientDomainStr
1219 if _, ok := busyDomains[dom]; !ok && !seen[dom] {
1221 msgs = append(msgs, m)
1226 log.Errorx("querying for work in queue", err)
1227 mox.Sleep(mox.Shutdown, 1*time.Second)
1231 for _, m := range msgs {
1232 busyDomains[m.RecipientDomainStr] = struct{}{}
1233 go deliver(log, resolver, m)
1238// todo future: we may consider keeping message files around for a while after retiring. especially for failures to deliver. to inspect what exactly wasn't delivered.
1240func removeMsgsFS(log mlog.Log, msgs ...Msg) error {
1242 for _, m := range msgs {
1243 p := mox.DataDirPath(filepath.Join("queue", store.MessagePath(m.ID)))
1244 if err := os.Remove(p); err != nil {
1245 errs = append(errs, fmt.Sprintf("%s: %v", p, err))
1249 return fmt.Errorf("removing message files from queue: %s", strings.Join(errs, "; "))
1254// Move one or more messages to retire list or remove it. Webhooks are scheduled.
1255// IDs of msgs in suppressedMsgIDs caused a suppression to be added.
1257// Callers should update Msg.Results before calling.
1259// Callers must remove the messages from the file system afterwards, see
1260// removeMsgsFS. Callers must also kick the message and webhook queues.
1261func retireMsgs(log mlog.Log, tx *bstore.Tx, event webhook.OutgoingEvent, code int, secode string, suppressedMsgIDs []int64, msgs ...Msg) error {
1266 accConf, ok := mox.Conf.Account(m0.SenderAccount)
1268 if accConf.OutgoingWebhook != nil {
1269 hookURL = accConf.OutgoingWebhook.URL
1271 log.Debug("retiring messages from queue", slog.Any("event", event), slog.String("account", m0.SenderAccount), slog.Bool("ok", ok), slog.String("webhookurl", hookURL))
1272 if hookURL != "" && (len(accConf.OutgoingWebhook.Events) == 0 || slices.Contains(accConf.OutgoingWebhook.Events, string(event))) {
1273 for _, m := range msgs {
1274 suppressing := slices.Contains(suppressedMsgIDs, m.ID)
1275 h, err := hookCompose(m, hookURL, accConf.OutgoingWebhook.Authorization, event, suppressing, code, secode)
1277 log.Errorx("composing webhooks while retiring messages from queue, not queueing hook for message", err, slog.Int64("msgid", m.ID), slog.Any("recipient", m.Recipient()))
1279 hooks = append(hooks, h)
1284 msgKeep := 24 * 7 * time.Hour
1285 hookKeep := 24 * 7 * time.Hour
1287 msgKeep = accConf.KeepRetiredMessagePeriod
1288 hookKeep = accConf.KeepRetiredWebhookPeriod
1291 for _, m := range msgs {
1292 if err := tx.Delete(&m); err != nil {
1297 for _, m := range msgs {
1298 rm := m.Retired(event == webhook.EventDelivered, now, now.Add(msgKeep))
1299 if err := tx.Insert(&rm); err != nil {
1305 for i := range hooks {
1306 if err := hookInsert(tx, &hooks[i], now, hookKeep); err != nil {
1307 return fmt.Errorf("enqueueing webhooks while retiring messages from queue: %v", err)
1312 for _, h := range hooks {
1313 log.Debug("queued webhook while retiring message from queue", h.attrs()...)
1320// deliver attempts to deliver a message.
1321// The queue is updated, either by removing a delivered or permanently failed
1322// message, or updating the time for the next attempt. A DSN may be sent.
1323func deliver(log mlog.Log, resolver dns.Resolver, m0 Msg) {
1326 qlog := log.WithCid(mox.Cid()).With(
1327 slog.Any("from", m0.Sender()),
1328 slog.Int("attempts", m0.Attempts))
1331 deliveryResults <- formatIPDomain(m0.RecipientDomain)
1335 qlog.Error("deliver panic", slog.Any("panic", x), slog.Int64("msgid", m0.ID), slog.Any("recipient", m0.Recipient()))
1337 metrics.PanicInc(metrics.Queue)
1341 // We'll use a single transaction for the various checks, committing as soon as
1342 // we're done with it.
1343 xtx, err := DB.Begin(mox.Shutdown, true)
1345 qlog.Errorx("transaction for gathering messages to deliver", err)
1350 err := xtx.Rollback()
1351 qlog.Check(err, "rolling back transaction after error delivering")
1355 // We register this attempt by setting LastAttempt, adding an empty Result, and
1356 // already setting NextAttempt in the future with exponential backoff. If we run
1357 // into trouble delivery below, at least we won't be bothering the receiving server
1358 // with our problems.
1359 // Delivery attempts: immediately, 7.5m, 15m, 30m, 1h, 2h (send delayed DSN), 4h,
1360 // 8h, 16h (send permanent failure DSN).
1364 var backoff time.Duration
1365 var origNextAttempt time.Time
1366 prepare := func() error {
1367 // Refresh message within transaction.
1369 if err := xtx.Get(&m0); err != nil {
1370 return fmt.Errorf("get message to be delivered: %v", err)
1373 backoff = time.Duration(7*60+30+jitter.Intn(10)-5) * time.Second
1374 for i := 0; i < m0.Attempts; i++ {
1375 backoff *= time.Duration(2)
1378 origNextAttempt = m0.NextAttempt
1379 m0.LastAttempt = &now
1380 m0.NextAttempt = now.Add(backoff)
1381 m0.Results = append(m0.Results, MsgResult{Start: now, Error: resultErrorDelivering})
1382 if err := xtx.Update(&m0); err != nil {
1383 return fmt.Errorf("update message to be delivered: %v", err)
1387 if err := prepare(); err != nil {
1388 qlog.Errorx("storing delivery attempt", err, slog.Int64("msgid", m0.ID), slog.Any("recipient", m0.Recipient()))
1394 // Check if recipient is on suppression list. If so, fail delivery.
1395 path := smtp.Path{Localpart: m0.RecipientLocalpart, IPDomain: m0.RecipientDomain}
1396 baseAddr := baseAddress(path).XString(true)
1397 qsup := bstore.QueryTx[webapi.Suppression](xtx)
1398 qsup.FilterNonzero(webapi.Suppression{Account: m0.SenderAccount, BaseAddress: baseAddr})
1399 exists, err := qsup.Exists()
1400 if err != nil || exists {
1402 qlog.Errorx("checking whether recipient address is in suppression list", err)
1404 err := fmt.Errorf("not delivering to recipient address %s: %w", path.XString(true), errSuppressed)
1405 err = smtpclient.Error{Permanent: true, Err: err}
1406 failMsgsTx(qlog, xtx, []*Msg{&m0}, m0.DialedIPs, backoff, remoteMTA, err)
1409 qlog.Check(err, "commit processing failure to deliver messages")
1415 resolveTransport := func(mm Msg) (string, config.Transport, bool) {
1416 if mm.Transport != "" {
1417 transport, ok := mox.Conf.Static.Transports[mm.Transport]
1419 return "", config.Transport{}, false
1421 return mm.Transport, transport, ok
1423 route := findRoute(mm.Attempts, mm)
1424 return route.Transport, route.ResolvedTransport, true
1427 // Find route for transport to use for delivery attempt.
1429 transportName, transport, transportOK := resolveTransport(m0)
1432 failMsgsTx(qlog, xtx, []*Msg{&m0}, m0.DialedIPs, backoff, remoteMTA, fmt.Errorf("cannot find transport %q", m0.Transport))
1434 qlog.Check(err, "commit processing failure to deliver messages")
1440 if transportName != "" {
1441 qlog = qlog.With(slog.String("transport", transportName))
1442 qlog.Debug("delivering with transport")
1445 // Attempt to gather more recipients for this identical message, only with the same
1446 // recipient domain, and under the same conditions (recipientdomain, attempts,
1450 gather := func() error {
1451 q := bstore.QueryTx[Msg](xtx)
1452 q.FilterNonzero(Msg{BaseID: m0.BaseID, RecipientDomainStr: m0.RecipientDomainStr, Attempts: m0.Attempts - 1})
1453 q.FilterNotEqual("ID", m0.ID)
1454 q.FilterLessEqual("NextAttempt", origNextAttempt)
1455 q.FilterEqual("Hold", false)
1456 err := q.ForEach(func(xm Msg) error {
1457 mrtls := m0.RequireTLS != nil
1458 xmrtls := xm.RequireTLS != nil
1459 if mrtls != xmrtls || mrtls && *m0.RequireTLS != *xm.RequireTLS {
1462 tn, _, ok := resolveTransport(xm)
1463 if ok && tn == transportName {
1464 msgs = append(msgs, &xm)
1469 return fmt.Errorf("looking up more recipients: %v", err)
1472 // Mark these additional messages as attempted too.
1473 for _, mm := range msgs[1:] {
1475 mm.NextAttempt = m0.NextAttempt
1476 mm.LastAttempt = m0.LastAttempt
1477 mm.Results = append(mm.Results, MsgResult{Start: now, Error: resultErrorDelivering})
1478 if err := xtx.Update(mm); err != nil {
1479 return fmt.Errorf("updating more message recipients for smtp transaction: %v", err)
1484 if err := gather(); err != nil {
1485 qlog.Errorx("error finding more recipients for message, will attempt to send to single recipient", err)
1490 if err := xtx.Commit(); err != nil {
1491 qlog.Errorx("commit of preparation to deliver", err, slog.Any("msgid", m0.ID))
1497 ids := make([]int64, len(msgs))
1498 rcpts := make([]smtp.Path, len(msgs))
1499 for i, m := range msgs {
1501 rcpts[i] = m.Recipient()
1503 qlog.Debug("delivering to multiple recipients", slog.Any("msgids", ids), slog.Any("recipients", rcpts))
1505 qlog.Debug("delivering to single recipient", slog.Any("msgid", m0.ID), slog.Any("recipient", m0.Recipient()))
1509 deliverLocalserve(ctx, qlog, msgs, backoff)
1513 // We gather TLS connection successes and failures during delivery, and we store
1514 // them in tlsrptdb. Every 24 hours we send an email with a report to the recipient
1515 // domains that opt in via a TLSRPT DNS record. For us, the tricky part is
1516 // collecting all reporting information. We've got several TLS modes
1517 // (opportunistic, DANE and/or MTA-STS (PKIX), overrides due to Require TLS).
1518 // Failures can happen at various levels: MTA-STS policies (apply to whole delivery
1519 // attempt/domain), MX targets (possibly multiple per delivery attempt, both for
1520 // MTA-STS and DANE).
1522 // Once the SMTP client has tried a TLS handshake, we register success/failure,
1523 // regardless of what happens next on the connection. We also register failures
1524 // when they happen before we get to the SMTP client, but only if they are related
1525 // to TLS (and some DNSSEC).
1526 var recipientDomainResult tlsrpt.Result
1527 var hostResults []tlsrpt.Result
1529 if mox.Conf.Static.NoOutgoingTLSReports || m0.RecipientDomain.IsIP() {
1534 dayUTC := now.UTC().Format("20060102")
1536 // See if this contains a failure. If not, we'll mark TLS results for delivering
1537 // DMARC reports SendReport false, so we won't as easily get into a report sending
1540 for _, result := range hostResults {
1541 if result.Summary.TotalFailureSessionCount > 0 {
1546 if recipientDomainResult.Summary.TotalFailureSessionCount > 0 {
1550 results := make([]tlsrptdb.TLSResult, 0, 1+len(hostResults))
1551 tlsaPolicyDomains := map[string]bool{}
1552 addResult := func(r tlsrpt.Result, isHost bool) {
1553 var zerotype tlsrpt.PolicyType
1554 if r.Policy.Type == zerotype {
1558 // Ensure we store policy domain in unicode in database.
1559 policyDomain, err := dns.ParseDomain(r.Policy.Domain)
1561 qlog.Errorx("parsing policy domain for tls result", err, slog.String("policydomain", r.Policy.Domain))
1565 if r.Policy.Type == tlsrpt.TLSA {
1566 tlsaPolicyDomains[policyDomain.ASCII] = true
1569 tlsResult := tlsrptdb.TLSResult{
1570 PolicyDomain: policyDomain.Name(),
1572 RecipientDomain: m0.RecipientDomain.Domain.Name(),
1574 SendReport: !m0.IsTLSReport && (!m0.IsDMARCReport || failure),
1575 Results: []tlsrpt.Result{r},
1577 results = append(results, tlsResult)
1579 for _, result := range hostResults {
1580 addResult(result, true)
1582 // If we were delivering to a mail host directly (not a domain with MX records), we
1583 // are more likely to get a TLSA policy than an STS policy. Don't potentially
1584 // confuse operators with both a tlsa and no-policy-found result.
1586 if recipientDomainResult.Policy.Type != tlsrpt.NoPolicyFound || !tlsaPolicyDomains[recipientDomainResult.Policy.Domain] {
1587 addResult(recipientDomainResult, false)
1590 if len(results) > 0 {
1591 err := tlsrptdb.AddTLSResults(context.Background(), results)
1592 qlog.Check(err, "adding tls results to database for upcoming tlsrpt report")
1596 var dialer smtpclient.Dialer = &net.Dialer{}
1597 if transport.Submissions != nil {
1598 deliverSubmit(qlog, resolver, dialer, msgs, backoff, transportName, transport.Submissions, true, 465)
1599 } else if transport.Submission != nil {
1600 deliverSubmit(qlog, resolver, dialer, msgs, backoff, transportName, transport.Submission, false, 587)
1601 } else if transport.SMTP != nil {
1602 // todo future: perhaps also gather tlsrpt results for submissions.
1603 deliverSubmit(qlog, resolver, dialer, msgs, backoff, transportName, transport.SMTP, false, 25)
1605 ourHostname := mox.Conf.Static.HostnameDomain
1606 if transport.Socks != nil {
1607 socksdialer, err := proxy.SOCKS5("tcp", transport.Socks.Address, nil, &net.Dialer{})
1609 failMsgsDB(qlog, msgs, msgs[0].DialedIPs, backoff, dsn.NameIP{}, fmt.Errorf("socks dialer: %v", err))
1611 } else if d, ok := socksdialer.(smtpclient.Dialer); !ok {
1612 failMsgsDB(qlog, msgs, msgs[0].DialedIPs, backoff, dsn.NameIP{}, fmt.Errorf("socks dialer is not a contextdialer"))
1617 ourHostname = transport.Socks.Hostname
1619 recipientDomainResult, hostResults = deliverDirect(qlog, resolver, dialer, ourHostname, transportName, transport.Direct, msgs, backoff)
1623func findRoute(attempt int, m Msg) config.Route {
1624 routesAccount, routesDomain, routesGlobal := mox.Conf.Routes(m.SenderAccount, m.SenderDomain.Domain)
1625 if r, ok := findRouteInList(attempt, m, routesAccount); ok {
1628 if r, ok := findRouteInList(attempt, m, routesDomain); ok {
1631 if r, ok := findRouteInList(attempt, m, routesGlobal); ok {
1634 return config.Route{}
1637func findRouteInList(attempt int, m Msg, routes []config.Route) (config.Route, bool) {
1638 for _, r := range routes {
1639 if routeMatch(attempt, m, r) {
1643 return config.Route{}, false
1646func routeMatch(attempt int, m Msg, r config.Route) bool {
1647 return attempt >= r.MinimumAttempts && routeMatchDomain(r.FromDomainASCII, m.SenderDomain.Domain) && routeMatchDomain(r.ToDomainASCII, m.RecipientDomain.Domain)
1650func routeMatchDomain(l []string, d dns.Domain) bool {
1654 for _, e := range l {
1655 if d.ASCII == e || strings.HasPrefix(e, ".") && (d.ASCII == e[1:] || strings.HasSuffix(d.ASCII, e)) {
1662// Returns string representing delivery result for err, and number of delivered and
1665// Values: ok, okpartial, timeout, canceled, temperror, permerror, error.
1666func deliveryResult(err error, delivered, failed int) string {
1667 var cerr smtpclient.Error
1672 } else if failed > 0 {
1676 case errors.Is(err, os.ErrDeadlineExceeded), errors.Is(err, context.DeadlineExceeded):
1678 case errors.Is(err, context.Canceled):
1680 case errors.As(err, &cerr):