-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
keybase_daemon_rpc.go
486 lines (407 loc) · 13.5 KB
/
keybase_daemon_rpc.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
// Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"os"
"runtime"
"sync"
"time"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/go-framed-msgpack-rpc/rpc"
"golang.org/x/net/context"
)
// KeybaseDaemonRPC implements the KeybaseService interface using RPC
// calls.
type KeybaseDaemonRPC struct {
*KeybaseServiceBase
daemonLog logger.Logger
// Only used when there's a real connection (i.e., not in
// testing).
shutdownFn func()
keepAliveCancel context.CancelFunc
// protocols (additional to required protocols) to register on server connect
lock sync.RWMutex
protocols []rpc.Protocol
// server is set in OnConnect. If this is non-nil, subsequent AddProtocol
// calls triggers a server.Register.
server *rpc.Server
notifyService keybase1.NotifyServiceInterface
rawClient rpc.GenericClient
}
var _ keybase1.NotifySessionInterface = (*KeybaseDaemonRPC)(nil)
var _ keybase1.NotifyKeyfamilyInterface = (*KeybaseDaemonRPC)(nil)
var _ keybase1.NotifyPaperKeyInterface = (*KeybaseDaemonRPC)(nil)
var _ keybase1.NotifyFSRequestInterface = (*KeybaseDaemonRPC)(nil)
var _ keybase1.NotifyTeamInterface = (*KeybaseDaemonRPC)(nil)
var _ rpc.ConnectionHandler = (*KeybaseDaemonRPC)(nil)
var _ KeybaseService = (*KeybaseDaemonRPC)(nil)
var _ keybase1.ImplicitTeamMigrationInterface = (*KeybaseDaemonRPC)(nil)
func (k *KeybaseDaemonRPC) addKBFSProtocols() {
// Protocols that KBFS requires
protocols := []rpc.Protocol{
keybase1.LogUiProtocol(daemonLogUI{k.daemonLog}),
keybase1.IdentifyUiProtocol(daemonIdentifyUI{k.daemonLog}),
keybase1.NotifySessionProtocol(k),
keybase1.NotifyKeyfamilyProtocol(k),
keybase1.NotifyPaperKeyProtocol(k),
keybase1.NotifyFSRequestProtocol(k),
keybase1.NotifyTeamProtocol(k),
keybase1.NotifyFavoritesProtocol(k),
keybase1.TlfKeysProtocol(k),
keybase1.ReachabilityProtocol(k),
keybase1.ImplicitTeamMigrationProtocol(k),
}
if k.notifyService != nil {
k.log.Warning("adding NotifyService protocol")
protocols = append(protocols, keybase1.NotifyServiceProtocol(k.notifyService))
}
k.AddProtocols(protocols)
}
// NewKeybaseDaemonRPC makes a new KeybaseDaemonRPC that makes RPC
// calls using the socket of the given Keybase context.
func NewKeybaseDaemonRPC(config Config, kbCtx Context, log logger.Logger,
debug bool, additionalProtocols []rpc.Protocol) *KeybaseDaemonRPC {
k := newKeybaseDaemonRPC(config, kbCtx, log)
k.config = config
k.daemonLog = logger.New("daemon")
if debug {
k.daemonLog.Configure("", true, "")
}
conn := NewSharedKeybaseConnection(kbCtx, config, k)
k.fillClients(conn.GetClient())
k.shutdownFn = conn.Shutdown
if config.Mode().ServiceKeepaliveEnabled() {
ctx, cancel := context.WithCancel(context.Background())
k.keepAliveCancel = cancel
go k.keepAliveLoop(ctx)
}
k.notifyService = newNotifyServiceHandler(config, log)
k.addKBFSProtocols()
k.AddProtocols(additionalProtocols)
return k
}
// For testing.
func newKeybaseDaemonRPCWithClient(kbCtx Context, client rpc.GenericClient,
log logger.Logger) *KeybaseDaemonRPC {
k := newKeybaseDaemonRPC(nil, kbCtx, log)
k.fillClients(client)
// No need for a keepalive loop in this case, since this is only
// used during testing.
return k
}
func newKeybaseDaemonRPC(config Config, kbCtx Context, log logger.Logger) *KeybaseDaemonRPC {
serviceBase := NewKeybaseServiceBase(config, kbCtx, log)
if serviceBase == nil {
return nil
}
k := KeybaseDaemonRPC{
KeybaseServiceBase: serviceBase,
}
return &k
}
func (k *KeybaseDaemonRPC) fillClients(client rpc.GenericClient) {
k.FillClients(keybase1.IdentifyClient{Cli: client},
keybase1.UserClient{Cli: client},
keybase1.TeamsClient{Cli: client},
keybase1.MerkleClient{Cli: client},
keybase1.SessionClient{Cli: client},
keybase1.FavoriteClient{Cli: client},
keybase1.KbfsClient{Cli: client},
keybase1.KbfsMountClient{Cli: client},
keybase1.GitClient{Cli: client},
keybase1.KvstoreClient{Cli: client},
)
k.rawClient = client
}
type daemonLogUI struct {
log logger.Logger
}
var _ keybase1.LogUiInterface = daemonLogUI{}
func (l daemonLogUI) Log(ctx context.Context, arg keybase1.LogArg) error {
format := "%s"
// arg.Text.Markup should always be false, so ignore it.
s := arg.Text.Data
switch arg.Level {
case keybase1.LogLevel_DEBUG:
l.log.CDebugf(ctx, format, s)
case keybase1.LogLevel_INFO:
l.log.CInfof(ctx, format, s)
case keybase1.LogLevel_WARN:
l.log.CWarningf(ctx, format, s)
case keybase1.LogLevel_ERROR:
l.log.CErrorf(ctx, format, s)
case keybase1.LogLevel_NOTICE:
l.log.CNoticef(ctx, format, s)
case keybase1.LogLevel_CRITICAL:
l.log.CCriticalf(ctx, format, s)
default:
l.log.CWarningf(ctx, format, s)
}
return nil
}
type daemonIdentifyUI struct {
log logger.Logger
}
var _ keybase1.IdentifyUiInterface = daemonIdentifyUI{}
func (d daemonIdentifyUI) DelegateIdentifyUI(ctx context.Context) (int, error) {
d.log.CDebugf(ctx, "DelegateIdentifyUI() (returning 0, UIDelegationUnavailableError{}")
return 0, libkb.UIDelegationUnavailableError{}
}
func (d daemonIdentifyUI) Start(ctx context.Context, arg keybase1.StartArg) error {
d.log.CDebugf(ctx, "Start(%+v)", arg)
return nil
}
func (d daemonIdentifyUI) DisplayKey(ctx context.Context, arg keybase1.DisplayKeyArg) error {
d.log.CDebugf(ctx, "DisplayKey(%+v)", arg)
return nil
}
func (d daemonIdentifyUI) ReportLastTrack(ctx context.Context, arg keybase1.ReportLastTrackArg) error {
d.log.CDebugf(ctx, "ReportLastTrack(%+v)", arg)
return nil
}
func (d daemonIdentifyUI) LaunchNetworkChecks(ctx context.Context, arg keybase1.LaunchNetworkChecksArg) error {
d.log.CDebugf(ctx, "LaunchNetworkChecks(%+v)", arg)
return nil
}
func (d daemonIdentifyUI) DisplayTrackStatement(ctx context.Context, arg keybase1.DisplayTrackStatementArg) error {
d.log.CDebugf(ctx, "DisplayTrackStatement(%+v)", arg)
return nil
}
func (d daemonIdentifyUI) FinishWebProofCheck(ctx context.Context, arg keybase1.FinishWebProofCheckArg) error {
d.log.CDebugf(ctx, "FinishWebProofCheck(%+v)", arg)
return nil
}
func (d daemonIdentifyUI) FinishSocialProofCheck(ctx context.Context, arg keybase1.FinishSocialProofCheckArg) error {
d.log.CDebugf(ctx, "FinishSocialProofCheck(%+v)", arg)
return nil
}
func (d daemonIdentifyUI) DisplayCryptocurrency(ctx context.Context, arg keybase1.DisplayCryptocurrencyArg) error {
d.log.CDebugf(ctx, "DisplayCryptocurrency(%+v)", arg)
return nil
}
func (d daemonIdentifyUI) DisplayStellarAccount(ctx context.Context, arg keybase1.DisplayStellarAccountArg) error {
d.log.CDebugf(ctx, "DisplayStellarAccount(%+v)", arg)
return nil
}
func (d daemonIdentifyUI) ReportTrackToken(ctx context.Context, arg keybase1.ReportTrackTokenArg) error {
d.log.CDebugf(ctx, "ReportTrackToken(%+v)", arg)
return nil
}
func (d daemonIdentifyUI) DisplayUserCard(ctx context.Context, arg keybase1.DisplayUserCardArg) error {
d.log.CDebugf(ctx, "DisplayUserCard(%+v)", arg)
return nil
}
func (d daemonIdentifyUI) Confirm(ctx context.Context, arg keybase1.ConfirmArg) (keybase1.ConfirmResult, error) {
d.log.CDebugf(ctx, "Confirm(%+v) (returning false)", arg)
return keybase1.ConfirmResult{
IdentityConfirmed: false,
RemoteConfirmed: false,
}, nil
}
func (d daemonIdentifyUI) DisplayTLFCreateWithInvite(ctx context.Context,
arg keybase1.DisplayTLFCreateWithInviteArg) (err error) {
return nil
}
func (d daemonIdentifyUI) Dismiss(ctx context.Context,
_ keybase1.DismissArg) error {
return nil
}
func (d daemonIdentifyUI) Cancel(ctx context.Context, sessionID int) error {
d.log.CDebugf(ctx, "Cancel(%d)", sessionID)
return nil
}
func (d daemonIdentifyUI) Finish(ctx context.Context, sessionID int) error {
d.log.CDebugf(ctx, "Finish(%d)", sessionID)
return nil
}
// HandlerName implements the ConnectionHandler interface.
func (*KeybaseDaemonRPC) HandlerName() string {
return "KeybaseDaemonRPC"
}
func (k *KeybaseDaemonRPC) registerProtocol(server *rpc.Server, p rpc.Protocol) error {
k.log.Debug("registering protocol %q", p.Name)
err := server.Register(p)
switch err.(type) {
case nil, rpc.AlreadyRegisteredError:
return nil
default:
k.log.Warning("register protocol %q error", p.Name)
return err
}
}
// AddProtocols adds protocols that are registered on server connect
func (k *KeybaseDaemonRPC) AddProtocols(protocols []rpc.Protocol) {
if protocols == nil {
return
}
k.lock.Lock()
defer k.lock.Unlock()
if k.protocols != nil {
k.protocols = append(k.protocols, protocols...)
} else {
k.protocols = protocols
}
// If we are already connected, register these protocols.
if k.server != nil {
for _, p := range protocols {
err := k.registerProtocol(k.server, p)
if err != nil {
k.log.Debug("Couldn't register protocol: %+v", err)
}
}
}
}
// OnConnect implements the ConnectionHandler interface.
func (k *KeybaseDaemonRPC) OnConnect(ctx context.Context,
conn *rpc.Connection, rawClient rpc.GenericClient,
server *rpc.Server) (err error) {
k.lock.Lock()
defer k.lock.Unlock()
for _, p := range k.protocols {
if err = k.registerProtocol(server, p); err != nil {
return err
}
}
// Using conn.GetClient() here would cause problematic
// recursion.
c := keybase1.NotifyCtlClient{Cli: rawClient}
err = c.SetNotifications(ctx, keybase1.NotificationChannels{
Session: true,
Paperkeys: true,
Keyfamily: true,
Kbfsrequest: true,
Reachability: true,
Service: true,
Team: true,
Chatkbfsedits: true,
Favorites: true,
})
if err != nil {
return err
}
// Introduce ourselves. TODO: move this to SharedKeybaseConnection
// somehow?
configClient := keybase1.ConfigClient{Cli: rawClient}
err = configClient.HelloIAm(ctx, keybase1.ClientDetails{
Pid: os.Getpid(),
ClientType: k.config.Mode().ClientType(),
Argv: os.Args,
Version: VersionString(),
})
if err != nil {
return err
}
// Set k.server only if err == nil.
k.server = server
return nil
}
// OnConnectError implements the ConnectionHandler interface.
func (k *KeybaseDaemonRPC) OnConnectError(err error, wait time.Duration) {
k.log.Warning("KeybaseDaemonRPC: connection error: %q; retrying in %s",
err, wait)
}
// OnDoCommandError implements the ConnectionHandler interface.
func (k *KeybaseDaemonRPC) OnDoCommandError(err error, wait time.Duration) {
k.log.Warning("KeybaseDaemonRPC: docommand error: %q; retrying in %s",
err, wait)
}
// OnDisconnected implements the ConnectionHandler interface.
func (k *KeybaseDaemonRPC) OnDisconnected(ctx context.Context,
status rpc.DisconnectStatus) {
if status == rpc.StartingNonFirstConnection {
k.log.Warning("KeybaseDaemonRPC is disconnected")
}
k.ClearCaches(ctx)
k.lock.Lock()
defer k.lock.Unlock()
k.server = nil
}
// ShouldRetry implements the ConnectionHandler interface.
func (k *KeybaseDaemonRPC) ShouldRetry(rpcName string, err error) bool {
return false
}
// ShouldRetryOnConnect implements the ConnectionHandler interface.
func (k *KeybaseDaemonRPC) ShouldRetryOnConnect(err error) bool {
_, inputCanceled := err.(libkb.InputCanceledError)
return !inputCanceled
}
func (k *KeybaseDaemonRPC) sendPing(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
defer cancel()
err := k.sessionClient.SessionPing(ctx)
if err != nil {
k.log.CWarningf(
ctx, "Background keep alive hit an error: %v", err)
}
}
func (k *KeybaseDaemonRPC) keepAliveLoop(ctx context.Context) {
// If the connection is dropped, we need to re-connect and send
// another HelloIAm message. However, we can't actually detect
// when the connection is closed until KBFS makes another outgoing
// RPC, which might not happen for a while. So continuously send
// a cheap RPC in the background, so that OnConnect will get
// called as soon as the connection comes back.
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if k.sessionClient == nil {
// Clients haven't been filled yet.
continue
}
k.sendPing(ctx)
}
}
}
// Shutdown implements the KeybaseService interface for KeybaseDaemonRPC.
func (k *KeybaseDaemonRPC) Shutdown() {
if k.shutdownFn != nil {
k.shutdownFn()
}
if k.keepAliveCancel != nil {
k.keepAliveCancel()
}
k.log.Warning("Keybase service shutdown")
}
// notifyServiceHandler implements keybase1.NotifyServiceInterface
type notifyServiceHandler struct {
config Config
log logger.Logger
}
func (s *notifyServiceHandler) Shutdown(_ context.Context, code int) error {
s.log.Warning("NotifyService: Shutdown")
if runtime.GOOS == "windows" {
os.Exit(code)
}
return nil
}
func (s *notifyServiceHandler) HTTPSrvInfoUpdate(_ context.Context, info keybase1.HttpSrvInfo) error {
return nil
}
func (s *notifyServiceHandler) HandleKeybaseLink(_ context.Context, _ keybase1.HandleKeybaseLinkArg) error {
return nil
}
// newNotifyServiceHandler makes a new NotifyServiceHandler
func newNotifyServiceHandler(config Config, log logger.Logger) keybase1.NotifyServiceInterface {
s := ¬ifyServiceHandler{config: config, log: log}
return s
}
// FavoritesChanged implements keybase1.NotifyFavoritesClient
func (k *KeybaseDaemonRPC) FavoritesChanged(ctx context.Context,
uid keybase1.UID) error {
k.log.Debug("Received FavoritesChanged RPC.")
k.config.KBFSOps().RefreshCachedFavorites(ctx,
FavoritesRefreshModeInMainFavoritesLoop)
return nil
}
// GetKeybaseDaemonRawClient implements the KeybaseService interface for
// KeybaseServiceBase.
func (k *KeybaseDaemonRPC) GetKeybaseDaemonRawClient() rpc.GenericClient {
return k.rawClient
}