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/message"
21 "github.com/mjl-/mox/mlog"
22 "github.com/mjl-/mox/mox-"
23 "github.com/mjl-/mox/smtp"
26// Message represents a DSN message, with basic message headers, human-readable text,
27// machine-parsable data, and optional original message/headers.
29// A DSN represents a delayed, failed or successful delivery. Failing incoming
30// deliveries over SMTP, and failing outgoing deliveries from the message queue,
31// can result in a DSN being sent.
33 SMTPUTF8 bool // Whether the original was received with smtputf8.
35 // DSN message From header. E.g. postmaster@ourdomain.example. NOTE:
36 // DSNs should be sent with a null reverse path to prevent mail loops.
40 // "To" header, and also SMTP RCP TO to deliver DSN to. Should be taken
41 // from original SMTP transaction MAIL FROM.
45 // Message subject header, e.g. describing mail delivery failure.
48 // Set when message is composed.
51 // References header, with Message-ID of original message this DSN is about. So
52 // mail user-agents will thread the DSN with the original message.
55 // Human-readable text explaining the failure. Line endings should be
56 // bare newlines, not \r\n. They are converted to \r\n when composing.
59 // Per-message fields.
60 OriginalEnvelopeID string
61 ReportingMTA string // Required.
63 ReceivedFromMTA smtp.Ehlo // Host from which message was received.
66 // All per-message fields, including extensions. Only used for parsing,
68 MessageHeader textproto.MIMEHeader
70 // One or more per-recipient fields.
72 Recipients []Recipient
74 // Original message or headers to include in DSN as third MIME part.
75 // Optional. Only used for generating DSNs, not set for parsed DNSs.
79// Action is a field in a DSN.
85 Failed Action = "failed"
86 Delayed Action = "delayed"
87 Delivered Action = "delivered"
88 Relayed Action = "relayed"
89 Expanded Action = "expanded"
94// Recipient holds the per-recipient delivery-status lines in a DSN.
95type Recipient struct {
97 FinalRecipient smtp.Path // Final recipient of message.
100 // Enhanced status code. First digit indicates permanent or temporary
101 // error. If the string contains more than just a status, that
102 // additional text is added as comment when composing a DSN.
106 // Original intended recipient of message. Used with the DSN extensions ORCPT
109 OriginalRecipient smtp.Path
111 // Remote host that returned an error code. Can also be empty for
115 // If RemoteMTA is present, DiagnosticCode is from remote. When
116 // creating a DSN, additional text in the string will be added to the
118 DiagnosticCode string
119 LastAttemptDate time.Time
122 // For delayed deliveries, deliveries may be retried until this time.
123 WillRetryUntil *time.Time
125 // All fields, including extensions. Only used for parsing, not
127 Header textproto.MIMEHeader
130// Compose returns a DSN message.
132// smtputf8 indicates whether the remote MTA that is receiving the DSN
133// supports smtputf8. This influences the message media (sub)types used for the
136// DKIM signatures are added if DKIM signing is configured for the "from" domain.
137func (m *Message) Compose(log *mlog.Log, smtputf8 bool) ([]byte, error) {
140 // We'll make a multipart/report with 2 or 3 parts:
141 // - 1. human-readable explanation;
142 // - 2. message/delivery-status;
143 // - 3. (optional) original message (either in full, or only headers).
145 // todo future: add option to send full message. but only do so if the message is <100kb.
146 // todo future: possibly write to a file directly, instead of building up message in memory.
148 // If message does not require smtputf8, we are never generating a utf-8 DSN.
153 // We check for errors once after all the writes.
154 msgw := &errWriter{w: &bytes.Buffer{}}
156 header := func(k, v string) {
157 fmt.Fprintf(msgw, "%s: %s\r\n", k, v)
160 line := func(w io.Writer) {
161 _, _ = w.Write([]byte("\r\n"))
164 // Outer message headers.
165 header("From", fmt.Sprintf("<%s>", m.From.XString(smtputf8))) // todo: would be good to have a local ascii-only name for this address.
166 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.
167 header("Subject", m.Subject)
168 m.MessageID = mox.MessageIDGen(smtputf8)
169 header("Message-Id", fmt.Sprintf("<%s>", m.MessageID))
170 if m.References != "" {
171 header("References", m.References)
173 header("Date", time.Now().Format(message.RFC5322Z))
174 header("MIME-Version", "1.0")
175 mp := multipart.NewWriter(msgw)
176 header("Content-Type", fmt.Sprintf(`multipart/report; report-type="delivery-status"; boundary="%s"`, mp.Boundary()))
180 // First part, human-readable message.
181 msgHdr := textproto.MIMEHeader{}
183 msgHdr.Set("Content-Type", "text/plain; charset=utf-8")
184 msgHdr.Set("Content-Transfer-Encoding", "8BIT")
186 msgHdr.Set("Content-Type", "text/plain")
187 msgHdr.Set("Content-Transfer-Encoding", "7BIT")
189 msgp, err := mp.CreatePart(msgHdr)
193 if _, err := msgp.Write([]byte(strings.ReplaceAll(m.TextBody, "\n", "\r\n"))); err != nil {
198 statusHdr := textproto.MIMEHeader{}
201 statusHdr.Set("Content-Type", "message/global-delivery-status")
202 statusHdr.Set("Content-Transfer-Encoding", "8BIT")
204 statusHdr.Set("Content-Type", "message/delivery-status")
205 statusHdr.Set("Content-Transfer-Encoding", "7BIT")
207 statusp, err := mp.CreatePart(statusHdr)
214 // type fields:
../rfc/3464:536 https://www.iana.org/assignments/dsn-types/dsn-types.xhtml
216 status := func(k, v string) {
217 fmt.Fprintf(statusp, "%s: %s\r\n", k, v)
222 if m.OriginalEnvelopeID != "" {
223 status("Original-Envelope-ID", m.OriginalEnvelopeID)
226 if m.DSNGateway != "" {
228 status("DSN-Gateway", "dns; "+m.DSNGateway)
230 if !m.ReceivedFromMTA.IsZero() {
232 status("Received-From-MTA", fmt.Sprintf("dns;%s (%s)", m.ReceivedFromMTA.Name, smtp.AddressLiteral(m.ReceivedFromMTA.ConnIP)))
237 // todo: should also handle other address types. at least recognize "unknown". Probably just store this field.
../rfc/3464:819
242 if len(m.Recipients) == 0 {
243 return nil, fmt.Errorf("missing per-recipient fields")
245 for _, r := range m.Recipients {
247 if !r.OriginalRecipient.IsZero() {
249 status("Original-Recipient", addrType+r.OriginalRecipient.DSNString(smtputf8))
251 status("Final-Recipient", addrType+r.FinalRecipient.DSNString(smtputf8)) //
../rfc/3464:829
256 // Making up a status code is not great, but the field is required. We could simply
257 // require the caller to make one up...
268 st, rest = codeLine(st)
271 statusLine += " (" + rest + ")"
274 if !r.RemoteMTA.IsZero() {
276 s := "dns;" + r.RemoteMTA.Name
277 if len(r.RemoteMTA.IP) > 0 {
278 s += " (" + smtp.AddressLiteral(r.RemoteMTA.IP) + ")"
280 status("Remote-MTA", s)
283 if r.DiagnosticCode != "" {
284 diagCode, rest := codeLine(r.DiagnosticCode)
287 diagLine += " (" + rest + ")"
290 status("Diagnostic-Code", "smtp; "+diagLine)
292 if !r.LastAttemptDate.IsZero() {
293 status("Last-Attempt-Date", r.LastAttemptDate.Format(message.RFC5322Z)) //
../rfc/3464:1076
295 if r.FinalLogID != "" {
296 // todo future: think about adding cid as "Final-Log-Id"?
299 if r.WillRetryUntil != nil {
304 // We include only the header of the original message.
305 // todo: add the textual version of the original message, if it exists and isn't too large.
306 if m.Original != nil {
307 headers, err := message.ReadHeaders(bufio.NewReader(bytes.NewReader(m.Original)))
308 if err != nil && errors.Is(err, message.ErrHeaderSeparator) {
309 // Whole data is a header.
311 } else if err != nil {
314 // Else, this is a whole message. We still only include the headers. todo: include the whole body.
316 origHdr := textproto.MIMEHeader{}
321 origHdr.Set("Content-Transfer-Encoding", "8BIT")
326 origHdr.Set("Content-Type", "text/rfc822-headers; charset=utf-8")
327 origHdr.Set("Content-Transfer-Encoding", "BASE64")
329 origHdr.Set("Content-Type", "text/rfc822-headers")
330 origHdr.Set("Content-Transfer-Encoding", "7BIT")
333 origp, err := mp.CreatePart(origHdr)
338 if !smtputf8 && m.SMTPUTF8 {
339 data := base64.StdEncoding.EncodeToString(headers)
346 line, data = data[:n], data[n:]
347 if _, err := origp.Write([]byte(line + "\r\n")); err != nil {
352 if _, err := origp.Write(headers); err != nil {
358 if err := mp.Close(); err != nil {
366 data := msgw.w.Bytes()
368 fd := m.From.IPDomain.Domain
369 confDom, _ := mox.Conf.Domain(fd)
370 if len(confDom.DKIM.Sign) > 0 {
371 if dkimHeaders, err := dkim.Sign(context.Background(), m.From.Localpart, fd, confDom.DKIM, smtputf8, bytes.NewReader(data)); err != nil {
372 log.Errorx("dsn: dkim sign for domain, returning unsigned dsn", err, mlog.Field("domain", fd))
374 data = append([]byte(dkimHeaders), data...)
381type errWriter struct {
386func (w *errWriter) Write(buf []byte) (int, error) {
390 n, err := w.w.Write(buf)
395// split a line into enhanced status code and rest.
396func codeLine(s string) (string, string) {
397 t := strings.SplitN(s, " ", 2)
398 l := strings.Split(t[0], ".")
402 for i, e := range l {
403 _, err := strconv.ParseInt(e, 10, 32)
407 if i == 0 && len(e) != 1 {
419// HasCode returns whether line starts with an enhanced SMTP status code.
420func HasCode(line string) bool {
422 ecode, _ := codeLine(line)