aboutsummaryrefslogtreecommitdiff
path: root/internal/monitor/tail.go
blob: d00ebe6b033d938b9d60b7ab37f49ed72861eea4 (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package monitor

import (
	"context"
	"fmt"
	"sync"

	"github.com/google/certificate-transparency-go/client"
	"github.com/google/certificate-transparency-go/scanner"
	"gitlab.torproject.org/rgdd/ct/pkg/merkle"
	"rgdd.se/silentct/internal/ioutil"
	"rgdd.se/silentct/internal/logutil"
)

type tail struct {
	cfg     Config
	matcher Matcher
	scanner scanner.LogClient
	checker client.CheckLogClient
}

func (t *tail) run(ctx context.Context, mon MonitoredLog, eventCh chan Event, errorCh chan error) {
	chunkCh := make(chan *chunk)
	defer close(chunkCh)

	mctx, cancel := context.WithCancel(ctx)
	defer cancel()

	var wg sync.WaitGroup
	defer wg.Wait()

	callback := func(eb scanner.EntryBatch) {
		c := chunk{startIndex: uint64(eb.Start)}
		for i := 0; i < len(eb.Entries); i++ {
			c.leafHashes = append(c.leafHashes, merkle.HashLeafNode(eb.Entries[i].LeafInput))
			match, err := t.matcher.Match(eb.Entries[i].LeafInput, eb.Entries[i].ExtraData)
			if err != nil {
				c.errors = append(c.errors, fmt.Errorf("while processing index %d for %s: %v", i, mon.Config.URL, err))
				continue
			}
			if !match {
				continue
			}

			c.matches = append(c.matches, LogEntry{
				LeafIndex: c.startIndex + uint64(i),
				LeafData:  eb.Entries[i].LeafInput,
				ExtraData: eb.Entries[i].ExtraData,
			})
		}

		chunkCh <- &c
	}

	fetcher := scanner.NewFetcher(t.scanner, &scanner.FetcherOptions{
		BatchSize:     int(t.cfg.BatchSize),
		StartIndex:    int64(mon.State.NextIndex),
		ParallelFetch: int(t.cfg.NumWorkers),
		Continuous:    true, // FIXME: don't set this for read-only log
	})

	wg.Add(1)
	go func() {
		defer wg.Done()
		defer cancel()
		fetcher.Run(mctx, callback)
	}()

	wg.Add(1)
	go func() {
		defer wg.Done()
		defer cancel()
		t.sequence(mctx, mon, eventCh, errorCh, chunkCh)
	}()
}

func (t *tail) sequence(ctx context.Context, mon MonitoredLog, eventCh chan Event, errorCh chan error, chunkCh chan *chunk) {
	state := mon.State
	heap := newChunks()
	for {
		select {
		case <-ctx.Done():
			return // FIXME: check if we can pop something before return
		case c := <-chunkCh:
			heap.push(c)
			if heap.gap(state.NextIndex) {
				continue
			}
			c = heap.pop()
			if len(c.matches) == 0 && len(c.leafHashes) < int(t.cfg.ChunkSize) {
				heap.push(c)
				continue // FIXME: don't trigger if we havn't run nextState for too long
			}
			nextState, err := t.nextState(ctx, state, c)
			if err != nil {
				errorCh <- err
				heap.push(c)
				continue
			}

			state = nextState
			eventCh <- Event{State: state, Matches: c.matches, Errors: c.errors}
		}
	}
}

func (t *tail) nextState(ctx context.Context, state State, c *chunk) (State, error) {
	newState, err := t.nextConsistentState(ctx, state)
	if err != nil {
		return State{}, err
	}
	newState, err = t.nextIncludedState(ctx, newState, c)
	if err != nil {
		return State{}, err
	}
	return newState, nil
}

func (t *tail) nextConsistentState(ctx context.Context, state State) (State, error) {
	sth, err := logutil.GetSignedTreeHead(ctx, t.checker)
	if err != nil {
		return State{}, fmt.Errorf("%s: get-sth: %v", t.checker.BaseURI(), err)
	}
	sth.LogID = state.SignedTreeHead.LogID
	oldSize := state.TreeSize
	oldRoot := state.SHA256RootHash
	newSize := sth.TreeSize
	newRoot := sth.SHA256RootHash

	proof, err := logutil.GetConsistencyProof(ctx, t.checker, oldSize, newSize)
	if err != nil {
		return State{}, fmt.Errorf("%s: get-consistency: %v", t.checker.BaseURI(), err)
	}
	if err := merkle.VerifyConsistency(oldSize, newSize, oldRoot, newRoot, proof); err != nil {
		return State{}, fmt.Errorf("%s: verify consistency: %v", t.checker.BaseURI(), err)
	}

	return State{SignedTreeHead: *sth, CompactRange: ioutil.CopyHashes(state.CompactRange), NextIndex: state.NextIndex}, nil
}

func (t *tail) nextIncludedState(ctx context.Context, state State, c *chunk) (State, error) {
	cr, err := logutil.AppendCompactRange(state.CompactRange, state.NextIndex, c.leafHashes)
	if err != nil {
		panic(fmt.Sprintf("bug: %v", err))
	}
	oldRoot := logutil.RootHash(cr)
	oldSize := state.NextIndex + uint64(len(c.leafHashes))
	newRoot := state.SHA256RootHash
	newSize := state.TreeSize

	proof, err := logutil.GetConsistencyProof(ctx, t.checker, oldSize, newSize)
	if err != nil {
		return State{}, fmt.Errorf("%s: tree: get-consistency: %v", t.checker.BaseURI(), err)
	}
	if err := merkle.VerifyConsistency(oldSize, newSize, oldRoot, newRoot, proof); err != nil {
		return State{}, fmt.Errorf("%s: tree: verify consistency: %v", t.checker.BaseURI(), err)
	}

	state.NextIndex += uint64(len(c.leafHashes))
	state.CompactRange = ioutil.UnsliceHashes(cr.Hashes())
	return state, nil
}