This repository has been archived by the owner on Jan 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
connection.go
768 lines (689 loc) · 18.6 KB
/
connection.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
// connection.go - Client to provider connection.
// Copyright (C) 2017 Yawning Angel.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package minclient
import (
"bytes"
"context"
"errors"
"fmt"
"net"
"sync"
"sync/atomic"
"time"
"github.com/katzenpost/core/crypto/rand"
"github.com/katzenpost/core/epochtime"
cpki "github.com/katzenpost/core/pki"
"github.com/katzenpost/core/wire"
"github.com/katzenpost/core/wire/commands"
"github.com/katzenpost/core/worker"
"gopkg.in/op/go-logging.v1"
)
var (
// ErrNotConnected is the error returned when an operation fails due to the
// client not currently being connected to the Provider.
ErrNotConnected = errors.New("minclient/conn: not connected to the Provider")
// ErrShutdown is the error returned when the connection is closed due to
// a call to Shutdown().
ErrShutdown = errors.New("shutdown requested")
defaultDialer = net.Dialer{
KeepAlive: keepAliveInterval,
Timeout: connectTimeout,
}
keepAliveInterval = 3 * time.Minute
connectTimeout = 1 * time.Minute
pkiFallbackInterval = 3 * time.Minute
)
// ConnectError is the error used to indicate that a connect attempt has failed.
type ConnectError struct {
// Err is the original error that caused the connect attempt to fail.
Err error
}
// Error implements the error interface.
func (e *ConnectError) Error() string {
return fmt.Sprintf("minclient/conn: connect error: %v", e.Err)
}
func newConnectError(f string, a ...interface{}) error {
return &ConnectError{Err: fmt.Errorf(f, a...)}
}
// PKIError is the error used to indicate PKI related failures.
type PKIError struct {
// Err is the original PKI error.
Err error
}
// Error implements the error interface.
func (e *PKIError) Error() string {
return fmt.Sprintf("minclient/conn: PKI error: %v", e.Err)
}
func newPKIError(f string, a ...interface{}) error {
return &PKIError{Err: fmt.Errorf(f, a...)}
}
// ProtocolError is the error used to indicate that the connection was closed
// due to wire protocol related reasons.
type ProtocolError struct {
// Err is the original error that triggered connection termination.
Err error
}
// Error implements the error interface.
func (e *ProtocolError) Error() string {
return fmt.Sprintf("minclient/conn: protocol error: %v", e.Err)
}
func newProtocolError(f string, a ...interface{}) error {
return &ProtocolError{Err: fmt.Errorf(f, a...)}
}
type connection struct {
sync.Mutex
worker.Worker
c *Client
log *logging.Logger
pkiEpoch uint64
descriptor *cpki.MixDescriptor
pkiFetchCh chan interface{}
fetchCh chan interface{}
sendCh chan *connSendCtx
getConsensusCh chan *getConsensusCtx
retryDelay int64 // used as atomic time.Duration
isConnected bool
}
type getConsensusCtx struct {
replyCh chan interface{}
epoch uint64
doneFn func(error)
}
type connSendCtx struct {
pkt []byte
doneFn func(error)
}
// ForceFetch attempts to force an otherwise idle client to attempt to fetch
// the contents of the user's spool. This call has no effect if a connection
// is not established or if the connection is already in the middle of a
// fetch cycle, and should be considered a best effort operation.
func (c *Client) ForceFetch() {
select {
case c.conn.fetchCh <- true:
default:
}
}
func (c *connection) onPKIFetch() {
select {
case c.pkiFetchCh <- true:
default:
// Probably a connection is in progress, the right thing will happen
// regardless of if the signal gets dropped, though it might require
// the fallback timer to fire.
}
}
func (c *connection) getDescriptor() error {
ok := false
defer func() {
if !ok {
c.pkiEpoch = 0
c.descriptor = nil
}
}()
doc := c.c.CurrentDocument()
if doc == nil {
c.log.Debugf("No PKI document for current epoch.")
return newPKIError("no PKI document for current epoch")
}
desc, err := doc.GetProvider(c.c.cfg.Provider)
if err != nil {
c.log.Debugf("Failed to find descriptor for Provider: %v", err)
return newPKIError("failed to find descriptor for Provider: %v", err)
}
if c.c.cfg.ProviderKeyPin != nil && !c.c.cfg.ProviderKeyPin.Equal(desc.IdentityKey) {
c.log.Errorf("Provider identity key does not match pinned key: %v", desc.IdentityKey)
return newPKIError("identity key for Provider does not match pinned key: %v", desc.IdentityKey)
}
if desc != c.descriptor {
c.log.Debugf("Descriptor for epoch %v: %+v", doc.Epoch, desc)
}
c.descriptor = desc
c.pkiEpoch = doc.Epoch
ok = true
return nil
}
func (c *connection) connectWorker() {
defer c.log.Debugf("Terminating connect worker.")
dialCtx, cancelFn := context.WithCancel(context.Background())
go func() {
select {
case <-c.HaltCh():
cancelFn()
case <-dialCtx.Done():
}
}()
timer := time.NewTimer(pkiFallbackInterval)
defer timer.Stop()
for {
var timerFired bool
// Wait for a signal from the PKI (or a fallback timer to pass)
// before querying the PKI for a document iff we do not have the
// Provider's current descriptor.
if now, _, _ := epochtime.FromUnix(c.c.pki.skewedUnixTime()); now != c.pkiEpoch {
select {
case <-c.HaltCh():
return
case <-c.pkiFetchCh:
c.log.Debugf("PKI fetch successful.")
case <-timer.C:
c.log.Debugf("PKI fetch fallback timer.")
timerFired = true
}
}
if !timerFired && !timer.Stop() {
<-timer.C
}
// Query the PKI for the current descriptor.
if err := c.getDescriptor(); err == nil {
// Attempt to connect.
c.doConnect(dialCtx)
} else if c.c.cfg.OnConnFn != nil {
// Can't connect due to lacking descriptor.
c.c.cfg.OnConnFn(err)
}
select {
case <-c.HaltCh():
return
default:
}
timer.Reset(pkiFallbackInterval)
}
// NOTREACHED
}
func (c *connection) doConnect(dialCtx context.Context) {
const (
retryIncrement = 15 * time.Second
maxRetryDelay = 2 * time.Minute
)
dialFn := c.c.cfg.DialContextFn
if dialFn == nil {
dialFn = defaultDialer.DialContext
}
var connErr error
defer func() {
if connErr == nil {
panic("BUG: connErr is nil on connection teardown.")
}
if c.c.cfg.OnConnFn != nil {
c.c.cfg.OnConnFn(connErr)
}
}()
for {
if connErr = c.getDescriptor(); connErr != nil {
c.log.Debugf("Aborting connect loop, descriptor no longer present.")
return
}
// Build the list of candidate addresses, in decreasing order of
// preference, by transport.
var dstAddrs []string
transports := c.c.cfg.PreferedTransports
if transports == nil {
transports = cpki.ClientTransports
}
for _, t := range transports {
if v, ok := c.descriptor.Addresses[t]; ok {
dstAddrs = append(dstAddrs, v...)
}
}
if len(dstAddrs) == 0 {
c.log.Warningf("Aborting connect loop, no suitable addresses found.")
c.descriptor = nil // Give up till the next PKI fetch.
connErr = newConnectError("no suitable addreses found")
return
}
for _, addrPort := range dstAddrs {
select {
case <-time.After(time.Duration(atomic.LoadInt64(&c.retryDelay))):
// Back off the reconnect delay.
atomic.AddInt64(&c.retryDelay, int64(retryIncrement))
if atomic.LoadInt64(&c.retryDelay) > int64(maxRetryDelay) {
atomic.StoreInt64(&c.retryDelay, int64(maxRetryDelay))
}
case <-c.HaltCh():
c.log.Debugf("(Re)connection attempts cancelled.")
connErr = ErrShutdown
return
}
c.log.Debugf("Dialing: %v", addrPort)
conn, err := dialFn(dialCtx, "tcp", addrPort)
select {
case <-c.HaltCh():
if conn != nil {
conn.Close()
}
connErr = ErrShutdown
return
default:
if err != nil {
c.log.Warningf("Failed to connect to %v: %v", addrPort, err)
if c.c.cfg.OnConnFn != nil {
c.c.cfg.OnConnFn(&ConnectError{Err: err})
}
continue
}
}
c.log.Debugf("TCP connection established.")
// Do something with the connection.
c.onTCPConn(conn)
// Re-iterate through the address/ports on a sucessful connect.
c.log.Debugf("Connection terminated, will reconnect.")
// Emit a ConnectError when disconnected.
c.onConnStatusChange(ErrNotConnected)
break
}
}
}
func (c *connection) onTCPConn(conn net.Conn) {
const handshakeTimeout = 1 * time.Minute
var err error
defer func() {
c.log.Debugf("TCP connection closed.")
conn.Close()
}()
// Allocate the session struct.
cfg := &wire.SessionConfig{
Authenticator: c,
AdditionalData: []byte(c.c.cfg.User),
AuthenticationKey: c.c.cfg.LinkKey,
RandomReader: rand.Reader,
}
w, err := wire.NewSession(cfg, true)
if err != nil {
c.log.Errorf("Failed to allocate session: %v", err)
if c.c.cfg.OnConnFn != nil {
c.c.cfg.OnConnFn(&ConnectError{Err: err})
}
return
}
defer w.Close()
// Bind the session to the conn, handshake, authenticate.
conn.SetDeadline(time.Now().Add(handshakeTimeout))
if err = w.Initialize(conn); err != nil {
c.log.Errorf("Handshake failed: %v", err)
if c.c.cfg.OnConnFn != nil {
c.c.cfg.OnConnFn(&ConnectError{Err: err})
}
return
}
c.log.Debugf("Handshake completed.")
conn.SetDeadline(time.Time{})
c.c.pki.setClockSkew(int64(w.ClockSkew().Seconds()))
c.onWireConn(w)
}
func (c *connection) onWireConn(w *wire.Session) {
c.onConnStatusChange(nil)
var wireErr error
var cbWg sync.WaitGroup
closeConnCh := make(chan error, 1)
forceCloseConn := func(err error) {
// We only care about the first error from a callback.
select {
case closeConnCh <- err:
default:
}
}
cmdCloseCh := make(chan interface{})
defer func() {
if wireErr == nil {
panic("BUG: wireErr is nil on connection teardown.")
}
c.onConnStatusChange(wireErr)
close(cmdCloseCh)
cbWg.Wait()
}()
// Start the peer reader.
cmdCh := make(chan interface{})
go func() {
defer close(cmdCh)
for {
rawCmd, err := w.RecvCommand()
if err != nil {
c.log.Debugf("Failed to receive command: %v", err)
cmdCh <- err
return
}
// XXX: why retryDelay 0?
atomic.StoreInt64(&c.retryDelay, 0)
select {
case cmdCh <- rawCmd:
case <-cmdCloseCh:
return
}
}
}()
dispatchOnEmpty := func() error {
if c.c.cfg.OnEmptyFn != nil {
cbWg.Add(1)
go func() {
defer cbWg.Done()
if err := c.c.cfg.OnEmptyFn(); err != nil {
c.log.Debugf("Caller failed to handle MessageEmpty: %v", err)
forceCloseConn(err)
}
}()
}
return nil
}
var consensusCtx *getConsensusCtx
defer func() {
if consensusCtx != nil {
consensusCtx.replyCh <- ErrNotConnected
}
}()
var fetchDelay time.Duration
var selectAt time.Time
adjFetchDelay := func() {
sendAt := time.Now()
if deltaT := sendAt.Sub(selectAt); deltaT < fetchDelay {
fetchDelay = fetchDelay - deltaT
} else {
fetchDelay = 0
}
}
var seq uint32
checkSeq := func(cmdSeq uint32) error {
if seq != cmdSeq {
return newProtocolError("invalid/unexpected sequence: %v (Expecting: %v)", cmdSeq, seq)
}
return nil
}
nrReqs, nrResps := 0, 0
for {
var rawCmd commands.Command
var doFetch bool
selectAt = time.Now()
select {
case <-time.After(fetchDelay):
doFetch = true
case <-c.fetchCh:
doFetch = true
case ctx := <-c.getConsensusCh:
c.log.Debugf("Dequeued GetConsesus for send.")
if consensusCtx != nil {
ctx.doneFn(fmt.Errorf("outstanding GetConsensus already exists: %v", consensusCtx.epoch))
} else {
consensusCtx = ctx
cmd := &commands.GetConsensus{
Epoch: ctx.epoch,
}
wireErr = w.SendCommand(cmd)
ctx.doneFn(wireErr)
if wireErr != nil {
c.log.Debugf("Failed to send GetConsensus: %v", wireErr)
return
}
c.log.Debugf("Sent GetConsensus.")
}
adjFetchDelay()
continue
case ctx := <-c.sendCh:
c.log.Debugf("Dequeued packet for send.")
cmd := &commands.SendPacket{
SphinxPacket: ctx.pkt,
}
wireErr = w.SendCommand(cmd)
ctx.doneFn(wireErr)
if wireErr != nil {
c.log.Debugf("Failed to send SendPacket: %v", wireErr)
return
}
c.log.Debugf("Sent SendPacket.")
adjFetchDelay()
continue
case tmp, ok := <-cmdCh:
if !ok {
wireErr = newProtocolError("command receive worker terminated")
return
}
switch cmdOrErr := tmp.(type) {
case commands.Command:
rawCmd = cmdOrErr
case error:
wireErr = cmdOrErr
return
}
case <-c.HaltCh():
wireErr = ErrShutdown
return
case wireErr = <-closeConnCh:
c.log.Debugf("Closing connection due to callback error: %v", wireErr)
return
}
// Send a fetch if there is not one outstanding.
if doFetch {
if nrReqs == nrResps {
cmd := &commands.RetrieveMessage{
Sequence: seq,
}
if wireErr = w.SendCommand(cmd); wireErr != nil {
c.log.Debugf("Failed to send RetrieveMessage: %v", wireErr)
return
}
c.log.Debugf("Sent RetrieveMessage: %d", seq)
nrReqs++
}
fetchDelay = c.c.GetPollInterval()
continue
}
creds, err := w.PeerCredentials()
if err != nil {
// do not continue processing this command
continue
}
// Update the cached descriptor, and re-validate the connection.
if !c.IsPeerValid(creds) {
c.log.Warningf("No longer have a descriptor for current peer.")
wireErr = newProtocolError("current consensus no longer lists the Provider")
return
}
// Handle the response.
switch cmd := rawCmd.(type) {
case *commands.NoOp:
c.log.Debugf("Received NoOp.")
case *commands.Disconnect:
c.log.Debugf("Received Disconnect.")
wireErr = newProtocolError("peer send Disconnect")
return
case *commands.MessageEmpty:
c.log.Debugf("Received MessageEmpty: %v", cmd.Sequence)
if wireErr = checkSeq(cmd.Sequence); wireErr != nil {
c.log.Errorf("MessageEmpty sequence unexpected: %v", cmd.Sequence)
return
}
nrResps++
if wireErr = dispatchOnEmpty(); wireErr != nil {
return
}
case *commands.Message:
c.log.Debugf("Received Message: %v", cmd.Sequence)
if wireErr = checkSeq(cmd.Sequence); wireErr != nil {
c.log.Errorf("Message sequence unexpected: %v", cmd.Sequence)
return
}
nrResps++
if c.c.cfg.OnMessageFn != nil {
cbWg.Add(1)
go func() {
defer cbWg.Done()
if err := c.c.cfg.OnMessageFn(cmd.Payload); err != nil {
c.log.Debugf("Caller failed to handle Message: %v", err)
forceCloseConn(err)
}
}()
}
seq++
if cmd.QueueSizeHint == 0 {
c.log.Debugf("QueueSizeHint indicates empty queue, calling dispatchOnEmpty.")
if wireErr = dispatchOnEmpty(); wireErr != nil {
c.log.Debugf("dispatchOnEmpty returned error: %v", wireErr)
return
}
}
case *commands.MessageACK:
c.log.Debugf("Received MessageACK: %v", cmd.Sequence)
if wireErr = checkSeq(cmd.Sequence); wireErr != nil {
c.log.Errorf("MessageACK sequence unexpected: %v", cmd.Sequence)
return
}
nrResps++
if c.c.cfg.OnACKFn != nil {
cbWg.Add(1)
go func() {
defer cbWg.Done()
if err := c.c.cfg.OnACKFn(&cmd.ID, cmd.Payload); err != nil {
c.log.Debugf("Caller failed to handle MessageACK: %v", err)
forceCloseConn(err)
}
}()
}
seq++
case *commands.Consensus:
if consensusCtx != nil {
c.log.Debugf("Received Consensus: ErrorCode: %v, Payload %v bytes", cmd.ErrorCode, len(cmd.Payload))
consensusCtx.replyCh <- cmd
consensusCtx = nil
} else {
// Spurious Consensus replies are a protocol violation.
c.log.Errorf("Received spurious Consensus.")
wireErr = newProtocolError("received spurious Consensus")
return
}
default:
c.log.Errorf("Received unexpected command: %T", cmd)
wireErr = newProtocolError("received unknown command: %T", cmd)
return
}
}
}
func (c *connection) IsPeerValid(creds *wire.PeerCredentials) bool {
// Refresh the cached Provider descriptor.
if err := c.getDescriptor(); err != nil {
return false
}
if !bytes.Equal(c.descriptor.IdentityKey.Bytes(), creds.AdditionalData) {
return false
}
if !c.descriptor.LinkKey.Equal(creds.PublicKey) {
return false
}
return true
}
func (c *connection) onConnStatusChange(err error) {
c.Lock()
if err == nil {
c.isConnected = true
} else {
c.isConnected = false
// Force drain the channels used to poke the loop.
select {
case ctx := <-c.sendCh:
ctx.doneFn(ErrNotConnected)
default:
}
select {
case ctx := <-c.getConsensusCh:
ctx.doneFn(ErrNotConnected)
default:
}
select {
case <-c.fetchCh:
default:
}
}
c.Unlock()
if c.c.cfg.OnConnFn != nil {
c.c.cfg.OnConnFn(err)
}
}
func (c *connection) sendPacket(pkt []byte) error {
c.Lock()
if !c.isConnected {
c.Unlock()
return ErrNotConnected
}
errCh := make(chan error)
c.sendCh <- &connSendCtx{
pkt: pkt,
doneFn: func(err error) {
errCh <- err
},
}
c.log.Debugf("Enqueued packet for send.")
// Release the lock so this won't deadlock in onConnStatusChange.
c.Unlock()
return <-errCh
}
func (c *connection) getConsensus(ctx context.Context, epoch uint64) (*commands.Consensus, error) {
c.Lock()
if !c.isConnected {
c.Unlock()
return nil, ErrNotConnected
}
errCh := make(chan error)
replyCh := make(chan interface{})
c.getConsensusCh <- &getConsensusCtx{
replyCh: replyCh,
epoch: epoch,
doneFn: func(err error) {
errCh <- err
},
}
c.log.Debug("Enqueued GetConsensus command for send.")
// Release the lock so this won't deadlock in onConnStatusChange.
c.Unlock()
// Ensure the dispatch succeeded.
err := <-errCh
if err != nil {
c.log.Debugf("Failed to dispatch GetConsensus: %v", err)
return nil, err
}
// Wait for the dispatch to complete.
select {
case rawResp := <-replyCh:
switch resp := rawResp.(type) {
case error:
return nil, resp
case *commands.Consensus:
return resp, nil
default:
panic("BUG: Worker returned invalid Consensus response")
}
case <-ctx.Done():
// Canceled mid-fetch.
return nil, errGetConsensusCanceled
}
// NOTREACHED
}
func (c *connection) start() {
c.Go(c.connectWorker)
}
func newConnection(c *Client) *connection {
k := new(connection)
k.c = c
k.log = c.cfg.LogBackend.GetLogger("minclient/conn:" + c.displayName)
k.pkiFetchCh = make(chan interface{}, 1)
k.fetchCh = make(chan interface{}, 1)
k.sendCh = make(chan *connSendCtx)
k.getConsensusCh = make(chan *getConsensusCtx)
return k
}
func init() {
if WarpedEpoch == "true" {
keepAliveInterval = 30 * time.Second
connectTimeout = 10 * time.Second
pkiFallbackInterval = 30 * time.Second
}
}