13 "github.com/mjl-/mox/dns"
14 "github.com/mjl-/mox/message"
15 "github.com/mjl-/mox/mlog"
16 "github.com/mjl-/mox/smtp"
19// Parse reads a DSN message.
21// A DSN is a multipart internet mail message with 2 or 3 parts: human-readable
22// text, machine-parsable text, and optional original message or headers.
24// The first return value is the machine-parsed DSN message. The second value is
25// the entire MIME multipart message. Use its Parts field to access the
26// human-readable text and optional original message/headers.
27func Parse(elog *slog.Logger, r io.ReaderAt) (*Message, *message.Part, error) {
28 log := mlog.New("dsn", elog)
32 part, err := message.Parse(log.Logger, false, r)
34 return nil, nil, fmt.Errorf("parsing message: %v", err)
36 if part.MediaType != "MULTIPART" || part.MediaSubType != "REPORT" {
37 return nil, nil, fmt.Errorf(`message has content-type %q, must have "message/report"`, strings.ToLower(part.MediaType+"/"+part.MediaSubType))
39 err = part.Walk(log.Logger, nil)
41 return nil, nil, fmt.Errorf("parsing message parts: %v", err)
43 nparts := len(part.Parts)
44 if nparts != 2 && nparts != 3 {
45 return nil, nil, fmt.Errorf("invalid dsn, got %d multipart parts, 2 or 3 required", nparts)
48 if !(p0.MediaType == "" && p0.MediaSubType == "") && !(p0.MediaType == "TEXT" && p0.MediaSubType == "PLAIN") {
49 return nil, nil, fmt.Errorf(`invalid dsn, first part has content-type %q, must have "text/plain"`, strings.ToLower(p0.MediaType+"/"+p0.MediaSubType))
54 if !(p1.MediaType == "MESSAGE" && (p1.MediaSubType == "DELIVERY-STATUS" || p1.MediaSubType == "GLOBAL-DELIVERY-STATUS")) {
55 return nil, nil, fmt.Errorf(`invalid dsn, second part has content-type %q, must have "message/delivery-status" or "message/global-delivery-status"`, strings.ToLower(p1.MediaType+"/"+p1.MediaSubType))
57 utf8 := p1.MediaSubType == "GLOBAL-DELIVERY-STATUS"
58 m, err = Decode(p1.Reader(), utf8)
60 return nil, nil, fmt.Errorf("parsing dsn delivery-status part: %v", err)
63 addressPath := func(a message.Address) (smtp.Path, error) {
64 d, err := dns.ParseDomain(a.Host)
66 return smtp.Path{}, fmt.Errorf("parsing domain: %v", err)
68 lp, err := smtp.ParseLocalpart(a.User)
70 return smtp.Path{}, fmt.Errorf("parsing localpart: %v", err)
72 return smtp.Path{Localpart: lp, IPDomain: dns.IPDomain{Domain: d}}, nil
74 if len(part.Envelope.From) == 1 {
75 m.From, err = addressPath(part.Envelope.From[0])
77 return nil, nil, fmt.Errorf("parsing From-header: %v", err)
80 if len(part.Envelope.To) == 1 {
81 m.To, err = addressPath(part.Envelope.To[0])
83 return nil, nil, fmt.Errorf("parsing To-header: %v", err)
86 m.Subject = part.Envelope.Subject
87 buf, err := io.ReadAll(p0.ReaderUTF8OrBinary())
89 return nil, nil, fmt.Errorf("reading human-readable text part: %v", err)
91 m.TextBody = strings.ReplaceAll(string(buf), "\r\n", "\n")
98 ct := strings.ToLower(p2.MediaType + "/" + p2.MediaSubType)
100 case "text/rfc822-headers":
101 case "message/global-headers":
102 case "message/rfc822":
103 case "message/global":
105 return nil, nil, fmt.Errorf("invalid content-type %q for optional third part with original message/headers", ct)
111// Decode parses the (global) delivery-status part of a DSN.
113// utf8 indicates if UTF-8 is allowed for this message, if used by the media
114// subtype of the message parts.
115func Decode(r io.Reader, utf8 bool) (*Message, error) {
116 m := Message{SMTPUTF8: utf8}
118 // We are using textproto.Reader to read mime headers. It requires a header section ending in \r\n.
120 b := bufio.NewReader(io.MultiReader(r, strings.NewReader("\r\n")))
121 mr := textproto.NewReader(b)
123 // Read per-message lines.
125 msgh, err := mr.ReadMIMEHeader()
127 return nil, fmt.Errorf("reading per-message lines: %v", err)
129 for k, l := range msgh {
131 return nil, fmt.Errorf("multiple values for %q: %v", k, l)
134 // note: headers are in canonical form, as parsed by textproto.
136 case "Original-Envelope-Id":
137 m.OriginalEnvelopeID = v
138 case "Reporting-Mta":
139 mta, err := parseMTA(v, utf8)
141 return nil, fmt.Errorf("parsing reporting-mta: %v", err)
145 mta, err := parseMTA(v, utf8)
147 return nil, fmt.Errorf("parsing dsn-gateway: %v", err)
150 case "Received-From-Mta":
151 mta, err := parseMTA(v, utf8)
153 return nil, fmt.Errorf("parsing received-from-mta: %v", err)
155 d, err := dns.ParseDomain(mta)
157 return nil, fmt.Errorf("parsing received-from-mta domain %q: %v", mta, err)
159 m.ReceivedFromMTA = smtp.Ehlo{Name: dns.IPDomain{Domain: d}}
161 tm, err := parseDateTime(v)
163 return nil, fmt.Errorf("parsing arrival-date: %v", err)
167 // We'll assume it is an extension field, we'll ignore it for now.
170 m.MessageHeader = msgh
172 required := []string{"Reporting-Mta"}
173 for _, req := range required {
174 if _, ok := msgh[req]; !ok {
175 return nil, fmt.Errorf("missing required recipient field %q", req)
179 rh, err := parseRecipientHeader(mr, utf8)
181 return nil, fmt.Errorf("reading per-recipient header: %v", err)
183 m.Recipients = []Recipient{rh}
185 if _, err := b.Peek(1); err == io.EOF {
188 rh, err := parseRecipientHeader(mr, utf8)
190 return nil, fmt.Errorf("reading another per-recipient header: %v", err)
192 m.Recipients = append(m.Recipients, rh)
198func parseRecipientHeader(mr *textproto.Reader, utf8 bool) (Recipient, error) {
200 h, err := mr.ReadMIMEHeader()
202 return Recipient{}, err
205 for k, l := range h {
207 return Recipient{}, fmt.Errorf("multiple values for %q: %v", k, l)
210 // note: headers are in canonical form, as parsed by textproto.
213 case "Original-Recipient":
214 r.OriginalRecipient, err = parseAddress(v, utf8)
215 case "Final-Recipient":
216 r.FinalRecipient, err = parseAddress(v, utf8)
218 a := Action(strings.ToLower(v))
219 actions := []Action{Failed, Delayed, Delivered, Relayed, Expanded}
221 for _, x := range actions {
229 err = fmt.Errorf("unrecognized action %q", v)
232 // todo: parse the enhanced status code?
234 t := strings.SplitN(v, "(", 2)
235 v = strings.TrimSpace(v)
236 if len(t) == 2 && strings.HasSuffix(v, ")") {
237 r.Status = strings.TrimSpace(t[0])
238 r.StatusComment = strings.TrimSpace(strings.TrimSuffix(t[1], ")"))
242 r.RemoteMTA = NameIP{Name: v}
243 case "Diagnostic-Code":
245 t := strings.SplitN(v, ";", 2)
246 dt := strings.TrimSpace(t[0])
247 if strings.ToLower(dt) != "smtp" {
248 err = fmt.Errorf("unknown diagnostic-type %q, expected smtp", dt)
249 } else if len(t) != 2 {
250 err = fmt.Errorf("missing semicolon to separate diagnostic-type from code")
252 r.DiagnosticCodeSMTP = strings.TrimSpace(t[1])
254 case "Last-Attempt-Date":
255 r.LastAttemptDate, err = parseDateTime(v)
258 case "Will-Retry-Until":
259 tm, err := parseDateTime(v)
261 r.WillRetryUntil = &tm
264 // todo future: parse localized diagnostic text field?
265 // We'll assume it is an extension field, we'll ignore it for now.
268 return Recipient{}, fmt.Errorf("parsing field %q %q: %v", k, v, err)
272 required := []string{"Final-Recipient", "Action", "Status"}
273 for _, req := range required {
274 if _, ok := h[req]; !ok {
275 return Recipient{}, fmt.Errorf("missing required recipient field %q", req)
284func parseMTA(s string, utf8 bool) (string, error) {
285 s = removeComments(s)
286 t := strings.SplitN(s, ";", 2)
288 return "", fmt.Errorf("missing semicolon that splits type and name")
290 k := strings.TrimSpace(t[0])
291 if !strings.EqualFold(k, "dns") {
292 return "", fmt.Errorf("unknown type %q, expected dns", k)
294 return strings.TrimSpace(t[1]), nil
297func parseDateTime(s string) (time.Time, error) {
298 s = removeComments(s)
299 return time.Parse(message.RFC5322Z, s)
302func parseAddress(s string, utf8 bool) (smtp.Path, error) {
303 s = removeComments(s)
304 t := strings.SplitN(s, ";", 2)
306 addrType := strings.ToLower(strings.TrimSpace(t[0]))
308 return smtp.Path{}, fmt.Errorf("missing semicolon that splits address type and address")
309 } else if addrType == "utf-8" {
311 return smtp.Path{}, fmt.Errorf("utf-8 address type for non-utf-8 dsn")
313 } else if addrType != "rfc822" {
314 return smtp.Path{}, fmt.Errorf("unrecognized address type %q, expected rfc822", addrType)
316 s = strings.TrimSpace(t[1])
318 for _, c := range s {
320 return smtp.Path{}, fmt.Errorf("non-ascii without utf-8 enabled")
324 // todo: more proper parser
325 t = strings.Split(s, "@")
327 return smtp.Path{}, fmt.Errorf("invalid email address")
329 d, err := dns.ParseDomain(t[len(t)-1])
331 return smtp.Path{}, fmt.Errorf("parsing domain: %v", err)
335 lead := strings.Join(t[:len(t)-1], "@")
336 for _, c := range lead {
337 if esc == "" && c == '\\' || esc == `\` && (c == 'x' || c == 'X') || esc == `\x` && c == '{' {
342 } else if strings.HasPrefix(esc, `\x{`) {
344 c, err := strconv.ParseInt(esc[3:], 16, 32)
346 return smtp.Path{}, fmt.Errorf("parsing localpart with hexpoint: %v", err)
348 lp += string(rune(c))
358 return smtp.Path{}, fmt.Errorf("parsing localpart: unfinished embedded unicode char")
360 localpart, err := smtp.ParseLocalpart(lp)
362 return smtp.Path{}, fmt.Errorf("parsing localpart: %v", err)
364 p := smtp.Path{Localpart: localpart, IPDomain: dns.IPDomain{Domain: d}}
368func removeComments(s string) string {
371 for _, c := range s {
374 } else if c == ')' && n > 0 {