1package tlsrptdb
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "path/filepath"
8 "time"
9
10 "github.com/mjl-/bstore"
11
12 "github.com/mjl-/mox/mlog"
13 "github.com/mjl-/mox/mox-"
14)
15
16var (
17 ReportDBTypes = []any{Record{}}
18 ReportDB *bstore.DB
19
20 // Accessed directly by tlsrptsend.
21 ResultDBTypes = []any{TLSResult{}, SuppressAddress{}}
22 ResultDB *bstore.DB
23)
24
25// Init opens and possibly initializes the databases.
26func Init() error {
27 if ReportDB != nil || ResultDB != nil {
28 return fmt.Errorf("already initialized")
29 }
30
31 log := mlog.New("tlsrptdb", nil)
32 var err error
33
34 ReportDB, err = openReportDB(mox.Shutdown, log)
35 if err != nil {
36 return fmt.Errorf("opening report db: %v", err)
37 }
38 ResultDB, err = openResultDB(mox.Shutdown, log)
39 if err != nil {
40 return fmt.Errorf("opening result db: %v", err)
41 }
42 return nil
43}
44
45func openReportDB(ctx context.Context, log mlog.Log) (*bstore.DB, error) {
46 p := mox.DataDirPath("tlsrpt.db")
47 os.MkdirAll(filepath.Dir(p), 0770)
48 opts := bstore.Options{Timeout: 5 * time.Second, Perm: 0660, RegisterLogger: log.Logger}
49 return bstore.Open(ctx, p, &opts, ReportDBTypes...)
50}
51
52func openResultDB(ctx context.Context, log mlog.Log) (*bstore.DB, error) {
53 p := mox.DataDirPath("tlsrptresult.db")
54 os.MkdirAll(filepath.Dir(p), 0770)
55 opts := bstore.Options{Timeout: 5 * time.Second, Perm: 0660, RegisterLogger: log.Logger}
56 return bstore.Open(ctx, p, &opts, ResultDBTypes...)
57}
58
59// Close closes the database connections.
60func Close() error {
61 if err := ResultDB.Close(); err != nil {
62 return fmt.Errorf("closing result db: %w", err)
63 }
64 ResultDB = nil
65
66 if err := ReportDB.Close(); err != nil {
67 return fmt.Errorf("closing report db: %w", err)
68 }
69 ReportDB = nil
70 return nil
71}
72