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