14 "golang.org/x/exp/slices"
15 "golang.org/x/exp/slog"
17 "github.com/mjl-/mox/config"
18 "github.com/mjl-/mox/dns"
19 "github.com/mjl-/mox/dsn"
20 "github.com/mjl-/mox/mlog"
21 "github.com/mjl-/mox/mox-"
22 "github.com/mjl-/mox/sasl"
23 "github.com/mjl-/mox/smtp"
24 "github.com/mjl-/mox/smtpclient"
25 "github.com/mjl-/mox/store"
28// todo: reuse connection? do fewer concurrently (other than with direct delivery).
30// deliver via another SMTP server, e.g. relaying to a smart host, possibly
31// with authentication (submission).
32func deliverSubmit(qlog mlog.Log, resolver dns.Resolver, dialer smtpclient.Dialer, m Msg, backoff time.Duration, transportName string, transport *config.TransportSMTP, dialTLS bool, defaultPort int) {
33 // todo: configurable timeouts
35 port := transport.Port
40 tlsMode := smtpclient.TLSRequiredStartTLS
43 tlsMode = smtpclient.TLSImmediate
44 } else if transport.STARTTLSInsecureSkipVerify {
45 tlsMode = smtpclient.TLSRequiredStartTLS
47 } else if transport.NoSTARTTLS {
48 tlsMode = smtpclient.TLSSkip
52 var deliveryResult string
58 metricDelivery.WithLabelValues(fmt.Sprintf("%d", m.Attempts), transportName, string(tlsMode), deliveryResult).Observe(float64(time.Since(start)) / float64(time.Second))
59 qlog.Debug("queue deliversubmit result",
60 slog.Any("host", transport.DNSHost),
61 slog.Int("port", port),
62 slog.Int("attempt", m.Attempts),
63 slog.Bool("permanent", permanent),
64 slog.String("secodeopt", secodeOpt),
65 slog.String("errmsg", errmsg),
66 slog.Bool("ok", success),
67 slog.Duration("duration", time.Since(start)))
70 // todo: SMTP-DANE should be used when relaying on port 25.
73 // todo: for submission, understand SRV records, and even DANE.
77 // If submit was done with REQUIRETLS extension for SMTP, we must verify TLS
78 // certificates. If our submission connection is not configured that way, abort.
79 requireTLS := m.RequireTLS != nil && *m.RequireTLS
80 if requireTLS && (tlsMode != smtpclient.TLSRequiredStartTLS && tlsMode != smtpclient.TLSImmediate || !tlsPKIX) {
81 errmsg = fmt.Sprintf("transport %s: message requires verified tls but transport does not verify tls", transportName)
82 fail(ctx, qlog, m, backoff, true, dsn.NameIP{}, smtp.SePol7MissingReqTLS, errmsg)
86 dialctx, dialcancel := context.WithTimeout(ctx, 30*time.Second)
88 if m.DialedIPs == nil {
89 m.DialedIPs = map[string][]net.IP{}
91 _, _, _, ips, _, err := smtpclient.GatherIPs(dialctx, qlog.Logger, resolver, dns.IPDomain{Domain: transport.DNSHost}, m.DialedIPs)
94 if m.DialedIPs == nil {
95 m.DialedIPs = map[string][]net.IP{}
97 conn, _, err = smtpclient.Dial(dialctx, qlog.Logger, dialer, dns.IPDomain{Domain: transport.DNSHost}, ips, port, m.DialedIPs, mox.Conf.Static.SpecifiedSMTPListenIPs)
99 addr := net.JoinHostPort(transport.Host, fmt.Sprintf("%d", port))
104 case errors.Is(err, os.ErrDeadlineExceeded), errors.Is(err, context.DeadlineExceeded):
106 case errors.Is(err, context.Canceled):
111 metricConnection.WithLabelValues(result).Inc()
115 qlog.Check(err, "closing connection")
117 qlog.Errorx("dialing for submission", err, slog.String("remote", addr))
118 errmsg = fmt.Sprintf("transport %s: dialing %s for submission: %v", transportName, addr, err)
119 fail(ctx, qlog, m, backoff, false, dsn.NameIP{}, "", errmsg)
124 var auth func(mechanisms []string, cs *tls.ConnectionState) (sasl.Client, error)
125 if transport.Auth != nil {
127 auth = func(mechanisms []string, cs *tls.ConnectionState) (sasl.Client, error) {
128 var supportsscramsha1plus, supportsscramsha256plus bool
129 for _, mech := range a.EffectiveMechanisms {
130 if !slices.Contains(mechanisms, mech) {
132 case "SCRAM-SHA-1-PLUS":
133 supportsscramsha1plus = cs != nil
134 case "SCRAM-SHA-256-PLUS":
135 supportsscramsha256plus = cs != nil
139 if mech == "SCRAM-SHA-256-PLUS" && cs != nil {
140 return sasl.NewClientSCRAMSHA256PLUS(a.Username, a.Password, *cs), nil
141 } else if mech == "SCRAM-SHA-256" {
142 return sasl.NewClientSCRAMSHA256(a.Username, a.Password, supportsscramsha256plus), nil
143 } else if mech == "SCRAM-SHA-1-PLUS" && cs != nil {
144 return sasl.NewClientSCRAMSHA1PLUS(a.Username, a.Password, *cs), nil
145 } else if mech == "SCRAM-SHA-1" {
146 return sasl.NewClientSCRAMSHA1(a.Username, a.Password, supportsscramsha1plus), nil
147 } else if mech == "CRAM-MD5" {
148 return sasl.NewClientCRAMMD5(a.Username, a.Password), nil
149 } else if mech == "PLAIN" {
150 return sasl.NewClientPlain(a.Username, a.Password), nil
152 return nil, fmt.Errorf("internal error: unrecognized authentication mechanism %q for transport %s", mech, transportName)
155 // No mutually supported algorithm.
159 clientctx, clientcancel := context.WithTimeout(context.Background(), 60*time.Second)
161 opts := smtpclient.Opts{
163 RootCAs: mox.Conf.Static.TLS.CertPool,
165 client, err := smtpclient.New(clientctx, qlog.Logger, conn, tlsMode, tlsPKIX, mox.Conf.Static.HostnameDomain, transport.DNSHost, opts)
167 smtperr, ok := err.(smtpclient.Error)
168 var remoteMTA dsn.NameIP
170 remoteMTA.Name = transport.Host
172 qlog.Errorx("establishing smtp session for submission", err, slog.String("remote", addr))
173 errmsg = fmt.Sprintf("transport %s: establishing smtp session with %s for submission: %v", transportName, addr, err)
174 secodeOpt = smtperr.Secode
175 fail(ctx, qlog, m, backoff, false, remoteMTA, secodeOpt, errmsg)
179 err := client.Close()
180 qlog.Check(err, "closing smtp client after delivery")
184 var msgr io.ReadCloser
186 var req8bit, reqsmtputf8 bool
187 if len(m.DSNUTF8) > 0 && client.SupportsSMTPUTF8() {
188 msgr = io.NopCloser(bytes.NewReader(m.DSNUTF8))
190 size = int64(len(m.DSNUTF8))
192 req8bit = m.Has8bit // todo: not require this, but just try to submit?
198 qlog.Errorx("opening message for delivery", err, slog.String("remote", addr), slog.String("path", p))
199 errmsg = fmt.Sprintf("transport %s: opening message file for submission: %v", transportName, err)
200 fail(ctx, qlog, m, backoff, false, dsn.NameIP{}, "", errmsg)
203 msgr = store.FileMsgReader(m.MsgPrefix, f)
206 qlog.Check(err, "closing message after delivery attempt")
210 deliverctx, delivercancel := context.WithTimeout(context.Background(), time.Duration(60+size/(1024*1024))*time.Second)
211 defer delivercancel()
212 err = client.Deliver(deliverctx, m.Sender().String(), m.Recipient().String(), size, msgr, req8bit, reqsmtputf8, requireTLS)
214 qlog.Infox("delivery failed", err)
216 var cerr smtpclient.Error
219 deliveryResult = "ok"
221 case errors.Is(err, os.ErrDeadlineExceeded), errors.Is(err, context.DeadlineExceeded):
222 deliveryResult = "timeout"
223 case errors.Is(err, context.Canceled):
224 deliveryResult = "canceled"
225 case errors.As(err, &cerr):
226 deliveryResult = "temperror"
228 deliveryResult = "permerror"
231 deliveryResult = "error"
234 smtperr, ok := err.(smtpclient.Error)
235 var remoteMTA dsn.NameIP
237 remoteMTA.Name = transport.Host
239 qlog.Errorx("submitting email", err, slog.String("remote", addr))
240 permanent = smtperr.Permanent
241 secodeOpt = smtperr.Secode
242 errmsg = fmt.Sprintf("transport %s: submitting email to %s: %v", transportName, addr, err)
243 fail(ctx, qlog, m, backoff, permanent, remoteMTA, secodeOpt, errmsg)
246 qlog.Info("delivered from queue with transport")
247 if err := queueDelete(context.Background(), m.ID); err != nil {
248 qlog.Errorx("deleting message from queue after delivery", err)