1// Package dmarcrpt parses DMARC aggregate feedback reports.
15 "golang.org/x/exp/slog"
17 "github.com/mjl-/mox/message"
18 "github.com/mjl-/mox/mlog"
19 "github.com/mjl-/mox/moxio"
22var ErrNoReport = errors.New("no dmarc aggregate report found in message")
24// ParseReport parses an XML aggregate feedback report.
25// The maximum report size is 20MB.
26func ParseReport(r io.Reader) (*Feedback, error) {
27 r = &moxio.LimitReader{R: r, Limit: 20 * 1024 * 1024}
29 d := xml.NewDecoder(r)
30 if err := d.Decode(&feedback); err != nil {
36// ParseMessageReport parses an aggregate feedback report from a mail message. The
37// maximum message size is 15MB, the maximum report size after decompression is
39func ParseMessageReport(elog *slog.Logger, r io.ReaderAt) (*Feedback, error) {
40 log := mlog.New("dmarcrpt", elog)
42 p, err := message.Parse(log.Logger, true, &moxio.LimitAtReader{R: r, Limit: 15 * 1024 * 1024})
44 return nil, fmt.Errorf("parsing mail message: %s", err)
47 return parseMessageReport(log, p)
50func parseMessageReport(log mlog.Log, p message.Part) (*Feedback, error) {
52 // In practice, some parties will send the report as the only (non-multipart)
53 // content of the message.
55 if p.MediaType != "MULTIPART" {
60 sp, err := p.ParseNextPart(log.Logger)
62 return nil, ErrNoReport
67 report, err := parseMessageReport(log, *sp)
68 if err == ErrNoReport {
70 } else if err != nil || report != nil {
76func parseReport(p message.Part) (*Feedback, error) {
77 ct := strings.ToLower(p.MediaType + "/" + p.MediaSubType)
80 // If no (useful) content-type is set, try to detect it.
81 if ct == "" || ct == "application/octet-stream" {
82 data := make([]byte, 512)
83 n, err := io.ReadFull(r, data)
85 return nil, ErrNoReport
86 } else if err != nil && err != io.ErrUnexpectedEOF {
87 return nil, fmt.Errorf("reading application/octet-stream for content-type detection: %v", err)
90 ct = http.DetectContentType(data)
91 r = io.MultiReader(bytes.NewReader(data), r)
95 case "application/zip":
96 // Google sends messages with direct application/zip content-type.
98 case "application/gzip", "application/x-gzip":
99 gzr, err := gzip.NewReader(r)
101 return nil, fmt.Errorf("decoding gzip xml report: %s", err)
103 return ParseReport(gzr)
104 case "text/xml", "application/xml":
105 return ParseReport(r)
107 return nil, ErrNoReport
110func parseZip(r io.Reader) (*Feedback, error) {
111 buf, err := io.ReadAll(r)
113 return nil, fmt.Errorf("reading feedback: %s", err)
115 zr, err := zip.NewReader(bytes.NewReader(buf), int64(len(buf)))
117 return nil, fmt.Errorf("parsing zip file: %s", err)
119 if len(zr.File) != 1 {
120 return nil, fmt.Errorf("zip contains %d files, expected 1", len(zr.File))
122 f, err := zr.File[0].Open()
124 return nil, fmt.Errorf("opening file in zip: %s", err)
127 return ParseReport(f)