12 "golang.org/x/exp/slog"
14 "github.com/mjl-/mox/dns"
15 "github.com/mjl-/mox/message"
16 "github.com/mjl-/mox/mlog"
17 "github.com/mjl-/mox/smtp"
20// Parse reads a DSN message.
22// A DSN is a multipart internet mail message with 2 or 3 parts: human-readable
23// text, machine-parsable text, and optional original message or headers.
25// The first return value is the machine-parsed DSN message. The second value is
26// the entire MIME multipart message. Use its Parts field to access the
27// human-readable text and optional original message/headers.
28func Parse(elog *slog.Logger, r io.ReaderAt) (*Message, *message.Part, error) {
29 log := mlog.New("dsn", elog)
33 part, err := message.Parse(log.Logger, false, r)
35 return nil, nil, fmt.Errorf("parsing message: %v", err)
37 if part.MediaType != "MULTIPART" || part.MediaSubType != "REPORT" {
38 return nil, nil, fmt.Errorf(`message has content-type %q, must have "message/report"`, strings.ToLower(part.MediaType+"/"+part.MediaSubType))
40 err = part.Walk(log.Logger, nil)
42 return nil, nil, fmt.Errorf("parsing message parts: %v", err)
44 nparts := len(part.Parts)
45 if nparts != 2 && nparts != 3 {
46 return nil, nil, fmt.Errorf("invalid dsn, got %d multipart parts, 2 or 3 required", nparts)
49 if !(p0.MediaType == "" && p0.MediaSubType == "") && !(p0.MediaType == "TEXT" && p0.MediaSubType == "PLAIN") {
50 return nil, nil, fmt.Errorf(`invalid dsn, first part has content-type %q, must have "text/plain"`, strings.ToLower(p0.MediaType+"/"+p0.MediaSubType))
55 if !(p1.MediaType == "MESSAGE" && (p1.MediaSubType == "DELIVERY-STATUS" || p1.MediaSubType == "GLOBAL-DELIVERY-STATUS")) {
56 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))
58 utf8 := p1.MediaSubType == "GLOBAL-DELIVERY-STATUS"
59 m, err = Decode(p1.Reader(), utf8)
61 return nil, nil, fmt.Errorf("parsing dsn delivery-status part: %v", err)
64 addressPath := func(a message.Address) (smtp.Path, error) {
65 d, err := dns.ParseDomain(a.Host)
67 return smtp.Path{}, fmt.Errorf("parsing domain: %v", err)
69 return smtp.Path{Localpart: smtp.Localpart(a.User), IPDomain: dns.IPDomain{Domain: d}}, nil
71 if len(part.Envelope.From) == 1 {
72 m.From, err = addressPath(part.Envelope.From[0])
74 return nil, nil, fmt.Errorf("parsing From-header: %v", err)
77 if len(part.Envelope.To) == 1 {
78 m.To, err = addressPath(part.Envelope.To[0])
80 return nil, nil, fmt.Errorf("parsing To-header: %v", err)
83 m.Subject = part.Envelope.Subject
84 buf, err := io.ReadAll(p0.ReaderUTF8OrBinary())
86 return nil, nil, fmt.Errorf("reading human-readable text part: %v", err)
88 m.TextBody = strings.ReplaceAll(string(buf), "\r\n", "\n")
95 ct := strings.ToLower(p2.MediaType + "/" + p2.MediaSubType)
97 case "text/rfc822-headers":
98 case "message/global-headers":
99 case "message/rfc822":
100 case "message/global":
102 return nil, nil, fmt.Errorf("invalid content-type %q for optional third part with original message/headers", ct)
108// Decode parses the (global) delivery-status part of a DSN.
110// utf8 indicates if UTF-8 is allowed for this message, if used by the media
111// subtype of the message parts.
112func Decode(r io.Reader, utf8 bool) (*Message, error) {
113 m := Message{SMTPUTF8: utf8}
115 // We are using textproto.Reader to read mime headers. It requires a header section ending in \r\n.
117 b := bufio.NewReader(io.MultiReader(r, strings.NewReader("\r\n")))
118 mr := textproto.NewReader(b)
120 // Read per-message lines.
122 msgh, err := mr.ReadMIMEHeader()
124 return nil, fmt.Errorf("reading per-message lines: %v", err)
126 for k, l := range msgh {
128 return nil, fmt.Errorf("multiple values for %q: %v", k, l)
131 // note: headers are in canonical form, as parsed by textproto.
133 case "Original-Envelope-Id":
134 m.OriginalEnvelopeID = v
135 case "Reporting-Mta":
136 mta, err := parseMTA(v, utf8)
138 return nil, fmt.Errorf("parsing reporting-mta: %v", err)
142 mta, err := parseMTA(v, utf8)
144 return nil, fmt.Errorf("parsing dsn-gateway: %v", err)
147 case "Received-From-Mta":
148 mta, err := parseMTA(v, utf8)
150 return nil, fmt.Errorf("parsing received-from-mta: %v", err)
152 d, err := dns.ParseDomain(mta)
154 return nil, fmt.Errorf("parsing received-from-mta domain %q: %v", mta, err)
156 m.ReceivedFromMTA = smtp.Ehlo{Name: dns.IPDomain{Domain: d}}
158 tm, err := parseDateTime(v)
160 return nil, fmt.Errorf("parsing arrival-date: %v", err)
164 // We'll assume it is an extension field, we'll ignore it for now.
167 m.MessageHeader = msgh
169 required := []string{"Reporting-Mta"}
170 for _, req := range required {
171 if _, ok := msgh[req]; !ok {
172 return nil, fmt.Errorf("missing required recipient field %q", req)
176 rh, err := parseRecipientHeader(mr, utf8)
178 return nil, fmt.Errorf("reading per-recipient header: %v", err)
180 m.Recipients = []Recipient{rh}
182 if _, err := b.Peek(1); err == io.EOF {
185 rh, err := parseRecipientHeader(mr, utf8)
187 return nil, fmt.Errorf("reading another per-recipient header: %v", err)
189 m.Recipients = append(m.Recipients, rh)
195func parseRecipientHeader(mr *textproto.Reader, utf8 bool) (Recipient, error) {
197 h, err := mr.ReadMIMEHeader()
199 return Recipient{}, err
202 for k, l := range h {
204 return Recipient{}, fmt.Errorf("multiple values for %q: %v", k, l)
207 // note: headers are in canonical form, as parsed by textproto.
210 case "Original-Recipient":
211 r.OriginalRecipient, err = parseAddress(v, utf8)
212 case "Final-Recipient":
213 r.FinalRecipient, err = parseAddress(v, utf8)
215 a := Action(strings.ToLower(v))
216 actions := []Action{Failed, Delayed, Delivered, Relayed, Expanded}
218 for _, x := range actions {
225 err = fmt.Errorf("unrecognized action %q", v)
228 // todo: parse the enhanced status code?
231 r.RemoteMTA = NameIP{Name: v}
232 case "Diagnostic-Code":
234 t := strings.SplitN(v, ";", 2)
235 dt := strings.TrimSpace(t[0])
236 if strings.ToLower(dt) != "smtp" {
237 err = fmt.Errorf("unknown diagnostic-type %q, expected smtp", dt)
238 } else if len(t) != 2 {
239 err = fmt.Errorf("missing semicolon to separate diagnostic-type from code")
241 r.DiagnosticCode = strings.TrimSpace(t[1])
243 case "Last-Attempt-Date":
244 r.LastAttemptDate, err = parseDateTime(v)
247 case "Will-Retry-Until":
248 tm, err := parseDateTime(v)
250 r.WillRetryUntil = &tm
253 // todo future: parse localized diagnostic text field?
254 // We'll assume it is an extension field, we'll ignore it for now.
257 return Recipient{}, fmt.Errorf("parsing field %q %q: %v", k, v, err)
261 required := []string{"Final-Recipient", "Action", "Status"}
262 for _, req := range required {
263 if _, ok := h[req]; !ok {
264 return Recipient{}, fmt.Errorf("missing required recipient field %q", req)
273func parseMTA(s string, utf8 bool) (string, error) {
274 s = removeComments(s)
275 t := strings.SplitN(s, ";", 2)
277 return "", fmt.Errorf("missing semicolon that splits type and name")
279 k := strings.TrimSpace(t[0])
280 if !strings.EqualFold(k, "dns") {
281 return "", fmt.Errorf("unknown type %q, expected dns", k)
283 return strings.TrimSpace(t[1]), nil
286func parseDateTime(s string) (time.Time, error) {
287 s = removeComments(s)
288 return time.Parse(message.RFC5322Z, s)
291func parseAddress(s string, utf8 bool) (smtp.Path, error) {
292 s = removeComments(s)
293 t := strings.SplitN(s, ";", 2)
295 addrType := strings.ToLower(strings.TrimSpace(t[0]))
297 return smtp.Path{}, fmt.Errorf("missing semicolon that splits address type and address")
298 } else if addrType == "utf-8" {
300 return smtp.Path{}, fmt.Errorf("utf-8 address type for non-utf-8 dsn")
302 } else if addrType != "rfc822" {
303 return smtp.Path{}, fmt.Errorf("unrecognized address type %q, expected rfc822", addrType)
305 s = strings.TrimSpace(t[1])
307 for _, c := range s {
309 return smtp.Path{}, fmt.Errorf("non-ascii without utf-8 enabled")
313 // todo: more proper parser
314 t = strings.SplitN(s, "@", 2)
315 if len(t) != 2 || t[0] == "" || t[1] == "" {
316 return smtp.Path{}, fmt.Errorf("invalid email address")
318 d, err := dns.ParseDomain(t[1])
320 return smtp.Path{}, fmt.Errorf("parsing domain: %v", err)
324 for _, c := range t[0] {
325 if esc == "" && c == '\\' || esc == `\` && (c == 'x' || c == 'X') || esc == `\x` && c == '{' {
330 } else if strings.HasPrefix(esc, `\x{`) {
332 c, err := strconv.ParseInt(esc[3:], 16, 32)
334 return smtp.Path{}, fmt.Errorf("parsing localpart with hexpoint: %v", err)
336 lp += string(rune(c))
346 return smtp.Path{}, fmt.Errorf("parsing localpart: unfinished embedded unicode char")
348 p := smtp.Path{Localpart: smtp.Localpart(lp), IPDomain: dns.IPDomain{Domain: d}}
352func removeComments(s string) string {
355 for _, c := range s {
358 } else if c == ')' && n > 0 {