1// Package smtpclient is an SMTP client, for submitting to an SMTP server or
2// delivering from a queue.
3//
4// Email clients can submit a message to SMTP server, after which the server is
5// responsible for delivery to the final destination. A submission client
6// typically connects with TLS, and PKIX-verifies the server's certificate. The
7// client then authenticates using a SASL mechanism.
8//
9// Email servers manage a message queue, from which they will try to deliver
10// messages. In case of temporary failures, the message is kept in the queue and
11// tried again later. For delivery, no authentication is done. TLS is opportunistic
12// by default (TLS certificates not verified), but TLS and certificate verification
13// can be opted into by domains by specifying an MTA-STS policy for the domain, or
14// DANE TLSA records for their MX hosts.
15//
16// Delivering a message from a queue would involve:
17// 1. Looking up an MTA-STS policy, through a cache.
18// 2. Resolving the MX targets for a domain, through smtpclient.GatherDestinations,
19// and for each destination try delivery through:
20// 3. Looking up IP addresses for the destination, with smtpclient.GatherIPs.
21// 4. Looking up TLSA records for DANE, in case of authentic DNS responses
22// (DNSSEC), with smtpclient.GatherTLSA.
23// 5. Dialing the MX target with smtpclient.Dial.
24// 6. Initializing a SMTP session with smtpclient.New, with proper TLS
25// configuration based on discovered MTA-STS and DANE policies, and finally calling
26// client.Deliver.
27package smtpclient
28
29import (
30 "bufio"
31 "bytes"
32 "context"
33 "crypto/tls"
34 "crypto/x509"
35 "encoding/base64"
36 "errors"
37 "fmt"
38 "io"
39 "log/slog"
40 "net"
41 "reflect"
42 "strconv"
43 "strings"
44 "time"
45
46 "github.com/mjl-/adns"
47
48 "github.com/mjl-/mox/dane"
49 "github.com/mjl-/mox/dns"
50 "github.com/mjl-/mox/mlog"
51 "github.com/mjl-/mox/moxio"
52 "github.com/mjl-/mox/sasl"
53 "github.com/mjl-/mox/smtp"
54 "github.com/mjl-/mox/stub"
55 "github.com/mjl-/mox/tlsrpt"
56)
57
58// todo future: add function to deliver message to multiple recipients. requires more elaborate return value, indicating success per message: some recipients may succeed, others may fail, and we should still deliver. to prevent backscatter, we also sometimes don't allow multiple recipients. ../rfc/5321:1144
59
60var (
61 MetricCommands stub.HistogramVec = stub.HistogramVecIgnore{}
62 MetricTLSRequiredNoIgnored stub.CounterVec = stub.CounterVecIgnore{}
63 MetricPanicInc = func() {}
64)
65
66var (
67 ErrSize = errors.New("message too large for remote smtp server") // SMTP server announced a maximum message size and the message to be delivered exceeds it.
68 Err8bitmimeUnsupported = errors.New("remote smtp server does not implement 8bitmime extension, required by message")
69 ErrSMTPUTF8Unsupported = errors.New("remote smtp server does not implement smtputf8 extension, required by message")
70 ErrRequireTLSUnsupported = errors.New("remote smtp server does not implement requiretls extension, required for delivery")
71 ErrStatus = errors.New("remote smtp server sent unexpected response status code") // Relatively common, e.g. when a 250 OK was expected and server sent 451 temporary error.
72 ErrProtocol = errors.New("smtp protocol error") // After a malformed SMTP response or inconsistent multi-line response.
73 ErrTLS = errors.New("tls error") // E.g. handshake failure, or hostname verification was required and failed.
74 ErrBotched = errors.New("smtp connection is botched") // Set on a client, and returned for new operations, after an i/o error or malformed SMTP response.
75 ErrClosed = errors.New("client is closed")
76)
77
78// TLSMode indicates if TLS must, should or must not be used.
79type TLSMode string
80
81const (
82 // TLS immediately ("implicit TLS"), directly starting TLS on the TCP connection,
83 // so not using STARTTLS. Whether PKIX and/or DANE is verified is specified
84 // separately.
85 TLSImmediate TLSMode = "immediate"
86
87 // Required TLS with STARTTLS for SMTP servers. The STARTTLS command is always
88 // executed, even if the server does not announce support.
89 // Whether PKIX and/or DANE is verified is specified separately.
90 TLSRequiredStartTLS TLSMode = "requiredstarttls"
91
92 // Use TLS with STARTTLS if remote claims to support it.
93 TLSOpportunistic TLSMode = "opportunistic"
94
95 // TLS must not be attempted, e.g. due to earlier TLS handshake error.
96 TLSSkip TLSMode = "skip"
97)
98
99// Client is an SMTP client that can deliver messages to a mail server.
100//
101// Use New to make a new client.
102type Client struct {
103 // OrigConn is the original (TCP) connection. We'll read from/write to conn, which
104 // can be wrapped in a tls.Client. We close origConn instead of conn because
105 // closing the TLS connection would send a TLS close notification, which may block
106 // for 5s if the server isn't reading it (because it is also sending it).
107 origConn net.Conn
108 conn net.Conn
109 tlsVerifyPKIX bool
110 ignoreTLSVerifyErrors bool
111 rootCAs *x509.CertPool
112 remoteHostname dns.Domain // TLS with SNI and name verification.
113 daneRecords []adns.TLSA // For authenticating (START)TLS connection.
114 daneMoreHostnames []dns.Domain // Additional allowed names in TLS certificate for DANE-TA.
115 daneVerifiedRecord *adns.TLSA // If non-nil, then will be set to verified DANE record if any.
116
117 // TLS connection success/failure are added. These are always non-nil, regardless
118 // of what was passed in opts. It lets us unconditionally dereference them.
119 recipientDomainResult *tlsrpt.Result // Either "sts" or "no-policy-found".
120 hostResult *tlsrpt.Result // Either "dane" or "no-policy-found".
121
122 r *bufio.Reader
123 w *bufio.Writer
124 tr *moxio.TraceReader // Kept for changing trace levels between cmd/auth/data.
125 tw *moxio.TraceWriter
126 log mlog.Log
127 lastlog time.Time // For adding delta timestamps between log lines.
128 cmds []string // Last or active command, for generating errors and metrics.
129 cmdStart time.Time // Start of command.
130 tls bool // Whether connection is TLS protected.
131 firstReadAfterHandshake bool // To detect TLS alert error from remote just after handshake.
132
133 botched bool // If set, protocol is out of sync and no further commands can be sent.
134 needRset bool // If set, a new delivery requires an RSET command.
135
136 remoteHelo string // From 220 greeting line.
137 extEcodes bool // Remote server supports sending extended error codes.
138 extStartTLS bool // Remote server supports STARTTLS.
139 ext8bitmime bool
140 extSize bool // Remote server supports SIZE parameter. Must only be used if > 0.
141 maxSize int64 // Max size of email message.
142 extPipelining bool // Remote server supports command pipelining.
143 extSMTPUTF8 bool // Remote server supports SMTPUTF8 extension.
144 extAuthMechanisms []string // Supported authentication mechanisms.
145 extRequireTLS bool // Remote supports REQUIRETLS extension.
146 ExtLimits map[string]string // For LIMITS extension, only if present and valid, with uppercase keys.
147 ExtLimitMailMax int // Max "MAIL" commands in a connection, if > 0.
148 ExtLimitRcptMax int // Max "RCPT" commands in a transaction, if > 0.
149 ExtLimitRcptDomainMax int // Max unique domains in a connection, if > 0.
150}
151
152// Error represents a failure to deliver a message.
153//
154// Code, Secode, Command and Line are only set for SMTP-level errors, and are zero
155// values otherwise.
156type Error struct {
157 // Whether failure is permanent, typically because of 5xx response.
158 Permanent bool
159 // SMTP response status, e.g. 2xx for success, 4xx for transient error and 5xx for
160 // permanent failure.
161 Code int
162 // Short enhanced status, minus first digit and dot. Can be empty, e.g. for io
163 // errors or if remote does not send enhanced status codes. If remote responds with
164 // "550 5.7.1 ...", the Secode will be "7.1".
165 Secode string
166 // SMTP command causing failure.
167 Command string
168 // For errors due to SMTP responses, the full SMTP line excluding CRLF that caused
169 // the error. First line of a multi-line response.
170 Line string
171 // Optional additional lines in case of multi-line SMTP response. Most SMTP
172 // responses are single-line, leaving this field empty.
173 MoreLines []string
174 // Underlying error, e.g. one of the Err variables in this package, or io errors.
175 Err error
176}
177
178type Response Error
179
180// Unwrap returns the underlying Err.
181func (e Error) Unwrap() error {
182 return e.Err
183}
184
185// Error returns a readable error string.
186func (e Error) Error() string {
187 s := ""
188 if e.Err != nil {
189 s = e.Err.Error() + ", "
190 }
191 if e.Permanent {
192 s += "permanent"
193 } else {
194 s += "transient"
195 }
196 if e.Line != "" {
197 s += ": " + e.Line
198 }
199 return s
200}
201
202// Opts influence behaviour of Client.
203type Opts struct {
204 // If auth is non-nil, authentication will be done with the returned sasl client.
205 // The function should select the preferred mechanism. Mechanisms are in upper
206 // case.
207 //
208 // The TLS connection state can be used for the SCRAM PLUS mechanisms, binding the
209 // authentication exchange to a TLS connection. It is only present for TLS
210 // connections.
211 //
212 // If no mechanism is supported, a nil client and nil error can be returned, and
213 // the connection will fail.
214 Auth func(mechanisms []string, cs *tls.ConnectionState) (sasl.Client, error)
215
216 DANERecords []adns.TLSA // If not nil, DANE records to verify.
217 DANEMoreHostnames []dns.Domain // For use with DANE, where additional certificate host names are allowed.
218 DANEVerifiedRecord *adns.TLSA // If non-empty, set to the DANE record that verified the TLS connection.
219
220 // If set, TLS verification errors (for DANE or PKIX) are ignored. Useful for
221 // delivering messages with message header "TLS-Required: No".
222 // Certificates are still verified, and results are still tracked for TLS
223 // reporting, but the connections will continue.
224 IgnoreTLSVerifyErrors bool
225
226 // If not nil, used instead of the system default roots for TLS PKIX verification.
227 RootCAs *x509.CertPool
228
229 // TLS verification successes/failures is added to these TLS reporting results.
230 // Once the STARTTLS handshake is attempted, a successful/failed connection is
231 // tracked.
232 RecipientDomainResult *tlsrpt.Result // MTA-STS or no policy.
233 HostResult *tlsrpt.Result // DANE or no policy.
234}
235
236// New initializes an SMTP session on the given connection, returning a client that
237// can be used to deliver messages.
238//
239// New optionally starts TLS (for submission), reads the server greeting,
240// identifies itself with a HELO or EHLO command, initializes TLS with STARTTLS if
241// remote supports it and optionally authenticates. If successful, a client is
242// returned on which eventually Close must be called. Otherwise an error is
243// returned and the caller is responsible for closing the connection.
244//
245// Connecting to the correct host for delivery can be done using the Gather
246// functions, and with Dial. The queue managing outgoing messages typically decides
247// which host to deliver to, taking multiple MX records with preferences, other DNS
248// records, MTA-STS, retries and special cases into account.
249//
250// tlsMode indicates if and how TLS may/must (not) be used.
251//
252// tlsVerifyPKIX indicates if TLS certificates must be validated against the
253// PKIX/WebPKI certificate authorities (if TLS is done).
254//
255// DANE-verification is done when opts.DANERecords is not nil.
256//
257// TLS verification errors will be ignored if opts.IgnoreTLSVerification is set.
258//
259// If TLS is done, PKIX verification is always performed for tracking the results
260// for TLS reporting, but if tlsVerifyPKIX is false, the verification result does
261// not affect the connection.
262//
263// At the time of writing, delivery of email on the internet is done with
264// opportunistic TLS without PKIX verification by default. Recipient domains can
265// opt-in to PKIX verification by publishing an MTA-STS policy, or opt-in to DANE
266// verification by publishing DNSSEC-protected TLSA records in DNS.
267func New(ctx context.Context, elog *slog.Logger, conn net.Conn, tlsMode TLSMode, tlsVerifyPKIX bool, ehloHostname, remoteHostname dns.Domain, opts Opts) (*Client, error) {
268 ensureResult := func(r *tlsrpt.Result) *tlsrpt.Result {
269 if r == nil {
270 return &tlsrpt.Result{}
271 }
272 return r
273 }
274
275 c := &Client{
276 origConn: conn,
277 tlsVerifyPKIX: tlsVerifyPKIX,
278 ignoreTLSVerifyErrors: opts.IgnoreTLSVerifyErrors,
279 rootCAs: opts.RootCAs,
280 remoteHostname: remoteHostname,
281 daneRecords: opts.DANERecords,
282 daneMoreHostnames: opts.DANEMoreHostnames,
283 daneVerifiedRecord: opts.DANEVerifiedRecord,
284 lastlog: time.Now(),
285 cmds: []string{"(none)"},
286 recipientDomainResult: ensureResult(opts.RecipientDomainResult),
287 hostResult: ensureResult(opts.HostResult),
288 }
289 c.log = mlog.New("smtpclient", elog).WithFunc(func() []slog.Attr {
290 now := time.Now()
291 l := []slog.Attr{
292 slog.Duration("delta", now.Sub(c.lastlog)),
293 }
294 c.lastlog = now
295 return l
296 })
297
298 if tlsMode == TLSImmediate {
299 config := c.tlsConfig()
300 tlsconn := tls.Client(conn, config)
301 // The tlsrpt tracking isn't used by caller, but won't hurt.
302 if err := tlsconn.HandshakeContext(ctx); err != nil {
303 c.tlsResultAdd(0, 1, err)
304 return nil, err
305 }
306 c.firstReadAfterHandshake = true
307 c.tlsResultAdd(1, 0, nil)
308 c.conn = tlsconn
309 tlsversion, ciphersuite := moxio.TLSInfo(tlsconn)
310 c.log.Debug("tls client handshake done",
311 slog.String("tls", tlsversion),
312 slog.String("ciphersuite", ciphersuite),
313 slog.Any("servername", remoteHostname))
314 c.tls = true
315 } else {
316 c.conn = conn
317 }
318
319 // We don't wrap reads in a timeoutReader for fear of an optional TLS wrapper doing
320 // reads without the client asking for it. Such reads could result in a timeout
321 // error.
322 c.tr = moxio.NewTraceReader(c.log, "RS: ", c.conn)
323 c.r = bufio.NewReader(c.tr)
324 // We use a single write timeout of 30 seconds.
325 // todo future: use different timeouts ../rfc/5321:3610
326 c.tw = moxio.NewTraceWriter(c.log, "LC: ", timeoutWriter{c.conn, 30 * time.Second, c.log})
327 c.w = bufio.NewWriter(c.tw)
328
329 if err := c.hello(ctx, tlsMode, ehloHostname, opts.Auth); err != nil {
330 return nil, err
331 }
332 return c, nil
333}
334
335// reportedError wraps an error while indicating it was already tracked for TLS
336// reporting.
337type reportedError struct{ err error }
338
339func (e reportedError) Error() string {
340 return e.err.Error()
341}
342
343func (e reportedError) Unwrap() error {
344 return e.err
345}
346
347func (c *Client) tlsConfig() *tls.Config {
348 // We always manage verification ourselves: We need to report in detail about
349 // failures. And we may have to verify both PKIX and DANE, record errors for
350 // each, and possibly ignore the errors.
351
352 verifyConnection := func(cs tls.ConnectionState) error {
353 // Collect verification errors. If there are none at the end, TLS validation
354 // succeeded. We may find validation problems below, record them for a TLS report
355 // but continue due to policies. We track the TLS reporting result in this
356 // function, wrapping errors in a reportedError.
357 var daneErr, pkixErr error
358
359 // DANE verification.
360 // daneRecords can be non-nil and empty, that's intended.
361 if c.daneRecords != nil {
362 verified, record, err := dane.Verify(c.log.Logger, c.daneRecords, cs, c.remoteHostname, c.daneMoreHostnames, c.rootCAs)
363 c.log.Debugx("dane verification", err, slog.Bool("verified", verified), slog.Any("record", record))
364 if verified {
365 if c.daneVerifiedRecord != nil {
366 *c.daneVerifiedRecord = record
367 }
368 } else {
369 // Track error for reports.
370 // todo spec: may want to propose adding a result for no-dane-match. dane allows multiple records, some mismatching/failing isn't fatal and reporting on each record is probably not productive. ../rfc/8460:541
371 fd := c.tlsrptFailureDetails(tlsrpt.ResultValidationFailure, "dane-no-match")
372 if err != nil {
373 // todo future: potentially add more details. e.g. dane-ta verification errors. tlsrpt does not have "result types" to indicate those kinds of errors. we would probably have to pass c.daneResult to dane.Verify.
374
375 // We may have encountered errors while evaluation some of the TLSA records.
376 fd.FailureReasonCode += "+errors"
377 }
378 c.hostResult.Add(0, 0, fd)
379
380 if c.ignoreTLSVerifyErrors {
381 // We ignore the failure and continue the connection.
382 c.log.Infox("verifying dane failed, continuing with connection", err)
383 MetricTLSRequiredNoIgnored.IncLabels("daneverification")
384 } else {
385 // This connection will fail.
386 daneErr = dane.ErrNoMatch
387 }
388 }
389 }
390
391 // PKIX verification.
392 opts := x509.VerifyOptions{
393 DNSName: cs.ServerName,
394 Intermediates: x509.NewCertPool(),
395 Roots: c.rootCAs,
396 }
397 for _, cert := range cs.PeerCertificates[1:] {
398 opts.Intermediates.AddCert(cert)
399 }
400 if _, err := cs.PeerCertificates[0].Verify(opts); err != nil {
401 resultType, reasonCode := tlsrpt.TLSFailureDetails(err)
402 fd := c.tlsrptFailureDetails(resultType, reasonCode)
403 c.recipientDomainResult.Add(0, 0, fd)
404
405 if c.tlsVerifyPKIX && !c.ignoreTLSVerifyErrors {
406 pkixErr = err
407 }
408 }
409
410 if daneErr != nil && pkixErr != nil {
411 return reportedError{errors.Join(daneErr, pkixErr)}
412 } else if daneErr != nil {
413 return reportedError{daneErr}
414 } else if pkixErr != nil {
415 return reportedError{pkixErr}
416 }
417 return nil
418 }
419
420 return &tls.Config{
421 ServerName: c.remoteHostname.ASCII, // For SNI.
422 // todo: possibly accept older TLS versions for TLSOpportunistic? or would our private key be at risk?
423 MinVersion: tls.VersionTLS12, // ../rfc/8996:31 ../rfc/8997:66
424 InsecureSkipVerify: true, // VerifyConnection below is called and will do all verification.
425 VerifyConnection: verifyConnection,
426 }
427}
428
429// xbotchf generates a temporary error and marks the client as botched. e.g. for
430// i/o errors or invalid protocol messages.
431func (c *Client) xbotchf(code int, secode string, firstLine string, moreLines []string, format string, args ...any) {
432 panic(c.botchf(code, secode, firstLine, moreLines, format, args...))
433}
434
435// botchf generates a temporary error and marks the client as botched. e.g. for
436// i/o errors or invalid protocol messages.
437func (c *Client) botchf(code int, secode string, firstLine string, moreLines []string, format string, args ...any) error {
438 c.botched = true
439 return c.errorf(false, code, secode, firstLine, moreLines, format, args...)
440}
441
442func (c *Client) errorf(permanent bool, code int, secode, firstLine string, moreLines []string, format string, args ...any) error {
443 var cmd string
444 if len(c.cmds) > 0 {
445 cmd = c.cmds[0]
446 }
447 return Error{permanent, code, secode, cmd, firstLine, moreLines, fmt.Errorf(format, args...)}
448}
449
450func (c *Client) xerrorf(permanent bool, code int, secode, firstLine string, moreLines []string, format string, args ...any) {
451 panic(c.errorf(permanent, code, secode, firstLine, moreLines, format, args...))
452}
453
454// timeoutWriter passes each Write on to conn after setting a write deadline on conn based on
455// timeout.
456type timeoutWriter struct {
457 conn net.Conn
458 timeout time.Duration
459 log mlog.Log
460}
461
462func (w timeoutWriter) Write(buf []byte) (int, error) {
463 if err := w.conn.SetWriteDeadline(time.Now().Add(w.timeout)); err != nil {
464 w.log.Errorx("setting write deadline", err)
465 }
466
467 return w.conn.Write(buf)
468}
469
470var bufs = moxio.NewBufpool(8, 2*1024)
471
472func (c *Client) readline() (string, error) {
473 // todo: could have per-operation timeouts. and rfc suggests higher minimum timeouts. ../rfc/5321:3610
474 if err := c.conn.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil {
475 c.log.Errorx("setting read deadline", err)
476 }
477
478 line, err := bufs.Readline(c.log, c.r)
479 if err != nil {
480 // See if this is a TLS alert from remote, and one other than 0 (which notifies
481 // that the connection is being closed. If so, we register a TLS connection
482 // failure. This handles TLS alerts that happen just after a successful handshake.
483 var netErr *net.OpError
484 if c.firstReadAfterHandshake && errors.As(err, &netErr) && netErr.Op == "remote error" && netErr.Err != nil && reflect.ValueOf(netErr.Err).Kind() == reflect.Uint8 && reflect.ValueOf(netErr.Err).Uint() != 0 {
485 resultType, reasonCode := tlsrpt.TLSFailureDetails(err)
486 // We count -1 success to compensate for the assumed success right after the handshake.
487 c.tlsResultAddFailureDetails(-1, 1, c.tlsrptFailureDetails(resultType, reasonCode))
488 }
489
490 return line, c.botchf(0, "", "", nil, "%s: %w", strings.Join(c.cmds, ","), err)
491 }
492 c.firstReadAfterHandshake = false
493 return line, nil
494}
495
496func (c *Client) xtrace(level slog.Level) func() {
497 c.xflush()
498 c.tr.SetTrace(level)
499 c.tw.SetTrace(level)
500 return func() {
501 c.xflush()
502 c.tr.SetTrace(mlog.LevelTrace)
503 c.tw.SetTrace(mlog.LevelTrace)
504 }
505}
506
507func (c *Client) xwritelinef(format string, args ...any) {
508 c.xbwritelinef(format, args...)
509 c.xflush()
510}
511
512func (c *Client) xwriteline(line string) {
513 c.xbwriteline(line)
514 c.xflush()
515}
516
517func (c *Client) xbwritelinef(format string, args ...any) {
518 c.xbwriteline(fmt.Sprintf(format, args...))
519}
520
521func (c *Client) xbwriteline(line string) {
522 _, err := fmt.Fprintf(c.w, "%s\r\n", line)
523 if err != nil {
524 c.xbotchf(0, "", "", nil, "write: %w", err)
525 }
526}
527
528func (c *Client) xflush() {
529 err := c.w.Flush()
530 if err != nil {
531 c.xbotchf(0, "", "", nil, "writes: %w", err)
532 }
533}
534
535// read response, possibly multiline, with supporting extended codes based on configuration in client.
536func (c *Client) xread() (code int, secode, firstLine string, moreLines []string) {
537 var err error
538 code, secode, firstLine, moreLines, err = c.read()
539 if err != nil {
540 panic(err)
541 }
542 return
543}
544
545func (c *Client) read() (code int, secode, firstLine string, moreLines []string, rerr error) {
546 code, secode, _, firstLine, moreLines, _, rerr = c.readecode(c.extEcodes)
547 return
548}
549
550// read response, possibly multiline.
551// if ecodes, extended codes are parsed.
552func (c *Client) readecode(ecodes bool) (code int, secode, lastText, firstLine string, moreLines, moreTexts []string, rerr error) {
553 first := true
554 for {
555 co, sec, text, line, last, err := c.read1(ecodes)
556 if first {
557 firstLine = line
558 first = false
559 } else if line != "" {
560 moreLines = append(moreLines, line)
561 if text != "" {
562 moreTexts = append(moreTexts, text)
563 }
564 }
565 if err != nil {
566 rerr = err
567 return
568 }
569 if code != 0 && co != code {
570 // ../rfc/5321:2771
571 err := c.botchf(0, "", firstLine, moreLines, "%w: multiline response with different codes, previous %d, last %d", ErrProtocol, code, co)
572 return 0, "", "", "", nil, nil, err
573 }
574 code = co
575 if last {
576 if code != smtp.C334ContinueAuth {
577 cmd := ""
578 if len(c.cmds) > 0 {
579 cmd = c.cmds[0]
580 // We only keep the last, so we're not creating new slices all the time.
581 if len(c.cmds) > 1 {
582 c.cmds = c.cmds[1:]
583 }
584 }
585 MetricCommands.ObserveLabels(float64(time.Since(c.cmdStart))/float64(time.Second), cmd, fmt.Sprintf("%d", co), sec)
586 c.log.Debug("smtpclient command result",
587 slog.String("cmd", cmd),
588 slog.Int("code", co),
589 slog.String("secode", sec),
590 slog.Duration("duration", time.Since(c.cmdStart)))
591 }
592 return co, sec, text, firstLine, moreLines, moreTexts, nil
593 }
594 }
595}
596
597func (c *Client) xreadecode(ecodes bool) (code int, secode, lastText, firstLine string, moreLines, moreTexts []string) {
598 var err error
599 code, secode, lastText, firstLine, moreLines, moreTexts, err = c.readecode(ecodes)
600 if err != nil {
601 panic(err)
602 }
603 return
604}
605
606// read single response line.
607// if ecodes, extended codes are parsed.
608func (c *Client) read1(ecodes bool) (code int, secode, text, line string, last bool, rerr error) {
609 line, rerr = c.readline()
610 if rerr != nil {
611 return
612 }
613 i := 0
614 for ; i < len(line) && line[i] >= '0' && line[i] <= '9'; i++ {
615 }
616 if i != 3 {
617 rerr = c.botchf(0, "", line, nil, "%w: expected response code: %s", ErrProtocol, line)
618 return
619 }
620 v, err := strconv.ParseInt(line[:i], 10, 32)
621 if err != nil {
622 rerr = c.botchf(0, "", line, nil, "%w: bad response code (%s): %s", ErrProtocol, err, line)
623 return
624 }
625 code = int(v)
626 major := code / 100
627 s := line[3:]
628 if strings.HasPrefix(s, "-") || strings.HasPrefix(s, " ") {
629 last = s[0] == ' '
630 s = s[1:]
631 } else if s == "" {
632 // Allow missing space. ../rfc/5321:2570 ../rfc/5321:2612
633 last = true
634 } else {
635 rerr = c.botchf(0, "", line, nil, "%w: expected space or dash after response code: %s", ErrProtocol, line)
636 return
637 }
638
639 if ecodes {
640 secode, s = parseEcode(major, s)
641 }
642
643 return code, secode, s, line, last, nil
644}
645
646func parseEcode(major int, s string) (secode string, remain string) {
647 o := 0
648 bad := false
649 take := func(need bool, a, b byte) bool {
650 if !bad && o < len(s) && s[o] >= a && s[o] <= b {
651 o++
652 return true
653 }
654 bad = bad || need
655 return false
656 }
657 digit := func(need bool) bool {
658 return take(need, '0', '9')
659 }
660 dot := func() bool {
661 return take(true, '.', '.')
662 }
663
664 digit(true)
665 dot()
666 xo := o
667 digit(true)
668 for digit(false) {
669 }
670 dot()
671 digit(true)
672 for digit(false) {
673 }
674 secode = s[xo:o]
675 take(false, ' ', ' ')
676 if bad || int(s[0])-int('0') != major {
677 return "", s
678 }
679 return secode, s[o:]
680}
681
682func (c *Client) recover(rerr *error) {
683 x := recover()
684 if x == nil {
685 return
686 }
687 cerr, ok := x.(Error)
688 if !ok {
689 MetricPanicInc()
690 panic(x)
691 }
692 *rerr = cerr
693}
694
695func (c *Client) hello(ctx context.Context, tlsMode TLSMode, ehloHostname dns.Domain, auth func(mechanisms []string, cs *tls.ConnectionState) (sasl.Client, error)) (rerr error) {
696 defer c.recover(&rerr)
697
698 // perform EHLO handshake, falling back to HELO if server does not appear to
699 // implement EHLO.
700 hello := func(heloOK bool) {
701 // Write EHLO and parse the supported extensions.
702 // ../rfc/5321:987
703 c.cmds[0] = "ehlo"
704 c.cmdStart = time.Now()
705 // Syntax: ../rfc/5321:1827
706 c.xwritelinef("EHLO %s", ehloHostname.ASCII)
707 code, _, _, firstLine, moreLines, moreTexts := c.xreadecode(false)
708 switch code {
709 // ../rfc/5321:997
710 // ../rfc/5321:3098
711 case smtp.C500BadSyntax, smtp.C501BadParamSyntax, smtp.C502CmdNotImpl, smtp.C503BadCmdSeq, smtp.C504ParamNotImpl:
712 if !heloOK {
713 c.xerrorf(true, code, "", firstLine, moreLines, "%w: remote claims ehlo is not supported", ErrProtocol)
714 }
715 // ../rfc/5321:996
716 c.cmds[0] = "helo"
717 c.cmdStart = time.Now()
718 c.xwritelinef("HELO %s", ehloHostname.ASCII)
719 code, _, _, firstLine, _, _ = c.xreadecode(false)
720 if code != smtp.C250Completed {
721 c.xerrorf(code/100 == 5, code, "", firstLine, moreLines, "%w: expected 250 to HELO, got %d", ErrStatus, code)
722 }
723 return
724 case smtp.C250Completed:
725 default:
726 c.xerrorf(code/100 == 5, code, "", firstLine, moreLines, "%w: expected 250, got %d", ErrStatus, code)
727 }
728 for _, s := range moreTexts {
729 // ../rfc/5321:1869
730 s = strings.ToUpper(strings.TrimSpace(s))
731 switch s {
732 case "STARTTLS":
733 c.extStartTLS = true
734 case "ENHANCEDSTATUSCODES":
735 c.extEcodes = true
736 case "8BITMIME":
737 c.ext8bitmime = true
738 case "PIPELINING":
739 c.extPipelining = true
740 case "REQUIRETLS":
741 c.extRequireTLS = true
742 default:
743 // For SMTPUTF8 we must ignore any parameter. ../rfc/6531:207
744 if s == "SMTPUTF8" || strings.HasPrefix(s, "SMTPUTF8 ") {
745 c.extSMTPUTF8 = true
746 } else if strings.HasPrefix(s, "SIZE ") {
747 // ../rfc/1870:77
748 c.extSize = true
749 if v, err := strconv.ParseInt(s[len("SIZE "):], 10, 64); err == nil {
750 c.maxSize = v
751 }
752 } else if strings.HasPrefix(s, "AUTH ") {
753 c.extAuthMechanisms = strings.Split(s[len("AUTH "):], " ")
754 } else if strings.HasPrefix(s, "LIMITS ") {
755 c.ExtLimits, c.ExtLimitMailMax, c.ExtLimitRcptMax, c.ExtLimitRcptDomainMax = parseLimits([]byte(s[len("LIMITS"):]))
756 }
757 }
758 }
759 }
760
761 // Read greeting.
762 c.cmds = []string{"(greeting)"}
763 c.cmdStart = time.Now()
764 code, _, _, firstLine, moreLines, _ := c.xreadecode(false)
765 if code != smtp.C220ServiceReady {
766 c.xerrorf(code/100 == 5, code, "", firstLine, moreLines, "%w: expected 220, got %d", ErrStatus, code)
767 }
768 // ../rfc/5321:2588
769 _, c.remoteHelo, _ = strings.Cut(firstLine, " ")
770
771 // Write EHLO, falling back to HELO if server doesn't appear to support it.
772 hello(true)
773
774 // Attempt TLS if remote understands STARTTLS and we aren't doing immediate TLS or if caller requires it.
775 if c.extStartTLS && tlsMode == TLSOpportunistic || tlsMode == TLSRequiredStartTLS {
776 c.log.Debug("starting tls client", slog.Any("tlsmode", tlsMode), slog.Any("servername", c.remoteHostname))
777 c.cmds[0] = "starttls"
778 c.cmdStart = time.Now()
779 c.xwritelinef("STARTTLS")
780 code, secode, firstLine, _ := c.xread()
781 // ../rfc/3207:107
782 if code != smtp.C220ServiceReady {
783 c.tlsResultAddFailureDetails(0, 1, c.tlsrptFailureDetails(tlsrpt.ResultSTARTTLSNotSupported, fmt.Sprintf("smtp-starttls-reply-code-%d", code)))
784 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "%w: STARTTLS: got %d, expected 220", ErrTLS, code)
785 }
786
787 // We don't want to do TLS on top of c.r because it also prints protocol traces: We
788 // don't want to log the TLS stream. So we'll do TLS on the underlying connection,
789 // but make sure any bytes already read and in the buffer are used for the TLS
790 // handshake.
791 conn := c.conn
792 if n := c.r.Buffered(); n > 0 {
793 conn = &moxio.PrefixConn{
794 PrefixReader: io.LimitReader(c.r, int64(n)),
795 Conn: conn,
796 }
797 }
798
799 tlsConfig := c.tlsConfig()
800 nconn := tls.Client(conn, tlsConfig)
801 c.conn = nconn
802
803 nctx, cancel := context.WithTimeout(ctx, time.Minute)
804 defer cancel()
805 err := nconn.HandshakeContext(nctx)
806 if err != nil {
807 // For each STARTTLS failure, we track a failed TLS session. For deliveries with
808 // multiple MX targets, we may add multiple failures, and delivery may succeed with
809 // a later MX target with which we can do STARTTLS. ../rfc/8460:524
810 c.tlsResultAdd(0, 1, err)
811 c.xerrorf(false, 0, "", "", nil, "%w: STARTTLS TLS handshake: %s", ErrTLS, err)
812 }
813 c.firstReadAfterHandshake = true
814 cancel()
815 c.tr = moxio.NewTraceReader(c.log, "RS: ", c.conn)
816 c.tw = moxio.NewTraceWriter(c.log, "LC: ", c.conn) // No need to wrap in timeoutWriter, it would just set the timeout on the underlying connection, which is still active.
817 c.r = bufio.NewReader(c.tr)
818 c.w = bufio.NewWriter(c.tw)
819
820 tlsversion, ciphersuite := moxio.TLSInfo(nconn)
821 c.log.Debug("starttls client handshake done",
822 slog.Any("tlsmode", tlsMode),
823 slog.Bool("verifypkix", c.tlsVerifyPKIX),
824 slog.Bool("verifydane", c.daneRecords != nil),
825 slog.Bool("ignoretlsverifyerrors", c.ignoreTLSVerifyErrors),
826 slog.String("tls", tlsversion),
827 slog.String("ciphersuite", ciphersuite),
828 slog.Any("servername", c.remoteHostname),
829 slog.Any("danerecord", c.daneVerifiedRecord))
830 c.tls = true
831 // Track successful TLS connection. ../rfc/8460:515
832 c.tlsResultAdd(1, 0, nil)
833
834 hello(false)
835 } else if tlsMode == TLSOpportunistic {
836 // Result: ../rfc/8460:538
837 c.tlsResultAddFailureDetails(0, 0, c.tlsrptFailureDetails(tlsrpt.ResultSTARTTLSNotSupported, ""))
838 }
839
840 if auth != nil {
841 return c.auth(auth)
842 }
843 return
844}
845
846// parse text after "LIMITS", including leading space.
847func parseLimits(b []byte) (map[string]string, int, int, int) {
848 // ../rfc/9422:150
849 var o int
850 // Read next " name=value".
851 pair := func() ([]byte, []byte) {
852 if o >= len(b) || b[o] != ' ' {
853 return nil, nil
854 }
855 o++
856
857 ns := o
858 for o < len(b) {
859 c := b[o]
860 if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_' {
861 o++
862 } else {
863 break
864 }
865 }
866 es := o
867 if ns == es || o >= len(b) || b[o] != '=' {
868 return nil, nil
869 }
870 o++
871 vs := o
872 for o < len(b) {
873 c := b[o]
874 if c > 0x20 && c < 0x7f && c != ';' {
875 o++
876 } else {
877 break
878 }
879 }
880 if vs == o {
881 return nil, nil
882 }
883 return b[ns:es], b[vs:o]
884 }
885 limits := map[string]string{}
886 var mailMax, rcptMax, rcptDomainMax int
887 for o < len(b) {
888 name, value := pair()
889 if name == nil {
890 // We skip the entire LIMITS extension for syntax errors. ../rfc/9422:232
891 return nil, 0, 0, 0
892 }
893 k := strings.ToUpper(string(name))
894 if _, ok := limits[k]; ok {
895 // Not specified, but we treat duplicates as error.
896 return nil, 0, 0, 0
897 }
898 limits[k] = string(value)
899 // For individual value syntax errors, we skip that value, leaving the default 0.
900 // ../rfc/9422:254
901 switch string(name) {
902 case "MAILMAX":
903 if v, err := strconv.Atoi(string(value)); err == nil && v > 0 && len(value) <= 6 {
904 mailMax = v
905 }
906 case "RCPTMAX":
907 if v, err := strconv.Atoi(string(value)); err == nil && v > 0 && len(value) <= 6 {
908 rcptMax = v
909 }
910 case "RCPTDOMAINMAX":
911 if v, err := strconv.Atoi(string(value)); err == nil && v > 0 && len(value) <= 6 {
912 rcptDomainMax = v
913 }
914 }
915 }
916 return limits, mailMax, rcptMax, rcptDomainMax
917}
918
919func addrIP(addr net.Addr) string {
920 if t, ok := addr.(*net.TCPAddr); ok {
921 return t.IP.String()
922 }
923 host, _, _ := net.SplitHostPort(addr.String())
924 ip := net.ParseIP(host)
925 if ip == nil {
926 return "" // For pipe during tests.
927 }
928 return ip.String()
929}
930
931// tlsrptFailureDetails returns FailureDetails with connection details (such as
932// IP addresses) for inclusion in a TLS report.
933func (c *Client) tlsrptFailureDetails(resultType tlsrpt.ResultType, reasonCode string) tlsrpt.FailureDetails {
934 return tlsrpt.FailureDetails{
935 ResultType: resultType,
936 SendingMTAIP: addrIP(c.origConn.LocalAddr()),
937 ReceivingMXHostname: c.remoteHostname.ASCII,
938 ReceivingMXHelo: c.remoteHelo,
939 ReceivingIP: addrIP(c.origConn.RemoteAddr()),
940 FailedSessionCount: 1,
941 FailureReasonCode: reasonCode,
942 }
943}
944
945// tlsResultAdd adds TLS success/failure to all results.
946func (c *Client) tlsResultAdd(success, failure int64, err error) {
947 // Only track failure if not already done so in tls.Config.VerifyConnection.
948 var fds []tlsrpt.FailureDetails
949 var repErr reportedError
950 if err != nil && !errors.As(err, &repErr) {
951 resultType, reasonCode := tlsrpt.TLSFailureDetails(err)
952 fd := c.tlsrptFailureDetails(resultType, reasonCode)
953 fds = []tlsrpt.FailureDetails{fd}
954 }
955 c.tlsResultAddFailureDetails(success, failure, fds...)
956}
957
958func (c *Client) tlsResultAddFailureDetails(success, failure int64, fds ...tlsrpt.FailureDetails) {
959 c.recipientDomainResult.Add(success, failure, fds...)
960 c.hostResult.Add(success, failure, fds...)
961}
962
963// ../rfc/4954:139
964func (c *Client) auth(auth func(mechanisms []string, cs *tls.ConnectionState) (sasl.Client, error)) (rerr error) {
965 defer c.recover(&rerr)
966
967 c.cmds[0] = "auth"
968 c.cmdStart = time.Now()
969
970 mechanisms := make([]string, len(c.extAuthMechanisms))
971 for i, m := range c.extAuthMechanisms {
972 mechanisms[i] = strings.ToUpper(m)
973 }
974 a, err := auth(mechanisms, c.TLSConnectionState())
975 if err != nil {
976 c.xerrorf(true, 0, "", "", nil, "get authentication mechanism: %s, server supports %s", err, strings.Join(c.extAuthMechanisms, ", "))
977 } else if a == nil {
978 c.xerrorf(true, 0, "", "", nil, "no matching authentication mechanisms, server supports %s", strings.Join(c.extAuthMechanisms, ", "))
979 }
980 name, cleartextCreds := a.Info()
981
982 abort := func() (int, string, string, []string) {
983 // Abort authentication. ../rfc/4954:193
984 c.xwriteline("*")
985
986 // Server must respond with 501. // ../rfc/4954:195
987 code, secode, firstLine, moreLines := c.xread()
988 if code != smtp.C501BadParamSyntax {
989 c.botched = true
990 }
991 return code, secode, firstLine, moreLines
992 }
993
994 toserver, last, err := a.Next(nil)
995 if err != nil {
996 c.xerrorf(false, 0, "", "", nil, "initial step in auth mechanism %s: %w", name, err)
997 }
998 if cleartextCreds {
999 defer c.xtrace(mlog.LevelTraceauth)()
1000 }
1001 if toserver == nil {
1002 c.xwriteline("AUTH " + name)
1003 } else if len(toserver) == 0 {
1004 c.xwriteline("AUTH " + name + " =") // ../rfc/4954:214
1005 } else {
1006 c.xwriteline("AUTH " + name + " " + base64.StdEncoding.EncodeToString(toserver))
1007 }
1008 for {
1009 if cleartextCreds && last {
1010 c.xtrace(mlog.LevelTrace) // Restore.
1011 }
1012
1013 code, secode, lastText, firstLine, moreLines, _ := c.xreadecode(last)
1014 if code == smtp.C235AuthSuccess {
1015 if !last {
1016 c.xerrorf(false, code, secode, firstLine, moreLines, "server completed authentication earlier than client expected")
1017 }
1018 return nil
1019 } else if code == smtp.C334ContinueAuth {
1020 if last {
1021 c.xerrorf(false, code, secode, firstLine, moreLines, "server requested unexpected continuation of authentication")
1022 }
1023 if len(moreLines) > 0 {
1024 abort()
1025 c.xerrorf(false, code, secode, firstLine, moreLines, "server responded with multiline contination")
1026 }
1027 fromserver, err := base64.StdEncoding.DecodeString(lastText)
1028 if err != nil {
1029 abort()
1030 c.xerrorf(false, code, secode, firstLine, moreLines, "malformed base64 data in authentication continuation response")
1031 }
1032 toserver, last, err = a.Next(fromserver)
1033 if err != nil {
1034 // For failing SCRAM, the client stops due to message about invalid proof. The
1035 // server still sends an authentication result (it probably should send 501
1036 // instead).
1037 xcode, xsecode, xfirstLine, xmoreLines := abort()
1038 c.xerrorf(false, xcode, xsecode, xfirstLine, xmoreLines, "client aborted authentication: %w", err)
1039 }
1040 c.xwriteline(base64.StdEncoding.EncodeToString(toserver))
1041 } else {
1042 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "unexpected response during authentication, expected 334 continue or 235 auth success")
1043 }
1044 }
1045}
1046
1047// Supports8BITMIME returns whether the SMTP server supports the 8BITMIME
1048// extension, needed for sending data with non-ASCII bytes.
1049func (c *Client) Supports8BITMIME() bool {
1050 return c.ext8bitmime
1051}
1052
1053// SupportsSMTPUTF8 returns whether the SMTP server supports the SMTPUTF8
1054// extension, needed for sending messages with UTF-8 in headers or in an (SMTP)
1055// address.
1056func (c *Client) SupportsSMTPUTF8() bool {
1057 return c.extSMTPUTF8
1058}
1059
1060// SupportsStartTLS returns whether the SMTP server supports the STARTTLS
1061// extension.
1062func (c *Client) SupportsStartTLS() bool {
1063 return c.extStartTLS
1064}
1065
1066// SupportsRequireTLS returns whether the SMTP server supports the REQUIRETLS
1067// extension. The REQUIRETLS extension is only announced after enabling
1068// STARTTLS.
1069func (c *Client) SupportsRequireTLS() bool {
1070 return c.extRequireTLS
1071}
1072
1073// TLSConnectionState returns TLS details if TLS is enabled, and nil otherwise.
1074func (c *Client) TLSConnectionState() *tls.ConnectionState {
1075 if tlsConn, ok := c.conn.(*tls.Conn); ok {
1076 cs := tlsConn.ConnectionState()
1077 return &cs
1078 }
1079 return nil
1080}
1081
1082// Deliver attempts to deliver a message to a mail server.
1083//
1084// mailFrom must be an email address, or empty in case of a DSN. rcptTo must be
1085// an email address.
1086//
1087// If the message contains bytes with the high bit set, req8bitmime must be true. If
1088// set, the remote server must support the 8BITMIME extension or delivery will
1089// fail.
1090//
1091// If the message is internationalized, e.g. when headers contain non-ASCII
1092// character, or when UTF-8 is used in a localpart, reqSMTPUTF8 must be true. If set,
1093// the remote server must support the SMTPUTF8 extension or delivery will fail.
1094//
1095// If requireTLS is true, the remote server must support the REQUIRETLS
1096// extension, or delivery will fail.
1097//
1098// Deliver uses the following SMTP extensions if the remote server supports them:
1099// 8BITMIME, SMTPUTF8, SIZE, PIPELINING, ENHANCEDSTATUSCODES, STARTTLS.
1100//
1101// Returned errors can be of type Error, one of the Err-variables in this package
1102// or other underlying errors, e.g. for i/o. Use errors.Is to check.
1103func (c *Client) Deliver(ctx context.Context, mailFrom string, rcptTo string, msgSize int64, msg io.Reader, req8bitmime, reqSMTPUTF8, requireTLS bool) (rerr error) {
1104 _, err := c.DeliverMultiple(ctx, mailFrom, []string{rcptTo}, msgSize, msg, req8bitmime, reqSMTPUTF8, requireTLS)
1105 return err
1106}
1107
1108var errNoRecipientsPipelined = errors.New("no recipients accepted in pipelined transaction")
1109var errNoRecipients = errors.New("no recipients accepted in transaction")
1110
1111// DeliverMultiple is like Deliver, but attempts to deliver a message to multiple
1112// recipients. Errors about the entire transaction, such as i/o errors or error
1113// responses to the MAIL FROM or DATA commands, are returned by a non-nil rerr. If
1114// rcptTo has a single recipient, an error to the RCPT TO command is returned in
1115// rerr instead of rcptResps. Otherwise, the SMTP response for each recipient is
1116// returned in rcptResps.
1117//
1118// The caller should take extLimit* into account when sending. And recognize
1119// recipient response code "452" to mean that a recipient limit was reached,
1120// another transaction can be attempted immediately after instead of marking the
1121// delivery attempt as failed. Also code "552" must be treated like temporary error
1122// code "452" for historic reasons.
1123func (c *Client) DeliverMultiple(ctx context.Context, mailFrom string, rcptTo []string, msgSize int64, msg io.Reader, req8bitmime, reqSMTPUTF8, requireTLS bool) (rcptResps []Response, rerr error) {
1124 defer c.recover(&rerr)
1125
1126 if len(rcptTo) == 0 {
1127 return nil, fmt.Errorf("need at least one recipient")
1128 }
1129
1130 if c.origConn == nil {
1131 return nil, ErrClosed
1132 } else if c.botched {
1133 return nil, ErrBotched
1134 } else if c.needRset {
1135 if err := c.Reset(); err != nil {
1136 return nil, err
1137 }
1138 }
1139
1140 if !c.ext8bitmime && req8bitmime {
1141 // Temporary error, e.g. OpenBSD spamd does not announce 8bitmime support, but once
1142 // you get through, the mail server behind it probably does. Just needs a few
1143 // retries.
1144 c.xerrorf(false, 0, "", "", nil, "%w", Err8bitmimeUnsupported)
1145 }
1146 if !c.extSMTPUTF8 && reqSMTPUTF8 {
1147 // ../rfc/6531:313
1148 c.xerrorf(false, 0, "", "", nil, "%w", ErrSMTPUTF8Unsupported)
1149 }
1150 if !c.extRequireTLS && requireTLS {
1151 c.xerrorf(false, 0, "", "", nil, "%w", ErrRequireTLSUnsupported)
1152 }
1153
1154 // Max size enforced, only when not zero. ../rfc/1870:79
1155 if c.extSize && c.maxSize > 0 && msgSize > c.maxSize {
1156 c.xerrorf(true, 0, "", "", nil, "%w: message is %d bytes, remote has a %d bytes maximum size", ErrSize, msgSize, c.maxSize)
1157 }
1158
1159 var mailSize, bodyType string
1160 if c.extSize {
1161 mailSize = fmt.Sprintf(" SIZE=%d", msgSize)
1162 }
1163 if c.ext8bitmime {
1164 if req8bitmime {
1165 bodyType = " BODY=8BITMIME"
1166 } else {
1167 bodyType = " BODY=7BIT"
1168 }
1169 }
1170 var smtputf8Arg string
1171 if reqSMTPUTF8 {
1172 // ../rfc/6531:213
1173 smtputf8Arg = " SMTPUTF8"
1174 }
1175 var requiretlsArg string
1176 if requireTLS {
1177 // ../rfc/8689:155
1178 requiretlsArg = " REQUIRETLS"
1179 }
1180
1181 // Transaction overview: ../rfc/5321:1015
1182 // MAIL FROM: ../rfc/5321:1879
1183 // RCPT TO: ../rfc/5321:1916
1184 // DATA: ../rfc/5321:1992
1185 lineMailFrom := fmt.Sprintf("MAIL FROM:<%s>%s%s%s%s", mailFrom, mailSize, bodyType, smtputf8Arg, requiretlsArg)
1186
1187 // We are going into a transaction. We'll clear this when done.
1188 c.needRset = true
1189
1190 if c.extPipelining {
1191 c.cmds = make([]string, 1+len(rcptTo)+1)
1192 c.cmds[0] = "mailfrom"
1193 for i := range rcptTo {
1194 c.cmds[1+i] = "rcptto"
1195 }
1196 c.cmds[len(c.cmds)-1] = "data"
1197 c.cmdStart = time.Now()
1198
1199 // Write and read in separte goroutines. Otherwise, writing a large recipient list
1200 // could block when a server doesn't read more commands before we read their
1201 // response.
1202 errc := make(chan error, 1)
1203 // Make sure we don't return before we're done writing to the connection.
1204 defer func() {
1205 if errc != nil {
1206 <-errc
1207 }
1208 }()
1209 go func() {
1210 var b bytes.Buffer
1211 b.WriteString(lineMailFrom)
1212 b.WriteString("\r\n")
1213 for _, rcpt := range rcptTo {
1214 b.WriteString("RCPT TO:<")
1215 b.WriteString(rcpt)
1216 b.WriteString(">\r\n")
1217 }
1218 b.WriteString("DATA\r\n")
1219 _, err := c.w.Write(b.Bytes())
1220 if err == nil {
1221 err = c.w.Flush()
1222 }
1223 errc <- err
1224 }()
1225
1226 // Read response to MAIL FROM.
1227 mfcode, mfsecode, mffirstLine, mfmoreLines := c.xread()
1228
1229 // We read the response to RCPT TOs and DATA without panic on read error. Servers
1230 // may be aborting the connection after a failed MAIL FROM, e.g. outlook when it
1231 // has blocklisted your IP. We don't want the read for the response to RCPT TO to
1232 // cause a read error as it would result in an unhelpful error message and a
1233 // temporary instead of permanent error code.
1234
1235 // Read responses to RCPT TO.
1236 rcptResps = make([]Response, len(rcptTo))
1237 nok := 0
1238 for i := 0; i < len(rcptTo); i++ {
1239 code, secode, firstLine, moreLines, err := c.read()
1240 // 552 should be treated as temporary historically, ../rfc/5321:3576
1241 permanent := code/100 == 5 && code != smtp.C552MailboxFull
1242 rcptResps[i] = Response{permanent, code, secode, "rcptto", firstLine, moreLines, err}
1243 if code == smtp.C250Completed {
1244 nok++
1245 }
1246 }
1247
1248 // Read response to DATA.
1249 datacode, datasecode, datafirstLine, datamoreLines, dataerr := c.read()
1250
1251 writeerr := <-errc
1252 errc = nil
1253
1254 // If MAIL FROM failed, it's an error for the entire transaction. We may have been
1255 // blocked.
1256 if mfcode != smtp.C250Completed {
1257 if writeerr != nil || dataerr != nil {
1258 c.botched = true
1259 }
1260 c.xerrorf(mfcode/100 == 5, mfcode, mfsecode, mffirstLine, mfmoreLines, "%w: got %d, expected 2xx", ErrStatus, mfcode)
1261 }
1262
1263 // If there was an i/o error writing the commands, there is no point continuing.
1264 if writeerr != nil {
1265 c.xbotchf(0, "", "", nil, "writing pipelined mail/rcpt/data: %w", writeerr)
1266 }
1267
1268 // If the data command had an i/o or protocol error, it's also a failure for the
1269 // entire transaction.
1270 if dataerr != nil {
1271 panic(dataerr)
1272 }
1273
1274 // If we didn't have any successful recipient, there is no point in continuing.
1275 if nok == 0 {
1276 // Servers may return success for a DATA without valid recipients. Write a dot to
1277 // end DATA and restore the connection to a known state.
1278 // ../rfc/2920:328
1279 if datacode == smtp.C354Continue {
1280 _, doterr := fmt.Fprintf(c.w, ".\r\n")
1281 if doterr == nil {
1282 doterr = c.w.Flush()
1283 }
1284 if doterr == nil {
1285 _, _, _, _, doterr = c.read()
1286 }
1287 if doterr != nil {
1288 c.botched = true
1289 }
1290 }
1291
1292 if len(rcptTo) == 1 {
1293 panic(Error(rcptResps[0]))
1294 }
1295 c.xerrorf(false, 0, "", "", nil, "%w", errNoRecipientsPipelined)
1296 }
1297
1298 if datacode != smtp.C354Continue {
1299 c.xerrorf(datacode/100 == 5, datacode, datasecode, datafirstLine, datamoreLines, "%w: got %d, expected 354", ErrStatus, datacode)
1300 }
1301
1302 } else {
1303 c.cmds[0] = "mailfrom"
1304 c.cmdStart = time.Now()
1305 c.xwriteline(lineMailFrom)
1306 code, secode, firstLine, moreLines := c.xread()
1307 if code != smtp.C250Completed {
1308 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "%w: got %d, expected 2xx", ErrStatus, code)
1309 }
1310
1311 rcptResps = make([]Response, len(rcptTo))
1312 nok := 0
1313 for i, rcpt := range rcptTo {
1314 c.cmds[0] = "rcptto"
1315 c.cmdStart = time.Now()
1316 c.xwriteline(fmt.Sprintf("RCPT TO:<%s>", rcpt))
1317 code, secode, firstLine, moreLines = c.xread()
1318 if i > 0 && (code == smtp.C452StorageFull || code == smtp.C552MailboxFull) {
1319 // Remote doesn't accept more recipients for this transaction. Don't send more, give
1320 // remaining recipients the same error result.
1321 for j := i; j < len(rcptTo); j++ {
1322 rcptResps[j] = Response{false, code, secode, "rcptto", firstLine, moreLines, fmt.Errorf("no more recipients accepted in transaction")}
1323 }
1324 break
1325 }
1326 var err error
1327 if code == smtp.C250Completed {
1328 nok++
1329 } else {
1330 err = fmt.Errorf("%w: got %d, expected 2xx", ErrStatus, code)
1331 }
1332 rcptResps[i] = Response{code/100 == 5, code, secode, "rcptto", firstLine, moreLines, err}
1333 }
1334
1335 if nok == 0 {
1336 if len(rcptTo) == 1 {
1337 panic(Error(rcptResps[0]))
1338 }
1339 c.xerrorf(false, 0, "", "", nil, "%w", errNoRecipients)
1340 }
1341
1342 c.cmds[0] = "data"
1343 c.cmdStart = time.Now()
1344 c.xwriteline("DATA")
1345 code, secode, firstLine, moreLines = c.xread()
1346 if code != smtp.C354Continue {
1347 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "%w: got %d, expected 354", ErrStatus, code)
1348 }
1349 }
1350
1351 // For a DATA write, the suggested timeout is 3 minutes, we use 30 seconds for all
1352 // writes through timeoutWriter. ../rfc/5321:3651
1353 defer c.xtrace(mlog.LevelTracedata)()
1354 err := smtp.DataWrite(c.w, msg)
1355 if err != nil {
1356 c.xbotchf(0, "", "", nil, "writing message as smtp data: %w", err)
1357 }
1358 c.xflush()
1359 c.xtrace(mlog.LevelTrace) // Restore.
1360 code, secode, firstLine, moreLines := c.xread()
1361 if code != smtp.C250Completed {
1362 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "%w: got %d, expected 2xx", ErrStatus, code)
1363 }
1364
1365 c.needRset = false
1366 return
1367}
1368
1369// Reset sends an SMTP RSET command to reset the message transaction state. Deliver
1370// automatically sends it if needed.
1371func (c *Client) Reset() (rerr error) {
1372 if c.origConn == nil {
1373 return ErrClosed
1374 } else if c.botched {
1375 return ErrBotched
1376 }
1377
1378 defer c.recover(&rerr)
1379
1380 // ../rfc/5321:2079
1381 c.cmds[0] = "rset"
1382 c.cmdStart = time.Now()
1383 c.xwriteline("RSET")
1384 code, secode, firstLine, moreLines := c.xread()
1385 if code != smtp.C250Completed {
1386 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "%w: got %d, expected 2xx", ErrStatus, code)
1387 }
1388 c.needRset = false
1389 return
1390}
1391
1392// Botched returns whether this connection is botched, e.g. a protocol error
1393// occurred and the connection is in unknown state, and cannot be used for message
1394// delivery.
1395func (c *Client) Botched() bool {
1396 return c.botched || c.origConn == nil
1397}
1398
1399// Close cleans up the client, closing the underlying connection.
1400//
1401// If the connection is initialized and not botched, a QUIT command is sent and the
1402// response read with a short timeout before closing the underlying connection.
1403//
1404// Close returns any error encountered during QUIT and closing.
1405func (c *Client) Close() (rerr error) {
1406 if c.origConn == nil {
1407 return ErrClosed
1408 }
1409
1410 defer c.recover(&rerr)
1411
1412 if !c.botched {
1413 // ../rfc/5321:2205
1414 c.cmds[0] = "quit"
1415 c.cmdStart = time.Now()
1416 c.xwriteline("QUIT")
1417 if err := c.conn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
1418 c.log.Infox("setting read deadline for reading quit response", err)
1419 } else if _, err := bufs.Readline(c.log, c.r); err != nil {
1420 rerr = fmt.Errorf("reading response to quit command: %v", err)
1421 c.log.Debugx("reading quit response", err)
1422 }
1423 }
1424
1425 err := c.origConn.Close()
1426 if c.conn != c.origConn {
1427 // This is the TLS connection. Close will attempt to write a close notification.
1428 // But it will fail quickly because the underlying socket was closed.
1429 c.conn.Close()
1430 }
1431 c.origConn = nil
1432 c.conn = nil
1433 if rerr != nil {
1434 rerr = err
1435 }
1436 return
1437}
1438
1439// Conn returns the connection with initialized SMTP session. Once the caller uses
1440// this connection it is in control, and responsible for closing the connection,
1441// and other functions on the client must not be called anymore.
1442func (c *Client) Conn() (net.Conn, error) {
1443 if err := c.conn.SetDeadline(time.Time{}); err != nil {
1444 return nil, fmt.Errorf("clearing io deadlines: %w", err)
1445 }
1446 return c.conn, nil
1447}
1448