1// Package dsn parses and composes Delivery Status Notification messages, see
2// RFC 3464 and RFC 6533.
3package dsn
4
5import (
6 "bufio"
7 "bytes"
8 "encoding/base64"
9 "errors"
10 "fmt"
11 "io"
12 "mime/multipart"
13 "net/textproto"
14 "strings"
15 "time"
16
17 "github.com/mjl-/mox/message"
18 "github.com/mjl-/mox/mlog"
19 "github.com/mjl-/mox/smtp"
20)
21
22// Message represents a DSN message, with basic message headers, human-readable text,
23// machine-parsable data, and optional original message/headers.
24//
25// A DSN represents a delayed, failed or successful delivery. Failing incoming
26// deliveries over SMTP, and failing outgoing deliveries from the message queue,
27// can result in a DSN being sent.
28type Message struct {
29 SMTPUTF8 bool // Whether the original was received with smtputf8.
30
31 // DSN message From header. E.g. postmaster@ourdomain.example. NOTE:
32 // DSNs should be sent with a null reverse path to prevent mail loops.
33 // ../rfc/3464:421
34 From smtp.Path
35
36 // "To" header, and also SMTP RCP TO to deliver DSN to. Should be taken
37 // from original SMTP transaction MAIL FROM.
38 // ../rfc/3464:415
39 To smtp.Path
40
41 // Message subject header, e.g. describing mail delivery failure.
42 Subject string
43
44 MessageID string
45
46 // References header, with Message-ID of original message this DSN is about. So
47 // mail user-agents will thread the DSN with the original message.
48 References string
49
50 // For message submitted with FUTURERELEASE SMTP extension. Value is either "for;"
51 // plus original interval in seconds or "until;" plus original UTC RFC3339
52 // date-time.
53 FutureReleaseRequest string
54 // ../rfc/4865:315
55
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.
58 TextBody string
59
60 // Per-message fields.
61 OriginalEnvelopeID string
62 ReportingMTA string // Required.
63 DSNGateway string
64 ReceivedFromMTA smtp.Ehlo // Host from which message was received.
65 ArrivalDate time.Time
66
67 // All per-message fields, including extensions. Only used for parsing,
68 // not composing.
69 MessageHeader textproto.MIMEHeader
70
71 // One or more per-recipient fields.
72 // ../rfc/3464:436
73 Recipients []Recipient
74
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.
77 Original []byte
78}
79
80// Action is a field in a DSN.
81type Action string
82
83// ../rfc/3464:890
84
85const (
86 Failed Action = "failed"
87 Delayed Action = "delayed"
88 Delivered Action = "delivered"
89 Relayed Action = "relayed"
90 Expanded Action = "expanded"
91)
92
93// ../rfc/3464:1530 ../rfc/6533:370
94
95// Recipient holds the per-recipient delivery-status lines in a DSN.
96type Recipient struct {
97 // Required fields.
98 FinalRecipient smtp.Path // Final recipient of message.
99 Action Action
100
101 // Enhanced status code. First digit indicates permanent or temporary
102 // error.
103 Status string
104 // For additional details, included in comment.
105 StatusComment string
106
107 // Optional fields.
108 // Original intended recipient of message. Used with the DSN extensions ORCPT
109 // parameter.
110 // ../rfc/3464:1197
111 OriginalRecipient smtp.Path
112
113 // Remote host that returned an error code. Can also be empty for
114 // deliveries.
115 RemoteMTA NameIP
116
117 // DiagnosticCodeSMTP are the full SMTP response lines, space separated. The marshaled
118 // form starts with "smtp; ", this value does not.
119 DiagnosticCodeSMTP string
120
121 LastAttemptDate time.Time
122 FinalLogID string
123
124 // For delayed deliveries, deliveries may be retried until this time.
125 WillRetryUntil *time.Time
126
127 // All fields, including extensions. Only used for parsing, not
128 // composing.
129 Header textproto.MIMEHeader
130}
131
132// Compose returns a DSN message.
133//
134// smtputf8 indicates whether the remote MTA that is receiving the DSN
135// supports smtputf8. This influences the message media (sub)types used for the
136// DSN.
137//
138// Called may want to add DKIM-Signature headers.
139func (m *Message) Compose(log mlog.Log, smtputf8 bool) ([]byte, error) {
140 // ../rfc/3462:119
141 // ../rfc/3464:377
142 // We'll make a multipart/report with 2 or 3 parts:
143 // - 1. human-readable explanation;
144 // - 2. message/delivery-status;
145 // - 3. (optional) original message (either in full, or only headers).
146
147 // todo future: add option to send full message. but only do so if the message is <100kb.
148 // todo future: possibly write to a file directly, instead of building up message in memory.
149
150 // If message does not require smtputf8, we are never generating a utf-8 DSN.
151 if !m.SMTPUTF8 {
152 smtputf8 = false
153 }
154
155 // We check for errors once after all the writes.
156 msgw := &errWriter{w: &bytes.Buffer{}}
157
158 header := func(k, v string) {
159 fmt.Fprintf(msgw, "%s: %s\r\n", k, v)
160 }
161
162 line := func(w io.Writer) {
163 _, _ = w.Write([]byte("\r\n"))
164 }
165
166 // Outer message headers.
167 header("From", fmt.Sprintf("<%s>", m.From.XString(smtputf8))) // todo: would be good to have a local ascii-only name for this address.
168 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.
169 header("Subject", m.Subject)
170 if m.MessageID == "" {
171 return nil, fmt.Errorf("missing message-id")
172 }
173 header("Message-Id", fmt.Sprintf("<%s>", m.MessageID))
174 if m.References != "" {
175 header("References", m.References)
176 }
177 header("Date", time.Now().Format(message.RFC5322Z))
178 header("MIME-Version", "1.0")
179 mp := multipart.NewWriter(msgw)
180 header("Content-Type", fmt.Sprintf(`multipart/report; report-type="delivery-status"; boundary="%s"`, mp.Boundary()))
181
182 line(msgw)
183
184 // First part, human-readable message.
185 msgHdr := textproto.MIMEHeader{}
186 if smtputf8 {
187 msgHdr.Set("Content-Type", "text/plain; charset=utf-8")
188 msgHdr.Set("Content-Transfer-Encoding", "8BIT")
189 } else {
190 msgHdr.Set("Content-Type", "text/plain")
191 msgHdr.Set("Content-Transfer-Encoding", "7BIT")
192 }
193 msgp, err := mp.CreatePart(msgHdr)
194 if err != nil {
195 return nil, err
196 }
197 if _, err := msgp.Write([]byte(strings.ReplaceAll(m.TextBody, "\n", "\r\n"))); err != nil {
198 return nil, err
199 }
200
201 // Machine-parsable message. ../rfc/3464:455
202 statusHdr := textproto.MIMEHeader{}
203 if smtputf8 {
204 // ../rfc/6533:325
205 statusHdr.Set("Content-Type", "message/global-delivery-status")
206 statusHdr.Set("Content-Transfer-Encoding", "8BIT")
207 } else {
208 statusHdr.Set("Content-Type", "message/delivery-status")
209 statusHdr.Set("Content-Transfer-Encoding", "7BIT")
210 }
211 statusp, err := mp.CreatePart(statusHdr)
212 if err != nil {
213 return nil, err
214 }
215
216 // ../rfc/3464:470
217 // examples: ../rfc/3464:1855
218 // type fields: ../rfc/3464:536 https://www.iana.org/assignments/dsn-types/dsn-types.xhtml
219
220 status := func(k, v string) {
221 fmt.Fprintf(statusp, "%s: %s\r\n", k, v)
222 }
223
224 // Per-message fields first. ../rfc/3464:575
225 // todo future: once we support the smtp dsn extension, the envid should be saved/set as OriginalEnvelopeID. ../rfc/3464:583 ../rfc/3461:1139
226 if m.OriginalEnvelopeID != "" {
227 status("Original-Envelope-ID", m.OriginalEnvelopeID)
228 }
229 status("Reporting-MTA", "dns; "+m.ReportingMTA) // ../rfc/3464:628
230 if m.DSNGateway != "" {
231 // ../rfc/3464:714
232 status("DSN-Gateway", "dns; "+m.DSNGateway)
233 }
234 if !m.ReceivedFromMTA.IsZero() {
235 // ../rfc/3464:735
236 status("Received-From-MTA", fmt.Sprintf("dns;%s (%s)", m.ReceivedFromMTA.Name, smtp.AddressLiteral(m.ReceivedFromMTA.ConnIP)))
237 }
238 status("Arrival-Date", m.ArrivalDate.Format(message.RFC5322Z)) // ../rfc/3464:758
239 if m.FutureReleaseRequest != "" {
240 // ../rfc/4865:320
241 status("Future-Release-Request", m.FutureReleaseRequest)
242 }
243
244 // Then per-recipient fields. ../rfc/3464:769
245 // todo: should also handle other address types. at least recognize "unknown". Probably just store this field. ../rfc/3464:819
246 addrType := "rfc822;" // ../rfc/3464:514
247 if smtputf8 {
248 addrType = "utf-8;" // ../rfc/6533:250
249 }
250 if len(m.Recipients) == 0 {
251 return nil, fmt.Errorf("missing per-recipient fields")
252 }
253 for _, r := range m.Recipients {
254 line(statusp)
255 if !r.OriginalRecipient.IsZero() {
256 // ../rfc/3464:807
257 status("Original-Recipient", addrType+r.OriginalRecipient.DSNString(smtputf8))
258 }
259 status("Final-Recipient", addrType+r.FinalRecipient.DSNString(smtputf8)) // ../rfc/3464:829
260 status("Action", string(r.Action)) // ../rfc/3464:879
261 st := r.Status
262 if st == "" {
263 // ../rfc/3464:944
264 // Making up a status code is not great, but the field is required. We could simply
265 // require the caller to make one up...
266 switch r.Action {
267 case Delayed:
268 st = "4.0.0"
269 case Failed:
270 st = "5.0.0"
271 default:
272 st = "2.0.0"
273 }
274 }
275 statusLine := st
276 if r.StatusComment != "" {
277 statusLine += " (" + r.StatusComment + ")"
278 }
279 status("Status", statusLine) // ../rfc/3464:975
280 if !r.RemoteMTA.IsZero() {
281 // ../rfc/3464:1015
282 s := "dns;" + r.RemoteMTA.Name
283 if len(r.RemoteMTA.IP) > 0 {
284 s += " (" + smtp.AddressLiteral(r.RemoteMTA.IP) + ")"
285 }
286 status("Remote-MTA", s)
287 }
288 // Presence of Diagnostic-Code indicates the code is from Remote-MTA. ../rfc/3464:1053
289 if r.DiagnosticCodeSMTP != "" {
290 // ../rfc/3461:1342 ../rfc/6533:589
291 status("Diagnostic-Code", "smtp; "+r.DiagnosticCodeSMTP)
292 }
293 if !r.LastAttemptDate.IsZero() {
294 status("Last-Attempt-Date", r.LastAttemptDate.Format(message.RFC5322Z)) // ../rfc/3464:1076
295 }
296 if r.FinalLogID != "" {
297 // todo future: think about adding cid as "Final-Log-Id"?
298 status("Final-Log-ID", r.FinalLogID) // ../rfc/3464:1098
299 }
300 if r.WillRetryUntil != nil {
301 status("Will-Retry-Until", r.WillRetryUntil.Format(message.RFC5322Z)) // ../rfc/3464:1108
302 }
303 }
304
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.
311 headers = m.Original
312 } else if err != nil {
313 return nil, err
314 }
315 // Else, this is a whole message. We still only include the headers. todo: include the whole body.
316
317 origHdr := textproto.MIMEHeader{}
318 if smtputf8 {
319 // ../rfc/6533:431
320 // ../rfc/6533:605
321 origHdr.Set("Content-Type", "message/global-headers") // ../rfc/6533:625
322 origHdr.Set("Content-Transfer-Encoding", "8BIT")
323 } else {
324 // ../rfc/3462:175
325 if m.SMTPUTF8 {
326 // ../rfc/6533:480
327 origHdr.Set("Content-Type", "text/rfc822-headers; charset=utf-8")
328 origHdr.Set("Content-Transfer-Encoding", "BASE64")
329 } else {
330 origHdr.Set("Content-Type", "text/rfc822-headers")
331 origHdr.Set("Content-Transfer-Encoding", "7BIT")
332 }
333 }
334 origp, err := mp.CreatePart(origHdr)
335 if err != nil {
336 return nil, err
337 }
338
339 if !smtputf8 && m.SMTPUTF8 {
340 data := base64.StdEncoding.EncodeToString(headers)
341 for len(data) > 0 {
342 line := data
343 n := len(line)
344 if n > 78 {
345 n = 78
346 }
347 line, data = data[:n], data[n:]
348 if _, err := origp.Write([]byte(line + "\r\n")); err != nil {
349 return nil, err
350 }
351 }
352 } else {
353 if _, err := origp.Write(headers); err != nil {
354 return nil, err
355 }
356 }
357 }
358
359 if err := mp.Close(); err != nil {
360 return nil, err
361 }
362
363 if msgw.err != nil {
364 return nil, err
365 }
366
367 data := msgw.w.Bytes()
368 return data, nil
369}
370
371type errWriter struct {
372 w *bytes.Buffer
373 err error
374}
375
376func (w *errWriter) Write(buf []byte) (int, error) {
377 if w.err != nil {
378 return -1, w.err
379 }
380 n, err := w.w.Write(buf)
381 w.err = err
382 return n, err
383}
384