aboutsummaryrefslogtreecommitdiff
path: root/database.go
blob: 87dfb4c385325ddb5aa26d4fceb444b797ca2e96 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main

import (
	"bytes"
	"io/ioutil"
	"log"
	"net/http"
	"sync"
	"time"

	"git.sr.ht/~benburwell/gosumdbaudit/sumdb"
)

type database struct {
	host         string
	key          string
	pollInterval time.Duration

	hc http.Client

	config   map[string][]byte
	configMu sync.RWMutex
}

func (d *database) ReadRemote(path string) ([]byte, error) {
	log.Printf("read remote: %s", path)
	resp, err := d.hc.Get("https://" + d.host + path)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	return ioutil.ReadAll(resp.Body)
}

func (d *database) ReadConfig(file string) ([]byte, error) {
	log.Printf("read config: %s", file)
	if file == "key" {
		return []byte(d.key), nil
	}
	d.configMu.RLock()
	defer d.configMu.RUnlock()
	if d.config == nil {
		d.config = make(map[string][]byte)
		// d.config["sum.golang.org/latest"] = []byte(`go.sum database tree
		// 163038
		// S1dhskM/kuUJUOCz3InBRhl0vFiHxr0INft+24ClisI=

		// — sum.golang.org Az3gruAGD/ybzwcCUArmKpzAZNmEOu3Yahr9WIKA2SFAK3G2xzo39uHS70mylR3nsT9t3ZpVQW89RT6Tg1+1nIf7bgI=
		// `)
	}
	c, ok := d.config[file]
	if !ok {
		return nil, nil
	}
	return c, nil
}

func (d *database) WriteConfig(file string, old, new []byte) error {
	log.Printf("write config: %s", file)
	d.configMu.Lock()
	defer d.configMu.Unlock()
	if val, ok := d.config[file]; ok && !bytes.Equal(val, old) {
		return sumdb.ErrWriteConflict
	}
	d.config[file] = new
	return nil
}

func (d *database) Log(msg string) {
	log.Printf(msg)
}

func (d *database) SecurityError(msg string) {
	log.Printf("!!! SECURITY ERROR !!!\n%s", msg)
}