forked from vuvuzela/vuvuzela
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dial.go
263 lines (207 loc) · 5.87 KB
/
dial.go
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package vuvuzela
import (
"encoding/binary"
"fmt"
"sync"
log "github.com/Sirupsen/logrus"
"golang.org/x/crypto/nacl/box"
. "github.com/davidlazar/vuvuzela/internal"
"github.com/davidlazar/vuvuzela/rand"
"github.com/davidlazar/vuvuzela/vrpc"
)
type DialService struct {
roundsMu sync.RWMutex
rounds map[uint32]*DialRound
Idle *sync.Mutex
LaplaceMu float64
LaplaceB float64
PKI *PKI
ServerName string
PrivateKey *BoxKey
Client *vrpc.Client
LastServer bool
}
type DialRound struct {
sync.Mutex
status dialStatus
incoming [][]byte
noise [][]byte
noiseWg sync.WaitGroup
}
type dialStatus int
const (
dialRoundOpen dialStatus = iota + 1
dialRoundClosed
)
func InitDialService(srv *DialService) {
srv.rounds = make(map[uint32]*DialRound)
}
func (srv *DialService) getRound(round uint32, expectedStatus dialStatus) (*DialRound, error) {
srv.roundsMu.RLock()
r, ok := srv.rounds[round]
srv.roundsMu.RUnlock()
if !ok {
return nil, fmt.Errorf("round %d not found", round)
}
if r.status != expectedStatus {
return r, fmt.Errorf("round %d: status %v, expecting %v", round, r.status, expectedStatus)
}
return r, nil
}
func (srv *DialService) NewRound(Round uint32, _ *struct{}) error {
log.WithFields(log.Fields{"service": "dial", "rpc": "NewRound", "round": Round}).Info()
srv.Idle.Lock()
srv.roundsMu.Lock()
defer srv.roundsMu.Unlock()
_, exists := srv.rounds[Round]
if exists {
return fmt.Errorf("round %d already exists", Round)
}
round := &DialRound{}
srv.rounds[Round] = round
round.noiseWg.Add(1)
go func() {
// NOTE: unlike the convo protocol, the last server also adds noise
noiseTotal := 0
noiseCounts := make([]int, TotalDialBuckets)
for b := range noiseCounts {
bmu := cappedFlooredLaplace(srv.LaplaceMu, srv.LaplaceB)
noiseCounts[b] = bmu
noiseTotal += bmu
}
round.noise = make([][]byte, noiseTotal)
nonce := ForwardNonce(Round)
nextKeys := srv.PKI.NextServerKeys(srv.ServerName).Keys()
FillWithFakeIntroductions(round.noise, noiseCounts, nonce, nextKeys)
round.noiseWg.Done()
}()
round.status = dialRoundOpen
return nil
}
type DialAddArgs struct {
Round uint32
Onions [][]byte
}
func (srv *DialService) Add(args *DialAddArgs, _ *struct{}) error {
log.WithFields(log.Fields{"service": "dial", "rpc": "Add", "round": args.Round, "onions": len(args.Onions)}).Debug()
round, err := srv.getRound(args.Round, dialRoundOpen)
if err != nil {
return err
}
nonce := ForwardNonce(args.Round)
messages := make([][]byte, 0, len(args.Onions))
expectedOnionSize := srv.PKI.IncomingOnionOverhead(srv.ServerName) + SizeDialExchange
for _, onion := range args.Onions {
if len(onion) == expectedOnionSize {
var theirPublic [32]byte
copy(theirPublic[:], onion[0:32])
message, ok := box.Open(nil, onion[32:], nonce, &theirPublic, srv.PrivateKey.Key())
if ok {
messages = append(messages, message)
}
}
}
round.Lock()
round.incoming = append(round.incoming, messages...)
round.Unlock()
return nil
}
func (srv *DialService) filterIncoming(round *DialRound) {
incomingValid := make([][]byte, 0, len(round.incoming))
seen := make(map[uint64]bool)
for _, msg := range round.incoming {
msgkey := binary.BigEndian.Uint64(msg[len(msg)-8:])
if !seen[msgkey] {
seen[msgkey] = true
incomingValid = append(incomingValid, msg)
}
}
round.incoming = incomingValid
}
func (srv *DialService) Close(Round uint32, _ *struct{}) error {
log.WithFields(log.Fields{"service": "dial", "rpc": "Close", "round": Round}).Info()
round, err := srv.getRound(Round, dialRoundOpen)
if err != nil {
return err
}
srv.filterIncoming(round)
round.noiseWg.Wait()
round.incoming = append(round.incoming, round.noise...)
shuffler := NewShuffler(rand.Reader, len(round.incoming))
shuffler.Shuffle(round.incoming)
if !srv.LastServer {
if err := NewDialRound(srv.Client, Round); err != nil {
return fmt.Errorf("NewDialRound: %s", err)
}
srv.Idle.Unlock()
if err := RunDialRound(srv.Client, Round, round.incoming); err != nil {
return fmt.Errorf("RunDialRound: %s", err)
}
round.incoming = nil
} else {
srv.Idle.Unlock()
}
round.noise = nil
round.status = dialRoundClosed
return nil
}
type DialBucketsArgs struct {
Round uint32
}
type DialBucketsResult struct {
Buckets [][][SizeEncryptedIntro]byte
}
func (srv *DialService) Buckets(args *DialBucketsArgs, result *DialBucketsResult) error {
log.WithFields(log.Fields{"service": "dial", "rpc": "Buckets", "round": args.Round}).Info()
if !srv.LastServer {
return fmt.Errorf("Dial.Buckets can only be called on the last server")
}
round, err := srv.getRound(args.Round, dialRoundClosed)
if err != nil {
return err
}
buckets := make([][][SizeEncryptedIntro]byte, TotalDialBuckets)
ex := new(DialExchange)
for _, m := range round.incoming {
if len(m) != SizeDialExchange {
continue
}
if err := ex.Unmarshal(m); err != nil {
continue
}
if ex.Bucket >= uint32(len(buckets)) {
continue
}
buckets[ex.Bucket] = append(buckets[ex.Bucket], ex.EncryptedIntro)
}
result.Buckets = buckets
return nil
}
// TODO we should probably have a corresponding Delete rpc
func NewDialRound(client *vrpc.Client, round uint32) error {
return client.Call("DialService.NewRound", round, nil)
}
func RunDialRound(client *vrpc.Client, round uint32, onions [][]byte) error {
spans := Spans(len(onions), 4000)
calls := make([]*vrpc.Call, len(spans))
ParallelFor(len(calls), func(p *P) {
for i, ok := p.Next(); ok; i, ok = p.Next() {
span := spans[i]
calls[i] = &vrpc.Call{
Method: "DialService.Add",
Args: &DialAddArgs{
Round: round,
Onions: onions[span.Start : span.Start+span.Count],
},
Reply: nil,
}
}
})
if err := client.CallMany(calls); err != nil {
return fmt.Errorf("Add: %s", err)
}
if err := client.Call("DialService.Close", round, nil); err != nil {
return fmt.Errorf("Close: %s", err)
}
return nil
}