1// Package dmarcdb stores incoming DMARC aggrate reports and evaluations for outgoing aggregate reports.
2//
3// With DMARC, a domain can request reports with DMARC evaluation results to be
4// sent to a specified address. Mox parses such reports, stores them in its
5// database and makes them available through its admin web interface. Mox also
6// keeps track of the evaluations it does for incoming messages and sends reports
7// to mail servers that request reports.
8//
9// Only aggregate reports are stored and sent. Failure reports about individual
10// messages are not implemented.
11package dmarcdb
12
13import (
14 "context"
15 "fmt"
16 "os"
17 "path/filepath"
18 "time"
19
20 "github.com/mjl-/bstore"
21
22 "github.com/mjl-/mox/mlog"
23 "github.com/mjl-/mox/mox-"
24)
25
26// Init opens the databases.
27//
28// The incoming reports and evaluations for outgoing reports are in separate
29// databases for simpler file-based handling of the databases.
30func Init() error {
31 if ReportsDB != nil || EvalDB != nil {
32 return fmt.Errorf("already initialized")
33 }
34
35 log := mlog.New("dmarcdb", nil)
36 var err error
37
38 ReportsDB, err = openReportsDB(mox.Shutdown, log)
39 if err != nil {
40 return fmt.Errorf("open reports db: %v", err)
41 }
42
43 EvalDB, err = openEvalDB(mox.Shutdown, log)
44 if err != nil {
45 return fmt.Errorf("open eval db: %v", err)
46 }
47
48 return nil
49}
50
51func Close() error {
52 if err := ReportsDB.Close(); err != nil {
53 return fmt.Errorf("closing reports db: %w", err)
54 }
55 ReportsDB = nil
56
57 if err := EvalDB.Close(); err != nil {
58 return fmt.Errorf("closing eval db: %w", err)
59 }
60 EvalDB = nil
61 return nil
62}
63
64func openReportsDB(ctx context.Context, log mlog.Log) (*bstore.DB, error) {
65 p := mox.DataDirPath("dmarcrpt.db")
66 os.MkdirAll(filepath.Dir(p), 0770)
67 opts := bstore.Options{Timeout: 5 * time.Second, Perm: 0660, RegisterLogger: log.Logger}
68 return bstore.Open(ctx, p, &opts, ReportsDBTypes...)
69}
70
71func openEvalDB(ctx context.Context, log mlog.Log) (*bstore.DB, error) {
72 p := mox.DataDirPath("dmarceval.db")
73 os.MkdirAll(filepath.Dir(p), 0770)
74 opts := bstore.Options{Timeout: 5 * time.Second, Perm: 0660, RegisterLogger: log.Logger}
75 return bstore.Open(ctx, p, &opts, EvalDBTypes...)
76}
77