This repository has been archived by the owner on Jul 7, 2020. It is now read-only.
forked from keybase/client
/
gregor.go
1925 lines (1650 loc) · 58 KB
/
gregor.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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package service
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"net"
"net/url"
"sync"
"time"
"golang.org/x/net/context"
"github.com/keybase/backoff"
"github.com/keybase/client/go/badges"
"github.com/keybase/client/go/chat"
"github.com/keybase/client/go/chat/globals"
chatstorage "github.com/keybase/client/go/chat/storage"
"github.com/keybase/client/go/chat/utils"
"github.com/keybase/client/go/engine"
"github.com/keybase/client/go/gregor"
grclient "github.com/keybase/client/go/gregor/client"
"github.com/keybase/client/go/gregor/storage"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/chat1"
"github.com/keybase/client/go/protocol/gregor1"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/clockwork"
"github.com/keybase/go-framed-msgpack-rpc/rpc"
jsonw "github.com/keybase/go-jsonw"
)
const GregorRequestTimeout time.Duration = 30 * time.Second
const GregorConnectionShortRetryInterval time.Duration = 2 * time.Second
const GregorConnectionLongRetryInterval time.Duration = 10 * time.Second
const GregorGetClientTimeout time.Duration = 4 * time.Second
const slowConnSleepTime = 1 * time.Second
type IdentifyUIHandler struct {
libkb.Contextified
connID libkb.ConnectionID
alwaysAlive bool
}
var _ libkb.GregorInBandMessageHandler = (*IdentifyUIHandler)(nil)
func NewIdentifyUIHandler(g *libkb.GlobalContext, connID libkb.ConnectionID) IdentifyUIHandler {
return IdentifyUIHandler{
Contextified: libkb.NewContextified(g),
connID: connID,
alwaysAlive: false,
}
}
func (h IdentifyUIHandler) IsAlive() bool {
return (h.alwaysAlive || h.G().ConnectionManager.LookupConnection(h.connID) != nil)
}
func (h IdentifyUIHandler) Name() string {
return "IdentifyUIHandler"
}
func (h *IdentifyUIHandler) toggleAlwaysAlive(alive bool) {
h.alwaysAlive = alive
}
type oobmSystemSubscriptions map[string]bool
func newOOBMSystemSubscriptions(oobmSystems []string) oobmSystemSubscriptions {
if oobmSystems == nil {
return nil
}
ret := make(oobmSystemSubscriptions)
for _, system := range oobmSystems {
ret[system] = true
}
return ret
}
type gregorFirehoseHandler struct {
libkb.Contextified
connID libkb.ConnectionID
cli keybase1.GregorUIClient
oobmFilter oobmSystemSubscriptions
}
func newGregorFirehoseHandler(g *libkb.GlobalContext, connID libkb.ConnectionID, xp rpc.Transporter, oobmSystems []string) *gregorFirehoseHandler {
return &gregorFirehoseHandler{
Contextified: libkb.NewContextified(g),
connID: connID,
cli: keybase1.GregorUIClient{Cli: rpc.NewClient(xp, libkb.NewContextifiedErrorUnwrapper(g), nil)},
oobmFilter: newOOBMSystemSubscriptions(oobmSystems),
}
}
func (h *gregorFirehoseHandler) IsAlive() bool {
return h.G().ConnectionManager.LookupConnection(h.connID) != nil
}
func (h *gregorFirehoseHandler) PushState(s gregor1.State, r keybase1.PushReason) {
err := h.cli.PushState(context.Background(), keybase1.PushStateArg{State: s, Reason: r})
if err != nil {
h.G().Log.Error(fmt.Sprintf("Error in firehose push state: %s", err))
}
}
func (h *gregorFirehoseHandler) filterOOBMs(v []gregor1.OutOfBandMessage) []gregor1.OutOfBandMessage {
// Filter OOBMs down to wanted systems if we have a filter installed
if h.oobmFilter == nil {
return v
}
var tmp []gregor1.OutOfBandMessage
for _, m := range v {
if h.oobmFilter[m.System().String()] {
tmp = append(tmp, m)
}
}
return tmp
}
func (h *gregorFirehoseHandler) PushOutOfBandMessages(v []gregor1.OutOfBandMessage) {
nOrig := len(v)
// Filter OOBMs down to wanted systems if we have a filter installed
v = h.filterOOBMs(v)
h.G().Log.Debug("gregorFirehoseHandler#PushOutOfBandMessages: %d message(s) (%d before filter)", len(v), nOrig)
if len(v) == 0 {
return
}
err := h.cli.PushOutOfBandMessages(context.Background(), v)
if err != nil {
h.G().Log.Error(fmt.Sprintf("Error in firehose push out-of-band messages: %s", err))
}
}
type testingReplayRes struct {
replayed []gregor.InBandMessage
err error
}
type testingEvents struct {
broadcastSentCh chan error
replayThreadCh chan testingReplayRes
}
func newTestingEvents() *testingEvents {
return &testingEvents{
broadcastSentCh: make(chan error),
replayThreadCh: make(chan testingReplayRes, 10),
}
}
type connectionAuthError struct {
msg string
shouldRetry bool
}
func newConnectionAuthError(msg string, shouldRetry bool) connectionAuthError {
return connectionAuthError{
msg: msg,
shouldRetry: shouldRetry,
}
}
func (c connectionAuthError) ShouldRetry() bool {
return c.shouldRetry
}
func (c connectionAuthError) Error() string {
return fmt.Sprintf("connection auth error: msg: %s shouldRetry: %v", c.msg, c.shouldRetry)
}
type replayThreadArg struct {
cli gregor1.IncomingInterface
t time.Time
ctx context.Context
}
type gregorHandler struct {
globals.Contextified
// This lock is to protect ibmHandlers and gregorCli and firehoseHandlers. Only public methods
// should grab it.
sync.Mutex
ibmHandlers []libkb.GregorInBandMessageHandler
// gregorCliMu just protecs the gregorCli pointer, since it can be swapped out
// in one goroutine and accessed in another.
gregorCliMu sync.Mutex
gregorCli *grclient.Client
firehoseHandlers []libkb.GregorFirehoseHandler
badger *badges.Badger
reachability *reachability
chatLog utils.DebugLabeler
// This mutex protects the con object
connMutex sync.Mutex
conn *rpc.Connection
uri *rpc.FMPURI
// connectHappened will be closed after gregor connection established
connectHappened chan struct{}
cli rpc.GenericClient
pingCli rpc.GenericClient
sessionID gregor1.SessionID
firstConnect bool
forceSessionCheck bool
// Function for determining if a new BroadcastMessage should trigger
// a pushState call to firehose handlers
pushStateFilter func(m gregor.Message) bool
shutdownCh chan struct{}
broadcastCh chan gregor1.Message
replayCh chan replayThreadArg
// Testing
testingEvents *testingEvents
transportForTesting *connTransport
}
var _ libkb.GregorDismisser = (*gregorHandler)(nil)
var _ libkb.GregorListener = (*gregorHandler)(nil)
func newGregorHandler(g *globals.Context) *gregorHandler {
gh := &gregorHandler{
Contextified: globals.NewContextified(g),
chatLog: utils.NewDebugLabeler(g.GetLog(), "PushHandler", false),
firstConnect: true,
pushStateFilter: func(m gregor.Message) bool { return true },
badger: nil,
broadcastCh: make(chan gregor1.Message, 10000),
forceSessionCheck: false,
connectHappened: make(chan struct{}),
replayCh: make(chan replayThreadArg, 10),
}
return gh
}
// Init starts all the background services for managing connection to Gregor
func (g *gregorHandler) Init() {
// Attempt to create a gregor client initially, if we are not logged in
// or don't have user/device info in G, then this won't work
if err := g.resetGregorClient(context.TODO()); err != nil {
g.Warning(context.Background(), "unable to create push service client: %s", err.Error())
}
// Start broadcast handler goroutine
go g.broadcastMessageHandler()
// Start the app state monitor thread
go g.monitorAppState()
// Start replay thread
go g.syncReplayThread()
}
func (g *gregorHandler) monitorAppState() {
// Wait for state updates and react accordingly
state := keybase1.AppState_FOREGROUND
for {
state = <-g.G().AppState.NextUpdate(&state)
switch state {
case keybase1.AppState_BACKGROUNDACTIVE:
fallthrough
case keybase1.AppState_FOREGROUND:
// Make sure the URI is set before attempting this (possible it isn't in a race)
if g.uri != nil {
g.chatLog.Debug(context.Background(), "foregrounded, reconnecting")
if err := g.Connect(g.uri); err != nil {
g.chatLog.Debug(context.Background(), "error reconnecting")
}
}
case keybase1.AppState_INACTIVE, keybase1.AppState_BACKGROUND:
g.chatLog.Debug(context.Background(), "backgrounded, shutting down connection")
g.Shutdown()
}
}
}
func (g *gregorHandler) GetURI() *rpc.FMPURI {
return g.uri
}
func (g *gregorHandler) GetIncomingClient() gregor1.IncomingInterface {
if g.IsShutdown() || g.cli == nil {
return gregor1.IncomingClient{Cli: chat.OfflineClient{}}
}
return gregor1.IncomingClient{Cli: g.cli}
}
func (g *gregorHandler) GetClient() chat1.RemoteInterface {
if g.IsShutdown() || g.cli == nil {
select {
case <-g.connectHappened:
if g.IsShutdown() || g.cli == nil {
g.chatLog.Debug(context.Background(), "GetClient: connectHappened, but still shutdown, using OfflineClient for chat1.RemoteClient")
return chat1.RemoteClient{Cli: chat.OfflineClient{}}
}
g.chatLog.Debug(context.Background(), "GetClient: successfully waited for connection")
return chat1.RemoteClient{Cli: chat.NewRemoteClient(g.G(), g.cli)}
case <-time.After(GregorGetClientTimeout):
g.chatLog.Debug(context.Background(), "GetClient: shutdown, using OfflineClient for chat1.RemoteClient (waited %s for connectHappened)", GregorGetClientTimeout)
return chat1.RemoteClient{Cli: chat.OfflineClient{}}
}
}
g.chatLog.Debug(context.Background(), "GetClient: not shutdown, making new remote client")
return chat1.RemoteClient{Cli: chat.NewRemoteClient(g.G(), g.cli)}
}
func (g *gregorHandler) resetGregorClient(ctx context.Context) (err error) {
defer g.G().Trace("gregorHandler#newGregorClient", func() error { return err })()
of := gregor1.ObjFactory{}
var guid gregor.UID
var gdid gregor.DeviceID
var b []byte
uid := g.G().Env.GetUID()
if !uid.Exists() {
err = errors.New("no UID; probably not logged in")
return err
}
if b = uid.ToBytes(); b == nil {
err = errors.New("Can't convert UID to byte array")
return err
}
if guid, err = of.MakeUID(b); err != nil {
return err
}
did := g.G().Env.GetDeviceID()
if !did.Exists() {
err = errors.New("no device ID; probably not logged in")
return err
}
if b, err = hex.DecodeString(did.String()); err != nil {
return err
}
if gdid, err = of.MakeDeviceID(b); err != nil {
return err
}
// Create client object
gcli := grclient.NewClient(guid, gdid, func() gregor.StateMachine {
return storage.NewMemEngine(of, clockwork.NewRealClock(), g.G().Log)
}, storage.NewLocalDB(g.G().ExternalG()), g.GetIncomingClient, g.G().Log)
// Bring up local state
g.Debug(ctx, "restoring state from leveldb")
if err = gcli.Restore(ctx); err != nil {
// If this fails, we'll keep trying since the server can bail us out
g.Debug(ctx, "restore local state failed: %s", err)
}
g.gregorCliMu.Lock()
gcliOld := g.gregorCli
g.gregorCli = gcli
g.gregorCliMu.Unlock()
if gcliOld != nil {
gcliOld.Stop()
}
return nil
}
func (g *gregorHandler) getGregorCli() (*grclient.Client, error) {
if g == nil {
return nil, errors.New("gregorHandler client unset")
}
g.gregorCliMu.Lock()
ret := g.gregorCli
g.gregorCliMu.Unlock()
if ret == nil {
return nil, errors.New("client unset")
}
return ret, nil
}
func (g *gregorHandler) getRPCCli() rpc.GenericClient {
return g.cli
}
func (g *gregorHandler) Debug(ctx context.Context, s string, args ...interface{}) {
g.G().Log.CloneWithAddedDepth(1).CDebugf(ctx, "PushHandler: "+s, args...)
}
func (g *gregorHandler) Warning(ctx context.Context, s string, args ...interface{}) {
g.G().Log.CloneWithAddedDepth(1).CWarningf(ctx, "PushHandler: "+s, args...)
}
func (g *gregorHandler) Errorf(ctx context.Context, s string, args ...interface{}) {
g.G().Log.CloneWithAddedDepth(1).CErrorf(ctx, "PushHandler: "+s, args...)
}
func (g *gregorHandler) SetPushStateFilter(f func(m gregor.Message) bool) {
g.pushStateFilter = f
}
func (g *gregorHandler) setReachability(r *reachability) {
g.reachability = r
}
func (g *gregorHandler) Connect(uri *rpc.FMPURI) (err error) {
defer g.G().Trace("gregorHandler#Connect", func() error { return err })()
g.connMutex.Lock()
defer g.connMutex.Unlock()
defer func() {
close(g.connectHappened)
g.connectHappened = make(chan struct{})
}()
// Create client interface to gregord; the user needs to be logged in for this
// to work
if err = g.resetGregorClient(context.TODO()); err != nil {
return err
}
// In case we need to interrupt auth'ing or the ping loop,
// set up this channel.
g.shutdownCh = make(chan struct{})
g.uri = uri
if uri.UseTLS() {
err = g.connectTLS()
} else {
err = g.connectNoTLS()
}
return err
}
func (g *gregorHandler) HandlerName() string {
return "gregor"
}
// PushHandler adds a new ibm handler to our list. This is usually triggered
// when an external entity (like Electron) connects to the service, and we can
// safely send Gregor information to it
func (g *gregorHandler) PushHandler(handler libkb.GregorInBandMessageHandler) {
defer g.chatLog.Trace(context.Background(), func() error { return nil }, "PushHandler")()
g.G().Log.Debug("pushing inband handler %s to position %d", handler.Name(), len(g.ibmHandlers))
g.Lock()
g.ibmHandlers = append(g.ibmHandlers, handler)
g.Unlock()
// Only try replaying if we are logged in, it's possible that a handler can
// attach before that is true (like if we start the service logged out and
// Electron connects)
if g.IsConnected() {
if _, err := g.replayInBandMessages(context.TODO(), gregor1.IncomingClient{Cli: g.cli},
time.Time{}, handler); err != nil {
g.Errorf(context.Background(), "replayInBandMessages on PushHandler failed: %s", err)
}
if g.badger != nil {
s, err := g.getState(context.Background())
if err != nil {
g.Warning(context.Background(), "Cannot get state in PushHandler: %s", err)
return
}
g.badger.PushState(s)
}
}
}
// PushFirehoseHandler pushes a new firehose handler onto the list of currently
// active firehose handles. We can have several of these active at once. All
// get the "firehose" of gregor events. They're removed lazily as their underlying
// connections die.
func (g *gregorHandler) PushFirehoseHandler(handler libkb.GregorFirehoseHandler) {
defer g.chatLog.Trace(context.Background(), func() error { return nil }, "PushFirehoseHandler")()
g.Lock()
g.firehoseHandlers = append(g.firehoseHandlers, handler)
g.Unlock()
s, err := g.getState(context.Background())
if err != nil {
g.Warning(context.Background(), "Cannot push state in firehose handler: %s", err)
return
}
g.Debug(context.Background(), "PushFirehoseHandler: pushing state with %d items", len(s.Items_))
handler.PushState(s, keybase1.PushReason_RECONNECTED)
}
// iterateOverFirehoseHandlers applies the function f to all live firehose handlers
// and then resets the list to only include the live ones.
func (g *gregorHandler) iterateOverFirehoseHandlers(f func(h libkb.GregorFirehoseHandler)) {
var freshHandlers []libkb.GregorFirehoseHandler
for _, h := range g.firehoseHandlers {
if h.IsAlive() {
f(h)
freshHandlers = append(freshHandlers, h)
}
}
g.firehoseHandlers = freshHandlers
return
}
func (g *gregorHandler) pushState(r keybase1.PushReason) {
s, err := g.getState(context.Background())
if err != nil {
g.Warning(context.Background(), "Cannot push state in firehose handler: %s", err)
return
}
g.iterateOverFirehoseHandlers(func(h libkb.GregorFirehoseHandler) {
g.Debug(context.Background(), "pushState: pushing state with %d items", len(s.Items_))
h.PushState(s, r)
})
// Only send this state update on reception of new data, not a reconnect since we will
// be sending that on a different code path altogether (see OnConnect).
if g.badger != nil && r != keybase1.PushReason_RECONNECTED {
g.badger.PushState(s)
}
}
func (g *gregorHandler) pushOutOfBandMessages(m []gregor1.OutOfBandMessage) {
g.iterateOverFirehoseHandlers(func(h libkb.GregorFirehoseHandler) { h.PushOutOfBandMessages(m) })
}
// replayInBandMessages will replay all the messages in the current state from
// the given time. If a handler is specified, it will only replay using it,
// otherwise it will try all of them. gregorHandler needs to be locked when calling
// this function.
func (g *gregorHandler) replayInBandMessages(ctx context.Context, cli gregor1.IncomingInterface,
t time.Time, handler libkb.GregorInBandMessageHandler) ([]gregor.InBandMessage, error) {
var msgs []gregor.InBandMessage
var err error
gcli, err := g.getGregorCli()
if err != nil {
return nil, err
}
if t.IsZero() {
g.Debug(ctx, "replayInBandMessages: fresh replay: using state items")
state, err := gcli.StateMachineState(ctx, nil, true)
if err != nil {
g.Debug(ctx, "replayInBandMessages: unable to fetch state for replay: %s", err)
return nil, err
}
if msgs, err = gcli.InBandMessagesFromState(state); err != nil {
g.Debug(ctx, "replayInBandMessages: unable to fetch messages from state for replay: %s", err)
return nil, err
}
} else {
g.Debug(ctx, "replayInBandMessages: incremental replay: using ibms since")
if msgs, err = gcli.StateMachineInBandMessagesSince(ctx, t, true); err != nil {
g.Debug(ctx, "replayInBandMessages: unable to fetch messages for replay: %s", err)
return nil, err
}
}
g.Debug(ctx, "replayInBandMessages: replaying %d messages", len(msgs))
for _, msg := range msgs {
g.Debug(ctx, "replayInBandMessages: replaying: %s", msg.Metadata().MsgID())
// If we have a handler, just run it on that, otherwise run it against
// all of the handlers we know about
if handler == nil {
err = g.handleInBandMessage(ctx, cli, msg)
} else {
_, err = g.handleInBandMessageWithHandler(ctx, cli, msg, handler)
}
// If an error happens when replaying, don't kill everything else that
// follows, just make a warning.
if err != nil {
g.Debug(ctx, "replayInBandMessages: failure in message replay: %s", err.Error())
err = nil
}
}
return msgs, nil
}
func (g *gregorHandler) IsShutdown() bool {
g.connMutex.Lock()
defer g.connMutex.Unlock()
return g.conn == nil
}
func (g *gregorHandler) IsConnected() bool {
g.connMutex.Lock()
defer g.connMutex.Unlock()
return g.conn != nil && g.conn.IsConnected()
}
func (g *gregorHandler) syncReplayThread() {
for rarg := range g.replayCh {
var trr testingReplayRes
replayedMsgs, err := g.replayInBandMessages(rarg.ctx, rarg.cli, rarg.t, nil)
if err != nil {
g.Debug(rarg.ctx, "serverSync: replayThread: replay messages failed: %s", err)
trr.err = err
} else {
g.Debug(rarg.ctx, "serverSync: replayThread: replayed %d messages", len(replayedMsgs))
trr.replayed = replayedMsgs
}
if g.testingEvents != nil {
g.testingEvents.replayThreadCh <- trr
}
}
}
// serverSync is called from
// gregord. This can happen either on initial startup, or after a reconnect. Needs
// to be called with gregorHandler locked.
func (g *gregorHandler) serverSync(ctx context.Context,
cli gregor1.IncomingInterface, gcli *grclient.Client, syncRes *chat1.SyncAllNotificationRes) ([]gregor.InBandMessage, error) {
// Get time of the last message we synced (unless this is our first time syncing)
var t time.Time
if !g.firstConnect {
pt := gcli.StateMachineLatestCTime(ctx)
if pt != nil {
t = *pt
}
g.Debug(ctx, "serverSync: starting replay from: %s", t)
} else {
g.Debug(ctx, "serverSync: performing a fresh replay")
}
// Sync down everything from the server
consumedMsgs, err := gcli.Sync(ctx, cli, syncRes)
if err != nil {
g.Debug(ctx, "serverSync: error syncing from the server, reason: %s", err)
return nil, err
}
g.Debug(ctx, "serverSync: consumed %d messages", len(consumedMsgs))
// Schedule replay of in-band messages
g.replayCh <- replayThreadArg{
cli: cli,
t: t,
ctx: chat.BackgroundContext(ctx, g.G()),
}
g.pushState(keybase1.PushReason_RECONNECTED)
return consumedMsgs, nil
}
func (g *gregorHandler) makeReconnectOobm() gregor1.Message {
return gregor1.Message{
Oobm_: &gregor1.OutOfBandMessage{
System_: "internal.reconnect",
},
}
}
func (g *gregorHandler) authParams(ctx context.Context) (uid gregor1.UID, token gregor1.SessionToken, nist *libkb.NIST, err error) {
var res loggedInRes
var stoken string
var kuid keybase1.UID
if kuid, stoken, nist, res = g.loggedIn(ctx); res != loggedInYes {
return uid, token, nil,
newConnectionAuthError("failed to check logged in status", res == loggedInMaybe)
}
return kuid.ToBytes(), gregor1.SessionToken(stoken), nist, nil
}
func (g *gregorHandler) inboxParams(ctx context.Context, uid gregor1.UID) chat1.InboxVers {
// Grab current on disk version
ibox := chatstorage.NewInbox(g.G(), uid)
vers, err := ibox.Version(ctx)
if err != nil {
g.chatLog.Debug(ctx, "inboxParams: failed to get current inbox version (using 0): %s",
err.Error())
vers = chat1.InboxVers(0)
}
return vers
}
func (g *gregorHandler) notificationParams(ctx context.Context, gcli *grclient.Client) (t gregor1.Time) {
pt := gcli.StateMachineLatestCTime(ctx)
if pt != nil {
t = gregor1.ToTime(*pt)
}
g.chatLog.Debug(ctx, "notificationParams: latest ctime: %v", t.Time())
return t
}
// OnConnect is called by the rpc library to indicate we have connected to
// gregord
func (g *gregorHandler) OnConnect(ctx context.Context, conn *rpc.Connection,
cli rpc.GenericClient, srv *rpc.Server) (err error) {
defer g.chatLog.Trace(ctx, func() error { return err }, "OnConnect")()
// If we get a random OnConnect on some other connection that is not g.conn, then
// just reject it.
g.connMutex.Lock()
if conn != g.conn {
g.connMutex.Unlock()
g.chatLog.Debug(ctx, "aborting on dup connection")
return chat.ErrDuplicateConnection
}
g.connMutex.Unlock()
g.chatLog.Debug(ctx, "connected")
timeoutCli := WrapGenericClientWithTimeout(cli, GregorRequestTimeout, chat.ErrChatServerTimeout)
chatCli := chat1.RemoteClient{Cli: chat.NewRemoteClient(g.G(), cli)}
if err := srv.Register(gregor1.OutgoingProtocol(g)); err != nil {
return fmt.Errorf("error registering protocol: %s", err.Error())
}
// Grab authentication and sync params
gcli, err := g.getGregorCli()
if err != nil {
return fmt.Errorf("failed to get gregor client: %s", err.Error())
}
uid, token, nist, err := g.authParams(ctx)
if err != nil {
return err
}
iboxVers := g.inboxParams(ctx, uid)
latestCtime := g.notificationParams(ctx, gcli)
// Run SyncAll to both authenticate, and grab all the data we will need to run the
// various resync procedures for chat and notifications
var identBreaks []keybase1.TLFIdentifyFailure
ctx = chat.Context(ctx, g.G(), keybase1.TLFIdentifyBehavior_CHAT_GUI, &identBreaks,
chat.NewCachingIdentifyNotifier(g.G()))
g.chatLog.Debug(ctx, "OnConnect begin")
syncAllRes, err := chatCli.SyncAll(ctx, chat1.SyncAllArg{
Uid: uid,
DeviceID: gcli.Device.(gregor1.DeviceID),
Session: token,
InboxVers: iboxVers,
Ctime: latestCtime,
Fresh: g.firstConnect,
ProtVers: chat1.SyncAllProtVers_V1,
HostName: g.GetURI().Host,
})
if err != nil {
// This will cause us to try and refresh session on the next attempt
if _, ok := err.(libkb.BadSessionError); ok {
g.chatLog.Debug(ctx, "bad session from SyncAll(): forcing session check on next attempt")
g.forceSessionCheck = true
nist.MarkFailure()
}
return fmt.Errorf("error running SyncAll: %s", err)
}
// Use the client parameter instead of conn.GetClient(), since we can get stuck
// in a recursive loop if we keep retrying on reconnect.
if err := g.auth(ctx, timeoutCli, &syncAllRes.Auth); err != nil {
return fmt.Errorf("error authenticating: %s", err)
}
// Sync chat data using a Syncer object
if err := g.G().Syncer.Connected(ctx, chatCli, uid, &syncAllRes.Chat); err != nil {
return fmt.Errorf("error running chat sync: %s", err)
}
// Sync down events since we have been dead
if _, err := g.serverSync(ctx, gregor1.IncomingClient{Cli: timeoutCli}, gcli,
&syncAllRes.Notification); err != nil {
g.chatLog.Debug(ctx, "serverSync: failure: %s", err)
return fmt.Errorf("error running state sync: %s", err)
}
// Sync badge state in the background
if g.badger != nil {
if err := g.badger.Resync(ctx, g.GetClient, gcli, &syncAllRes.Badge); err != nil {
g.chatLog.Debug(ctx, "badger failure: %s", err)
}
}
// Call out to reachability module if we have one
if g.reachability != nil {
g.reachability.setReachability(keybase1.Reachability{
Reachable: keybase1.Reachable_YES,
})
}
// Broadcast reconnect oobm. Spawn this off into a goroutine so that we don't delay
// reconnection any longer than we have to.
go func(m gregor1.Message) {
g.BroadcastMessage(context.Background(), m)
}(g.makeReconnectOobm())
// No longer first connect if we are now connected
g.firstConnect = false
// On successful login we can reset this guy to not force a check
g.forceSessionCheck = false
g.chatLog.Debug(ctx, "OnConnect complete")
return nil
}
func (g *gregorHandler) OnConnectError(err error, reconnectThrottleDuration time.Duration) {
g.chatLog.Debug(context.Background(), "connect error %s, reconnect throttle duration: %s", err, reconnectThrottleDuration)
// Check reachability here to see the nature of our offline status
go func() {
if g.reachability != nil && !g.isReachable() {
g.reachability.setReachability(keybase1.Reachability{
Reachable: keybase1.Reachable_NO,
})
}
}()
}
func (g *gregorHandler) OnDisconnected(ctx context.Context, status rpc.DisconnectStatus) {
g.chatLog.Debug(context.Background(), "disconnected: %v", status)
// Alert chat syncer that we are now disconnected
g.G().Syncer.Disconnected(ctx)
// Call out to reachability module if we have one (and we are currently connected)
go func() {
if g.reachability != nil && status != rpc.StartingFirstConnection && !g.isReachable() {
g.reachability.setReachability(keybase1.Reachability{
Reachable: keybase1.Reachable_NO,
})
}
}()
}
func (g *gregorHandler) OnDoCommandError(err error, nextTime time.Duration) {
g.chatLog.Debug(context.Background(), "do command error: %s, nextTime: %s", err, nextTime)
}
func (g *gregorHandler) ShouldRetry(name string, err error) bool {
g.chatLog.Debug(context.Background(), "should retry: name %s, err %v (returning false)", name, err)
return false
}
func (g *gregorHandler) ShouldRetryOnConnect(err error) bool {
if err == nil {
return false
}
ctx := context.Background()
g.chatLog.Debug(ctx, "should retry on connect, err %v", err)
if err == chat.ErrDuplicateConnection {
g.chatLog.Debug(ctx, "duplicate connection error, not retrying")
return false
}
if _, ok := err.(libkb.BadSessionError); ok {
g.chatLog.Debug(ctx, "bad session error, not retrying")
return false
}
if cerr, ok := err.(connectionAuthError); ok && !cerr.ShouldRetry() {
g.chatLog.Debug(ctx, "should retry on connect, non-retry error, ending: %s", err.Error())
return false
}
return true
}
func (g *gregorHandler) broadcastMessageOnce(ctx context.Context, m gregor1.Message) (err error) {
defer g.chatLog.Trace(ctx, func() error { return err }, "broadcastMessageOnce")()
// Handle the message
var obm gregor.OutOfBandMessage
ibm := m.ToInBandMessage()
if ibm != nil {
gcli, err := g.getGregorCli()
if err != nil {
g.Debug(ctx, "BroadcastMessage: failed to get Gregor client: %s", err.Error())
return err
}
// Check to see if this is already in our state
msgID := ibm.Metadata().MsgID()
state, err := gcli.StateMachineState(ctx, nil, false)
if err != nil {
g.Debug(ctx, "BroadcastMessage: no state machine available: %s", err.Error())
return err
}
if _, ok := state.GetItem(msgID); ok {
g.Debug(ctx, "BroadcastMessage: msgID: %s already in state, ignoring", msgID)
return errors.New("ignored repeat message")
}
g.Debug(ctx, "broadcast: in-band message: msgID: %s Ctime: %s", msgID, ibm.Metadata().CTime())
err = g.handleInBandMessage(ctx, g.GetIncomingClient(), ibm)
// Send message to local state machine
gcli.StateMachineConsumeMessage(ctx, m)
// Forward to electron or whichever UI is listening for the new gregor state
if g.pushStateFilter(m) {
g.pushState(keybase1.PushReason_NEW_DATA)
}
return err
}
obm = m.ToOutOfBandMessage()
if obm != nil {
g.Debug(ctx, "broadcast: out-of-band message: uid: %s",
m.ToOutOfBandMessage().UID())
if err := g.handleOutOfBandMessage(ctx, obm); err != nil {
g.Debug(ctx, "BroadcastMessage: error handling oobm: %s", err.Error())
return err
}
return nil
}
g.Debug(ctx, "BroadcastMessage: both in-band and out-of-band message nil")
return errors.New("invalid message, no ibm or oobm")
}
func (g *gregorHandler) broadcastMessageHandler() {
ctx := context.Background()
for {
m := <-g.broadcastCh
if g.G().GetEnv().GetSlowGregorConn() {
g.Debug(ctx, "[slow conn]: sleeping")
time.Sleep(time.Duration(slowConnSleepTime))
g.Debug(ctx, "[slow conn]: awake")
}
err := g.broadcastMessageOnce(ctx, m)
if err != nil {
g.Debug(context.Background(), "broadcast error: %v", err)
}
// Testing alerts
if g.testingEvents != nil {
g.testingEvents.broadcastSentCh <- err
}
}
}
// BroadcastMessage is called when we receive a new message from gregord. Grabs
// the lock protect the state machine and handleInBandMessage
func (g *gregorHandler) BroadcastMessage(ctx context.Context, m gregor1.Message) error {
// Send the message on a channel so we can return to Gregor as fast as possible. Note
// that this can block, but broadcastCh has a large buffer to try and mitigate
g.broadcastCh <- m
return nil
}
// handleInBandMessage runs a message on all the alive handlers. gregorHandler
// must be locked when calling this function.
func (g *gregorHandler) handleInBandMessage(ctx context.Context, cli gregor1.IncomingInterface,
ibm gregor.InBandMessage) (err error) {
defer g.G().Trace(fmt.Sprintf("gregorHandler#handleInBandMessage with %d handlers", len(g.ibmHandlers)), func() error { return err })()
ctx = libkb.WithLogTag(ctx, "GRGIBM")
var freshHandlers []libkb.GregorInBandMessageHandler
// Loop over all handlers and run the messages against any that are alive
// If the handler is not alive, we prune it from our list
for i, handler := range g.ibmHandlers {
g.Debug(ctx, "trying handler %s at position %d", handler.Name(), i)
if handler.IsAlive() {
if handled, err := g.handleInBandMessageWithHandler(ctx, cli, ibm, handler); err != nil {
if handled {
// Don't stop handling errors on a first failure.
g.Errorf(ctx, "failed to run %s handler: %s", handler.Name(), err)
} else {
g.Debug(ctx, "handleInBandMessage() failed to run %s handler: %s", handler.Name(), err)
}
}
freshHandlers = append(freshHandlers, handler)
} else {
g.Debug(ctx, "skipping handler as it's marked dead: %s", handler.Name())
}
}
if len(g.ibmHandlers) != len(freshHandlers) {
g.Debug(ctx, "Change # of live handlers from %d to %d", len(g.ibmHandlers), len(freshHandlers))
g.ibmHandlers = freshHandlers
}
return nil
}
// handleInBandMessageWithHandler runs a message against the specified handler
func (g *gregorHandler) handleInBandMessageWithHandler(ctx context.Context, cli gregor1.IncomingInterface,
ibm gregor.InBandMessage, handler libkb.GregorInBandMessageHandler) (bool, error) {
g.Debug(ctx, "handleInBand: %+v", ibm)
gcli, err := g.getGregorCli()
if err != nil {
return false, err
}
state, err := gcli.StateMachineState(ctx, nil, false)