13 "github.com/mjl-/mox/dns"
14 "github.com/mjl-/mox/message"
15 "github.com/mjl-/mox/mlog"
16 "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 lp, err := smtp.ParseLocalpart(a.User)
71 return smtp.Path{}, fmt.Errorf("parsing localpart: %v", err)
73 return smtp.Path{Localpart: lp, IPDomain: dns.IPDomain{Domain: d}}, nil
75 if len(part.Envelope.From) == 1 {
76 m.From, err = addressPath(part.Envelope.From[0])
78 return nil, nil, fmt.Errorf("parsing From-header: %v", err)
81 if len(part.Envelope.To) == 1 {
82 m.To, err = addressPath(part.Envelope.To[0])
84 return nil, nil, fmt.Errorf("parsing To-header: %v", err)
87 m.Subject = part.Envelope.Subject
88 buf, err := io.ReadAll(p0.ReaderUTF8OrBinary())
90 return nil, nil, fmt.Errorf("reading human-readable text part: %v", err)
92 m.TextBody = strings.ReplaceAll(string(buf), "\r\n", "\n")
99 ct := strings.ToLower(p2.MediaType + "/" + p2.MediaSubType)
101 case "text/rfc822-headers":
102 case "message/global-headers":
103 case "message/rfc822":
104 case "message/global":
106 return nil, nil, fmt.Errorf("invalid content-type %q for optional third part with original message/headers", ct)
112// Decode parses the (global) delivery-status part of a DSN.
114// utf8 indicates if UTF-8 is allowed for this message, if used by the media
115// subtype of the message parts.
116func Decode(r io.Reader, utf8 bool) (*Message, error) {
117 m := Message{SMTPUTF8: utf8}
119 // We are using textproto.Reader to read mime headers. It requires a header section ending in \r\n.
121 b := bufio.NewReader(io.MultiReader(r, strings.NewReader("\r\n")))
122 mr := textproto.NewReader(b)
124 // Read per-message lines.
126 msgh, err := mr.ReadMIMEHeader()
128 return nil, fmt.Errorf("reading per-message lines: %v", err)
130 for k, l := range msgh {
132 return nil, fmt.Errorf("multiple values for %q: %v", k, l)
135 // note: headers are in canonical form, as parsed by textproto.
137 case "Original-Envelope-Id":
138 m.OriginalEnvelopeID = v
139 case "Reporting-Mta":
140 mta, err := parseMTA(v, utf8)
142 return nil, fmt.Errorf("parsing reporting-mta: %v", err)
146 mta, err := parseMTA(v, utf8)
148 return nil, fmt.Errorf("parsing dsn-gateway: %v", err)
151 case "Received-From-Mta":
152 mta, err := parseMTA(v, utf8)
154 return nil, fmt.Errorf("parsing received-from-mta: %v", err)
156 d, err := dns.ParseDomain(mta)
158 return nil, fmt.Errorf("parsing received-from-mta domain %q: %v", mta, err)
160 m.ReceivedFromMTA = smtp.Ehlo{Name: dns.IPDomain{Domain: d}}
162 tm, err := parseDateTime(v)
164 return nil, fmt.Errorf("parsing arrival-date: %v", err)
168 // We'll assume it is an extension field, we'll ignore it for now.
171 m.MessageHeader = msgh
173 required := []string{"Reporting-Mta"}
174 for _, req := range required {
175 if _, ok := msgh[req]; !ok {
176 return nil, fmt.Errorf("missing required recipient field %q", req)
180 rh, err := parseRecipientHeader(mr, utf8)
182 return nil, fmt.Errorf("reading per-recipient header: %v", err)
184 m.Recipients = []Recipient{rh}
186 if _, err := b.Peek(1); err == io.EOF {
189 rh, err := parseRecipientHeader(mr, utf8)
191 return nil, fmt.Errorf("reading another per-recipient header: %v", err)
193 m.Recipients = append(m.Recipients, rh)
199func parseRecipientHeader(mr *textproto.Reader, utf8 bool) (Recipient, error) {
201 h, err := mr.ReadMIMEHeader()
203 return Recipient{}, err
206 for k, l := range h {
208 return Recipient{}, fmt.Errorf("multiple values for %q: %v", k, l)
211 // note: headers are in canonical form, as parsed by textproto.
214 case "Original-Recipient":
215 r.OriginalRecipient, err = parseAddress(v, utf8)
216 case "Final-Recipient":
217 r.FinalRecipient, err = parseAddress(v, utf8)
219 a := Action(strings.ToLower(v))
220 actions := []Action{Failed, Delayed, Delivered, Relayed, Expanded}
221 if slices.Contains(actions, a) {
224 err = fmt.Errorf("unrecognized action %q", v)
227 // todo: parse the enhanced status code?
229 t := strings.SplitN(v, "(", 2)
230 v = strings.TrimSpace(v)
231 if len(t) == 2 && strings.HasSuffix(v, ")") {
232 r.Status = strings.TrimSpace(t[0])
233 r.StatusComment = strings.TrimSpace(strings.TrimSuffix(t[1], ")"))
237 r.RemoteMTA = NameIP{Name: v}
238 case "Diagnostic-Code":
240 t := strings.SplitN(v, ";", 2)
241 dt := strings.TrimSpace(t[0])
242 if strings.ToLower(dt) != "smtp" {
243 err = fmt.Errorf("unknown diagnostic-type %q, expected smtp", dt)
244 } else if len(t) != 2 {
245 err = fmt.Errorf("missing semicolon to separate diagnostic-type from code")
247 r.DiagnosticCodeSMTP = strings.TrimSpace(t[1])
249 case "Last-Attempt-Date":
250 r.LastAttemptDate, err = parseDateTime(v)
253 case "Will-Retry-Until":
254 tm, err := parseDateTime(v)
256 r.WillRetryUntil = &tm
259 // todo future: parse localized diagnostic text field?
260 // We'll assume it is an extension field, we'll ignore it for now.
263 return Recipient{}, fmt.Errorf("parsing field %q %q: %v", k, v, err)
267 required := []string{"Final-Recipient", "Action", "Status"}
268 for _, req := range required {
269 if _, ok := h[req]; !ok {
270 return Recipient{}, fmt.Errorf("missing required recipient field %q", req)
279func parseMTA(s string, utf8 bool) (string, error) {
280 s = removeComments(s)
281 t := strings.SplitN(s, ";", 2)
283 return "", fmt.Errorf("missing semicolon that splits type and name")
285 k := strings.TrimSpace(t[0])
286 if !strings.EqualFold(k, "dns") {
287 return "", fmt.Errorf("unknown type %q, expected dns", k)
289 return strings.TrimSpace(t[1]), nil
292func parseDateTime(s string) (time.Time, error) {
293 s = removeComments(s)
294 return time.Parse(message.RFC5322Z, s)
297func parseAddress(s string, utf8 bool) (smtp.Path, error) {
298 s = removeComments(s)
299 t := strings.SplitN(s, ";", 2)
301 addrType := strings.ToLower(strings.TrimSpace(t[0]))
303 return smtp.Path{}, fmt.Errorf("missing semicolon that splits address type and address")
304 } else if addrType == "utf-8" {
306 return smtp.Path{}, fmt.Errorf("utf-8 address type for non-utf-8 dsn")
308 } else if addrType != "rfc822" {
309 return smtp.Path{}, fmt.Errorf("unrecognized address type %q, expected rfc822", addrType)
311 s = strings.TrimSpace(t[1])
313 for _, c := range s {
315 return smtp.Path{}, fmt.Errorf("non-ascii without utf-8 enabled")
319 // todo: more proper parser
320 t = strings.Split(s, "@")
322 return smtp.Path{}, fmt.Errorf("invalid email address")
324 d, err := dns.ParseDomain(t[len(t)-1])
326 return smtp.Path{}, fmt.Errorf("parsing domain: %v", err)
330 lead := strings.Join(t[:len(t)-1], "@")
331 for _, c := range lead {
332 if esc == "" && c == '\\' || esc == `\` && (c == 'x' || c == 'X') || esc == `\x` && c == '{' {
337 } else if strings.HasPrefix(esc, `\x{`) {
339 c, err := strconv.ParseInt(esc[3:], 16, 32)
341 return smtp.Path{}, fmt.Errorf("parsing localpart with hexpoint: %v", err)
343 lp += string(rune(c))
353 return smtp.Path{}, fmt.Errorf("parsing localpart: unfinished embedded unicode char")
355 localpart, err := smtp.ParseLocalpart(lp)
357 return smtp.Path{}, fmt.Errorf("parsing localpart: %v", err)
359 p := smtp.Path{Localpart: localpart, IPDomain: dns.IPDomain{Domain: d}}
363func removeComments(s string) string {
366 for _, c := range s {
369 } else if c == ')' && n > 0 {