1// Package dsn parses and composes Delivery Status Notification messages, see
2// RFC 3464 and RFC 6533.
19 "github.com/mjl-/mox/dkim"
20 "github.com/mjl-/mox/dns"
21 "github.com/mjl-/mox/message"
22 "github.com/mjl-/mox/mlog"
23 "github.com/mjl-/mox/mox-"
24 "github.com/mjl-/mox/smtp"
27// Message represents a DSN message, with basic message headers, human-readable text,
28// machine-parsable data, and optional original message/headers.
30// A DSN represents a delayed, failed or successful delivery. Failing incoming
31// deliveries over SMTP, and failing outgoing deliveries from the message queue,
32// can result in a DSN being sent.
34 SMTPUTF8 bool // Whether the original was received with smtputf8.
36 // DSN message From header. E.g. postmaster@ourdomain.example. NOTE:
37 // DSNs should be sent with a null reverse path to prevent mail loops.
41 // "To" header, and also SMTP RCP TO to deliver DSN to. Should be taken
42 // from original SMTP transaction MAIL FROM.
46 // Message subject header, e.g. describing mail delivery failure.
49 // Set when message is composed.
52 // References header, with Message-ID of original message this DSN is about. So
53 // mail user-agents will thread the DSN with the original message.
56 // Human-readable text explaining the failure. Line endings should be
57 // bare newlines, not \r\n. They are converted to \r\n when composing.
60 // Per-message fields.
61 OriginalEnvelopeID string
62 ReportingMTA string // Required.
64 ReceivedFromMTA smtp.Ehlo // Host from which message was received.
67 // All per-message fields, including extensions. Only used for parsing,
69 MessageHeader textproto.MIMEHeader
71 // One or more per-recipient fields.
73 Recipients []Recipient
75 // Original message or headers to include in DSN as third MIME part.
76 // Optional. Only used for generating DSNs, not set for parsed DNSs.
80// Action is a field in a DSN.
86 Failed Action = "failed"
87 Delayed Action = "delayed"
88 Delivered Action = "delivered"
89 Relayed Action = "relayed"
90 Expanded Action = "expanded"
95// Recipient holds the per-recipient delivery-status lines in a DSN.
96type Recipient struct {
98 FinalRecipient smtp.Path // Final recipient of message.
101 // Enhanced status code. First digit indicates permanent or temporary
102 // error. If the string contains more than just a status, that
103 // additional text is added as comment when composing a DSN.
107 // Original intended recipient of message. Used with the DSN extensions ORCPT
110 OriginalRecipient smtp.Path
112 // Remote host that returned an error code. Can also be empty for
116 // If RemoteMTA is present, DiagnosticCode is from remote. When
117 // creating a DSN, additional text in the string will be added to the
119 DiagnosticCode string
120 LastAttemptDate time.Time
123 // For delayed deliveries, deliveries may be retried until this time.
124 WillRetryUntil *time.Time
126 // All fields, including extensions. Only used for parsing, not
128 Header textproto.MIMEHeader
131// Compose returns a DSN message.
133// smtputf8 indicates whether the remote MTA that is receiving the DSN
134// supports smtputf8. This influences the message media (sub)types used for the
137// DKIM signatures are added if DKIM signing is configured for the "from" domain.
138func (m *Message) Compose(log *mlog.Log, smtputf8 bool) ([]byte, error) {
141 // We'll make a multipart/report with 2 or 3 parts:
142 // - 1. human-readable explanation;
143 // - 2. message/delivery-status;
144 // - 3. (optional) original message (either in full, or only headers).
146 // todo future: add option to send full message. but only do so if the message is <100kb.
147 // todo future: possibly write to a file directly, instead of building up message in memory.
149 // If message does not require smtputf8, we are never generating a utf-8 DSN.
154 // We check for errors once after all the writes.
155 msgw := &errWriter{w: &bytes.Buffer{}}
157 header := func(k, v string) {
158 fmt.Fprintf(msgw, "%s: %s\r\n", k, v)
161 line := func(w io.Writer) {
162 _, _ = w.Write([]byte("\r\n"))
165 // Outer message headers.
166 header("From", fmt.Sprintf("<%s>", m.From.XString(smtputf8))) // todo: would be good to have a local ascii-only name for this address.
167 header("To", fmt.Sprintf("<%s>", m.To.XString(smtputf8))) // todo: we could just leave this out if it has utf-8 and remote does not support utf-8.
168 header("Subject", m.Subject)
169 m.MessageID = mox.MessageIDGen(smtputf8)
170 header("Message-Id", fmt.Sprintf("<%s>", m.MessageID))
171 if m.References != "" {
172 header("References", m.References)
174 header("Date", time.Now().Format(message.RFC5322Z))
175 header("MIME-Version", "1.0")
176 mp := multipart.NewWriter(msgw)
177 header("Content-Type", fmt.Sprintf(`multipart/report; report-type="delivery-status"; boundary="%s"`, mp.Boundary()))
181 // First part, human-readable message.
182 msgHdr := textproto.MIMEHeader{}
184 msgHdr.Set("Content-Type", "text/plain; charset=utf-8")
185 msgHdr.Set("Content-Transfer-Encoding", "8BIT")
187 msgHdr.Set("Content-Type", "text/plain")
188 msgHdr.Set("Content-Transfer-Encoding", "7BIT")
190 msgp, err := mp.CreatePart(msgHdr)
194 if _, err := msgp.Write([]byte(strings.ReplaceAll(m.TextBody, "\n", "\r\n"))); err != nil {
199 statusHdr := textproto.MIMEHeader{}
202 statusHdr.Set("Content-Type", "message/global-delivery-status")
203 statusHdr.Set("Content-Transfer-Encoding", "8BIT")
205 statusHdr.Set("Content-Type", "message/delivery-status")
206 statusHdr.Set("Content-Transfer-Encoding", "7BIT")
208 statusp, err := mp.CreatePart(statusHdr)
215 // type fields:
../rfc/3464:536 https://www.iana.org/assignments/dsn-types/dsn-types.xhtml
217 status := func(k, v string) {
218 fmt.Fprintf(statusp, "%s: %s\r\n", k, v)
223 if m.OriginalEnvelopeID != "" {
224 status("Original-Envelope-ID", m.OriginalEnvelopeID)
227 if m.DSNGateway != "" {
229 status("DSN-Gateway", "dns; "+m.DSNGateway)
231 if !m.ReceivedFromMTA.IsZero() {
233 status("Received-From-MTA", fmt.Sprintf("dns;%s (%s)", m.ReceivedFromMTA.Name, smtp.AddressLiteral(m.ReceivedFromMTA.ConnIP)))
238 // todo: should also handle other address types. at least recognize "unknown". Probably just store this field.
../rfc/3464:819
243 if len(m.Recipients) == 0 {
244 return nil, fmt.Errorf("missing per-recipient fields")
246 for _, r := range m.Recipients {
248 if !r.OriginalRecipient.IsZero() {
250 status("Original-Recipient", addrType+r.OriginalRecipient.DSNString(smtputf8))
252 status("Final-Recipient", addrType+r.FinalRecipient.DSNString(smtputf8)) //
../rfc/3464:829
257 // Making up a status code is not great, but the field is required. We could simply
258 // require the caller to make one up...
269 st, rest = codeLine(st)
272 statusLine += " (" + rest + ")"
275 if !r.RemoteMTA.IsZero() {
277 s := "dns;" + r.RemoteMTA.Name
278 if len(r.RemoteMTA.IP) > 0 {
279 s += " (" + smtp.AddressLiteral(r.RemoteMTA.IP) + ")"
281 status("Remote-MTA", s)
284 if r.DiagnosticCode != "" {
285 diagCode, rest := codeLine(r.DiagnosticCode)
288 diagLine += " (" + rest + ")"
291 status("Diagnostic-Code", "smtp; "+diagLine)
293 if !r.LastAttemptDate.IsZero() {
294 status("Last-Attempt-Date", r.LastAttemptDate.Format(message.RFC5322Z)) //
../rfc/3464:1076
296 if r.FinalLogID != "" {
297 // todo future: think about adding cid as "Final-Log-Id"?
300 if r.WillRetryUntil != nil {
305 // We include only the header of the original message.
306 // todo: add the textual version of the original message, if it exists and isn't too large.
307 if m.Original != nil {
308 headers, err := message.ReadHeaders(bufio.NewReader(bytes.NewReader(m.Original)))
309 if err != nil && errors.Is(err, message.ErrHeaderSeparator) {
310 // Whole data is a header.
312 } else if err != nil {
315 // Else, this is a whole message. We still only include the headers. todo: include the whole body.
317 origHdr := textproto.MIMEHeader{}
322 origHdr.Set("Content-Transfer-Encoding", "8BIT")
327 origHdr.Set("Content-Type", "text/rfc822-headers; charset=utf-8")
328 origHdr.Set("Content-Transfer-Encoding", "BASE64")
330 origHdr.Set("Content-Type", "text/rfc822-headers")
331 origHdr.Set("Content-Transfer-Encoding", "7BIT")
334 origp, err := mp.CreatePart(origHdr)
339 if !smtputf8 && m.SMTPUTF8 {
340 data := base64.StdEncoding.EncodeToString(headers)
347 line, data = data[:n], data[n:]
348 if _, err := origp.Write([]byte(line + "\r\n")); err != nil {
353 if _, err := origp.Write(headers); err != nil {
359 if err := mp.Close(); err != nil {
367 data := msgw.w.Bytes()
369 // Add DKIM signature for domain, even if higher up than the full mail hostname.
370 // This helps with an assumed (because default) relaxed DKIM policy. If the DMARC
371 // policy happens to be strict, the signature won't help, but won't hurt either.
372 fd := m.From.IPDomain.Domain
373 var zerodom dns.Domain
375 confDom, ok := mox.Conf.Domain(fd)
378 _, nfd.ASCII, _ = strings.Cut(fd.ASCII, ".")
379 _, nfd.Unicode, _ = strings.Cut(fd.Unicode, ".")
384 dkimHeaders, err := dkim.Sign(context.Background(), m.From.Localpart, fd, confDom.DKIM, smtputf8, bytes.NewReader(data))
386 log.Errorx("dsn: dkim sign for domain, returning unsigned dsn", err, mlog.Field("domain", fd))
388 data = append([]byte(dkimHeaders), data...)
396type errWriter struct {
401func (w *errWriter) Write(buf []byte) (int, error) {
405 n, err := w.w.Write(buf)
410// split a line into enhanced status code and rest.
411func codeLine(s string) (string, string) {
412 t := strings.SplitN(s, " ", 2)
413 l := strings.Split(t[0], ".")
417 for i, e := range l {
418 _, err := strconv.ParseInt(e, 10, 32)
422 if i == 0 && len(e) != 1 {
434// HasCode returns whether line starts with an enhanced SMTP status code.
435func HasCode(line string) bool {
437 ecode, _ := codeLine(line)