1// Package dmarcrpt parses DMARC aggregate feedback reports.
16 "github.com/mjl-/mox/message"
17 "github.com/mjl-/mox/mlog"
18 "github.com/mjl-/mox/moxio"
21var ErrNoReport = errors.New("no dmarc aggregate report found in message")
23// ParseReport parses an XML aggregate feedback report.
24// The maximum report size is 20MB.
25func ParseReport(r io.Reader) (*Feedback, error) {
26 r = &moxio.LimitReader{R: r, Limit: 20 * 1024 * 1024}
28 d := xml.NewDecoder(r)
29 if err := d.Decode(&feedback); err != nil {
35// ParseMessageReport parses an aggregate feedback report from a mail message. The
36// maximum message size is 15MB, the maximum report size after decompression is
38func ParseMessageReport(elog *slog.Logger, r io.ReaderAt) (*Feedback, error) {
39 log := mlog.New("dmarcrpt", elog)
41 p, err := message.Parse(log.Logger, true, &moxio.LimitAtReader{R: r, Limit: 15 * 1024 * 1024})
43 return nil, fmt.Errorf("parsing mail message: %s", err)
46 return parseMessageReport(log, p)
49func parseMessageReport(log mlog.Log, p message.Part) (*Feedback, error) {
51 // In practice, some parties will send the report as the only (non-multipart)
52 // content of the message.
54 if p.MediaType != "MULTIPART" {
59 sp, err := p.ParseNextPart(log.Logger)
61 return nil, ErrNoReport
66 report, err := parseMessageReport(log, *sp)
67 if err == ErrNoReport {
69 } else if err != nil || report != nil {
75func parseReport(p message.Part) (*Feedback, error) {
76 ct := strings.ToLower(p.MediaType + "/" + p.MediaSubType)
79 // If no (useful) content-type is set, try to detect it.
80 if ct == "" || ct == "application/octet-stream" {
81 data := make([]byte, 512)
82 n, err := io.ReadFull(r, data)
84 return nil, ErrNoReport
85 } else if err != nil && err != io.ErrUnexpectedEOF {
86 return nil, fmt.Errorf("reading application/octet-stream for content-type detection: %v", err)
89 ct = http.DetectContentType(data)
90 r = io.MultiReader(bytes.NewReader(data), r)
94 case "application/zip":
95 // Google sends messages with direct application/zip content-type.
97 case "application/gzip", "application/x-gzip":
98 gzr, err := gzip.NewReader(r)
100 return nil, fmt.Errorf("decoding gzip xml report: %s", err)
102 return ParseReport(gzr)
103 case "text/xml", "application/xml":
104 return ParseReport(r)
106 return nil, ErrNoReport
109func parseZip(r io.Reader) (*Feedback, error) {
110 buf, err := io.ReadAll(r)
112 return nil, fmt.Errorf("reading feedback: %s", err)
114 zr, err := zip.NewReader(bytes.NewReader(buf), int64(len(buf)))
116 return nil, fmt.Errorf("parsing zip file: %s", err)
118 if len(zr.File) != 1 {
119 return nil, fmt.Errorf("zip contains %d files, expected 1", len(zr.File))
121 f, err := zr.File[0].Open()
123 return nil, fmt.Errorf("opening file in zip: %s", err)
126 return ParseReport(f)