parsimony/internal/router/dsn.go
tgiachi cd31d919a9 test(router): pin the edges of DSN parsing
- message/global-delivery-status (RFC 6533) counts like delivery-status.
- Only the first delivery-status part is read.
- A malformed delivery-status part does not count.
- Drop the redundant empty-boundary check: the multipart reader already
  fails on it.
2026-11-10 11:52:25 +01:00

66 lines
2.1 KiB
Go

package router
import (
"bufio"
"bytes"
"io"
"mime"
"mime/multipart"
"net/mail"
"net/textproto"
"strings"
)
// recipientUnknown are the DSN status codes that say the recipient does not exist: 5.1.1 bad
// mailbox, 5.1.2 bad domain, 5.1.3 bad address syntax, 5.1.6 moved, 5.1.10 null MX. It is the
// same set as outbound.recipientUnknown, used for RCPT TO answers; keep the two in sync.
var recipientUnknown = map[string]bool{"5.1.1": true, "5.1.2": true, "5.1.3": true, "5.1.6": true, "5.1.10": true}
// isHardBounce reports whether data is a delivery status notification (RFC 3464) that reports a
// recipient as non-existent: a multipart/report with a message/delivery-status part holding a
// per-recipient block with "Action: failed" and a status in recipientUnknown. Anything else (a
// policy or content rejection, a full mailbox, a delay, a status line in plain text) is not.
func isHardBounce(data []byte) bool {
msg, err := mail.ReadMessage(bytes.NewReader(data))
if err != nil {
return false
}
mt, params, err := mime.ParseMediaType(msg.Header.Get("Content-Type"))
if err != nil || mt != "multipart/report" {
return false
}
mr := multipart.NewReader(msg.Body, params["boundary"])
for {
p, err := mr.NextPart()
if err != nil {
return false
}
pt, _, _ := mime.ParseMediaType(p.Header.Get("Content-Type"))
if pt == "message/delivery-status" || pt == "message/global-delivery-status" {
return failedUnknownRecipient(p)
}
}
}
// failedUnknownRecipient reads the fields of a delivery-status body: a per-message block, then one
// block per recipient, separated by blank lines.
func failedUnknownRecipient(r io.Reader) bool {
tr := textproto.NewReader(bufio.NewReader(r))
for {
h, err := tr.ReadMIMEHeader()
if firstWord(h.Get("Action")) == "failed" && recipientUnknown[firstWord(h.Get("Status"))] {
return true
}
if err != nil {
return false
}
}
}
// firstWord returns the lowercase value of a field without its trailing comment.
func firstWord(v string) string {
if f := strings.Fields(v); len(f) > 0 {
return strings.ToLower(f[0])
}
return ""
}