/
globals.go
1580 lines (1335 loc) · 47.7 KB
/
globals.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
/// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
//
// globals
//
// All of the global objects in the libkb namespace that are shared
// and mutated across various source files are here. They are
// accessed like `G.Log` or `G.Env`. They're kept
// under the `G` namespace to better keep track of them all.
//
// The globals are built up gradually as the process comes up.
// At first, we only have a logger, but eventually we add
// command-line flags, configuration and environment, and accordingly,
// might actually go back and change the Logger.
package libkb
import (
"errors"
"fmt"
"io"
"log"
"os"
"runtime"
"sync"
"time"
logger "github.com/keybase/client/go/logger"
keybase1 "github.com/keybase/client/go/protocol/keybase1"
clockwork "github.com/keybase/clockwork"
context "golang.org/x/net/context"
)
var IsIPad bool // Set by bind's Init.
type ShutdownHook func(mctx MetaContext) error
type LoginHook interface {
OnLogin(mctx MetaContext) error
}
type LogoutHook interface {
OnLogout(mctx MetaContext) error
}
type DbNukeHook interface {
OnDbNuke(mctx MetaContext) error
}
type GlobalContext struct {
Log logger.Logger // Handles all logging
PerfLog logger.Logger // Handles all performance event logging
VDL *VDebugLog // verbose debug log
GUILogFile *logger.LogFileWriter // GUI logs
Env *Env // Env variables, cmdline args & config
SKBKeyringMu *sync.Mutex // Protects all attempts to mutate the SKBKeyringFile
Keyrings *Keyrings // Gpg Keychains holding keys
perUserKeyringMu *sync.Mutex
perUserKeyring *PerUserKeyring // Keyring holding per user keys
API API // How to make a REST call to the server
Resolver Resolver // cache of resolve results
LocalNetworkInstrumenterStorage *DiskInstrumentationStorage // Instrument Local RPC calls
RemoteNetworkInstrumenterStorage *DiskInstrumentationStorage // Instrument Remote API/RPC calls
LocalDb *JSONLocalDb // Local DB for cache
LocalChatDb *JSONLocalDb // Local DB for cache
MerkleClient MerkleClientInterface // client for querying server's merkle sig tree
XAPI ExternalAPI // for contacting Twitter, Github, etc.
DNSNSFetcher DNSNameServerFetcher // The mobile apps potentially pass an implementor of this interface which is used to grab currently configured DNS name servers
MobileNetState *MobileNetState // The kind of network connection for the currently running instance of the app
MobileAppState *MobileAppState // The state of focus for the currently running instance of the app
DesktopAppState *DesktopAppState // The state of focus for the currently running instance of the app
ChatHelper ChatHelper // conveniently send chat messages
RPCCanceler *RPCCanceler // register live RPCs so they can be cancelleed en masse
IdentifyDispatch *IdentifyDispatch // get notified of identify successes
Identify3State *Identify3State // keep track of Identify3 sessions
vidMu *sync.Mutex // protect VID
RuntimeStats RuntimeStats // performance runtime stats
cacheMu *sync.RWMutex // protects all caches
ProofCache *ProofCache // where to cache proof results
trackCache *TrackCache // cache of IdentifyOutcomes for tracking purposes
identify2Cache Identify2Cacher // cache of Identify2 results for fast-pathing identify2 RPCS
linkCache *LinkCache // cache of ChainLinks
upakLoader UPAKLoader // Load flat users with the ability to hit the cache
teamLoader TeamLoader // Play back teams for id/name properties
fastTeamLoader FastTeamLoader // Play back team in "fast" mode for keys and names only
hiddenTeamChainManager HiddenTeamChainManager
TeamRoleMapManager TeamRoleMapManager
IDLocktab *LockTable
loadUserLockTab *LockTable
teamAuditor TeamAuditor
teamBoxAuditor TeamBoxAuditor
stellar Stellar // Stellar related ops
deviceEKStorage DeviceEKStorage // Store device ephemeral keys
userEKBoxStorage UserEKBoxStorage // Store user ephemeral key boxes
teamEKBoxStorage TeamEKBoxStorage // Store team ephemeral key boxes
teambotEKBoxStorage TeamEKBoxStorage // Store team bot ephemeral key boxes
ekLib EKLib // Wrapper to call ephemeral key methods
teambotBotKeyer TeambotBotKeyer // TeambotKeyer for bot members
teambotMemberKeyer TeambotMemberKeyer // TeambotKeyer for non-bot members
itciCacher LRUer // Cacher for implicit team conflict info
iteamCacher MemLRUer // In memory cacher for implicit teams
cardCache *UserCardCache // cache of keybase1.UserCard objects
fullSelfer FullSelfer // a loader that gets the full self object
pvlSource MerkleStore // a cache and fetcher for pvl
paramProofStore MerkleStore // a cache and fetcher for param proofs
externalURLStore MerkleStore // a cache and fetcher for external urls
PayloadCache *PayloadCache // cache of ChainLink payload json wrappers
kvRevisionCache KVRevisionCacher // cache of revisions for verifying key-value store results
Pegboard *Pegboard
GpgClient *GpgCLI // A standard GPG-client (optional)
ShutdownHooks []ShutdownHook // on shutdown, fire these...
SocketInfo Socket // which socket to bind/connect to
socketWrapperMu *sync.RWMutex
SocketWrapper *SocketWrapper // only need one connection per
LoopbackListener *LoopbackListener // If we're in loopback mode, we'll connect through here
XStreams *ExportedStreams // a table of streams we've exported to the daemon (or vice-versa)
Timers *TimerSet // Which timers are currently configured on
UI UI // Interact with the UI
Service bool // whether we're in server mode
Standalone bool // whether we're launched as standalone command
shutdownOnce *sync.Once // whether we've shut down or not
ConnectionManager *ConnectionManager // keep tabs on all active client connections
NotifyRouter *NotifyRouter // How to route notifications
// How to route UIs. Nil if we're in standalone mode or in
// tests, and non-nil in service mode.
UIRouter UIRouter // How to route UIs
proofServices ExternalServicesCollector // All known external services
UIDMapper UIDMapper // maps from UID to Usernames
ServiceMapper ServiceSummaryMapper // handles and caches batch requests for service summaries
ExitCode keybase1.ExitCode // Value to return to OS on Exit()
RateLimits *RateLimits // tracks the last time certain actions were taken
clockMu *sync.Mutex // protects Clock
clock clockwork.Clock // RealClock unless we're testing
secretStoreMu *sync.Mutex // protects secretStore
secretStore *SecretStoreLocked // SecretStore
hookMu *sync.RWMutex // protects loginHooks, logoutHooks
loginHooks []LoginHook // call these on login
logoutHooks []NamedLogoutHook // call these on logout
dbNukeHooks []NamedDbNukeHook // call these on dbnuke
GregorState GregorState // for dismissing gregor items that we've handled
GregorListener GregorListener // for alerting about clients connecting and registering UI protocols
oodiMu *sync.RWMutex // For manipulating the OutOfDateInfo
outOfDateInfo *keybase1.OutOfDateInfo // Stores out of date messages we got from API server headers.
lastUpgradeWarning *time.Time // When the last upgrade was warned for (to reate-limit nagging)
uchMu *sync.Mutex // protects the UserChangedHandler array
UserChangedHandlers []UserChangedHandler // a list of handlers that deal generically with userchanged events
ConnectivityMonitor ConnectivityMonitor // Detect whether we're connected or not.
localSigchainGuard *LocalSigchainGuard // Non-strict guard for shoeing away bg tasks when the user is doing sigchain actions
FeatureFlags *FeatureFlagSet // user's feature flag set
StandaloneChatConnector StandaloneChatConnector
// Can be overloaded by tests to get an improvement in performance
NewTriplesec func(pw []byte, salt []byte) (Triplesec, error)
// Options specified for testing only
TestOptions GlobalTestOptions
// Interface to get (cryptographically secure) randomness. Makes it easier
// to test randomized behaviors.
random Random
// It is threadsafe to call methods on ActiveDevice which will always be non-nil.
// But don't access its members directly. If you're going to be changing out the
// user (and resetting the ActiveDevice), then you should hold the switchUserMu
switchUserMu *VerboseLock
ActiveDevice *ActiveDevice
switchedUsers map[NormalizedUsername]bool // bookkeep users who have been switched over (and are still in secret store)
// OS Version passed from mobile native code. iOS and Android only.
// See go/bind/keybase.go
MobileOsVersion string
IsIPad bool
SyncedContactList SyncedContactListProvider
GUIConfig *JSONFile
avatarLoader AvatarLoaderSource
TeamMemberCountCache *TeamMemberCountCache
}
type GlobalTestOptions struct {
NoBug3964Repair bool
NoAutorotateOnBoxAuditRetry bool
}
func (g *GlobalContext) GetLog() logger.Logger { return g.Log }
func (g *GlobalContext) GetPerfLog() logger.Logger { return g.PerfLog }
func (g *GlobalContext) GetGUILogWriter() io.Writer { return g.GUILogFile }
func (g *GlobalContext) GetVDebugLog() *VDebugLog { return g.VDL }
func (g *GlobalContext) GetAPI() API { return g.API }
func (g *GlobalContext) GetExternalAPI() ExternalAPI { return g.XAPI }
func (g *GlobalContext) GetServerURI() (string, error) { return g.Env.GetServerURI() }
func (g *GlobalContext) GetEnv() *Env { return g.Env }
func (g *GlobalContext) GetDNSNameServerFetcher() DNSNameServerFetcher { return g.DNSNSFetcher }
func (g *GlobalContext) GetKVStore() KVStorer { return g.LocalDb }
func (g *GlobalContext) GetClock() clockwork.Clock { return g.Clock() }
func (g *GlobalContext) GetEKLib() EKLib { return g.ekLib }
func (g *GlobalContext) GetTeambotBotKeyer() TeambotBotKeyer { return g.teambotBotKeyer }
func (g *GlobalContext) GetTeambotMemberKeyer() TeambotMemberKeyer { return g.teambotMemberKeyer }
func (g *GlobalContext) GetProofServices() ExternalServicesCollector { return g.proofServices }
func (g *GlobalContext) GetAvatarLoader() AvatarLoaderSource { return g.avatarLoader }
func (g *GlobalContext) GetRandom() Random { return g.random }
func (g *GlobalContext) SetRandom(r Random) {
if g.GetRunMode() != DevelRunMode {
panic("Random can only be altered in devel")
}
g.random = r
}
type LogGetter func() logger.Logger
// Note: all these sync.Mutex fields are pointers so that the Clone funcs work.
func NewGlobalContext() *GlobalContext {
log := logger.New("keybase")
ret := &GlobalContext{
Log: log,
PerfLog: log,
VDL: NewVDebugLog(log),
SKBKeyringMu: new(sync.Mutex),
perUserKeyringMu: new(sync.Mutex),
vidMu: new(sync.Mutex),
cacheMu: new(sync.RWMutex),
socketWrapperMu: new(sync.RWMutex),
shutdownOnce: new(sync.Once),
clockMu: new(sync.Mutex),
clock: clockwork.NewRealClock(),
hookMu: new(sync.RWMutex),
oodiMu: new(sync.RWMutex),
outOfDateInfo: &keybase1.OutOfDateInfo{},
lastUpgradeWarning: new(time.Time),
uchMu: new(sync.Mutex),
secretStoreMu: new(sync.Mutex),
NewTriplesec: NewSecureTriplesec,
ActiveDevice: NewActiveDevice(),
switchUserMu: NewVerboseLock(VLog0, "switchUserMu"),
FeatureFlags: NewFeatureFlagSet(),
switchedUsers: make(map[NormalizedUsername]bool),
Pegboard: NewPegboard(),
random: &SecureRandom{},
RuntimeStats: NewDummyRuntimeStats(),
}
ret.TeamMemberCountCache = newTeamMemberCountCache(ret)
return ret
}
func init() {
}
func (g *GlobalContext) SetCommandLine(cmd CommandLine) { g.Env.SetCommandLine(cmd) }
func (g *GlobalContext) SetUI(u UI) { g.UI = u }
func (g *GlobalContext) SetEKLib(ekLib EKLib) { g.ekLib = ekLib }
func (g *GlobalContext) SetTeambotBotKeyer(keyer TeambotBotKeyer) { g.teambotBotKeyer = keyer }
func (g *GlobalContext) SetTeambotMemberKeyer(keyer TeambotMemberKeyer) { g.teambotMemberKeyer = keyer }
func (g *GlobalContext) initPerfLogFile() {
lfc := g.Env.GetLogFileConfig(g.Env.GetPerfLogFile())
lfc.SkipRedirectStdErr = true
lfw := logger.NewLogFileWriter(*lfc)
if err := lfw.Open(g.GetClock().Now()); err != nil {
g.Log.Debug("Unable to getLogger %v", err)
return
}
g.PerfLog = logger.NewInternalLogger(log.New(lfw, "", log.LstdFlags|log.Lmicroseconds|log.Lshortfile))
}
func (g *GlobalContext) initGUILogFile() {
config := g.Env.GetLogFileConfig(g.Env.GetGUILogFile())
config.SkipRedirectStdErr = true
fileWriter := logger.NewLogFileWriter(*config)
if err := fileWriter.Open(g.GetClock().Now()); err != nil {
g.GetLog().Debug("Unable to init GUI log file %v", err)
return
}
g.GUILogFile = fileWriter
}
func (g *GlobalContext) Init() *GlobalContext {
g.Env = NewEnv(nil, nil, g.GetLog)
g.Service = false
g.Resolver = NewResolverImpl()
g.RateLimits = NewRateLimits(g)
g.upakLoader = NewUncachedUPAKLoader(g)
g.teamLoader = newNullTeamLoader(g)
g.fastTeamLoader = newNullFastTeamLoader()
g.hiddenTeamChainManager = newNullHiddenTeamChainManager()
g.TeamRoleMapManager = newNullTeamRoleMapManager()
g.teamAuditor = newNullTeamAuditor()
g.teamBoxAuditor = newNullTeamBoxAuditor()
g.stellar = newNullStellar(g)
g.fullSelfer = NewUncachedFullSelf(g)
g.ConnectivityMonitor = NullConnectivityMonitor{}
g.localSigchainGuard = NewLocalSigchainGuard(g)
g.MobileNetState = NewMobileNetState(g)
g.MobileAppState = NewMobileAppState(g)
g.DesktopAppState = NewDesktopAppState(g)
g.RPCCanceler = NewRPCCanceler()
g.IdentifyDispatch = NewIdentifyDispatch()
g.Identify3State = NewIdentify3State(g)
g.GregorState = newNullGregorState()
g.LocalNetworkInstrumenterStorage = NewDiskInstrumentationStorage(g, keybase1.NetworkSource_LOCAL)
g.RemoteNetworkInstrumenterStorage = NewDiskInstrumentationStorage(g, keybase1.NetworkSource_REMOTE)
g.Log.Debug("GlobalContext#Init(%p)\n", g)
return g
}
func NewGlobalContextInit() *GlobalContext {
return NewGlobalContext().Init()
}
func (g *GlobalContext) SetService() {
g.Service = true
g.ConnectionManager = NewConnectionManager()
g.NotifyRouter = NewNotifyRouter(g)
}
func (g *GlobalContext) SetUIDMapper(u UIDMapper) {
g.UIDMapper = u
}
func (g *GlobalContext) SetServiceSummaryMapper(u ServiceSummaryMapper) {
g.ServiceMapper = u
}
func (g *GlobalContext) SetUIRouter(u UIRouter) {
g.UIRouter = u
}
func (g *GlobalContext) SetDNSNameServerFetcher(d DNSNameServerFetcher) {
g.DNSNSFetcher = d
}
func (g *GlobalContext) SetUPAKLoader(u UPAKLoader) {
g.upakLoader = u
}
func (g *GlobalContext) SetAvatarLoader(a AvatarLoaderSource) {
g.avatarLoader = a
}
// simulateServiceRestart simulates what happens when a service restarts for the
// purposes of testing.
func (g *GlobalContext) simulateServiceRestart() {
defer g.switchUserMu.Acquire(NewMetaContext(context.TODO(), g), "simulateServiceRestart")()
_ = g.ActiveDevice.Clear()
}
// ConfigureLogging should be given non-nil Usage if called by the main
// service.
func (g *GlobalContext) ConfigureLogging(usage *Usage) error {
style := g.Env.GetLogFormat()
debug := g.Env.GetDebug()
logFile, ok := g.Env.GetEffectiveLogFile()
// Configure regardless if the logFile should be used or not
g.Log.Configure(style, debug, logFile)
// Start redirecting logs if the logFile should be used
// If this is not called, prints logs to stdout.
if ok {
err := logger.SetLogFileConfig(g.Env.GetLogFileConfig(logFile), &logger.BufferedLoggerConfig{
Frequency: 200 * time.Millisecond,
Size: 1000000,
})
if err != nil {
return err
}
}
g.VDL.Configure(g.Env.GetVDebugSetting())
// On Linux, the post-install script calls `keybase --use-root-config-file
// config get --direct` to figure out if the redirector should be enabled or not.
// That command, like all other commands, goes through all these initial steps
// like ConfigureLogging before executing the command. On Ubuntu, '$HOME' is *not*
// changed to the root's user's HOME when using sudo, which basically means
// that `sudo bash -c 'mkdir $HOME/.cache'`, e.g., creates it within the *user's*
// home directory with root permissions (unlike Debian, Fedora, Arch, etc.).
// So, in this case, we do not configure the log files so as not to mess up
// permissions in the user's home directory.
shouldInitLogs := true
if usage != nil && usage.AllowRoot {
isAdmin, _, err := IsSystemAdminUser()
if err == nil && isAdmin {
shouldInitLogs = false
}
}
if shouldInitLogs {
g.initGUILogFile()
g.initPerfLogFile()
}
return nil
}
func (g *GlobalContext) PushShutdownHook(sh ShutdownHook) {
g.ShutdownHooks = append(g.ShutdownHooks, sh)
}
func (g *GlobalContext) ConfigureConfig() error {
c := NewJSONConfigFile(g, g.Env.GetConfigFilename())
err := c.Load(false)
if err != nil {
return err
}
if err = c.Check(); err != nil {
return err
}
g.Env.SetConfig(c, c)
return nil
}
func (g *GlobalContext) ConfigReload() error {
err := g.ConfigureConfig()
if err != nil {
return err
}
guiConfigErr := g.ConfigureGUIConfig()
if guiConfigErr != nil {
g.Log.Debug("Failed to open gui config: %s", guiConfigErr)
}
return g.ConfigureUpdaterConfig()
}
// migrateGUIConfig does not delete old values from service's config.
func migrateGUIConfig(serviceConfig ConfigReader, guiConfig *JSONFile) error {
var errs []error
p := "ui.routeState2"
if uiRouteState2, isSet := serviceConfig.GetStringAtPath(p); isSet {
if err := guiConfig.SetStringAtPath(p, uiRouteState2); err != nil {
errs = append(errs, err)
}
}
p = "ui.shownMonsterPushPrompt"
if uiMonsterStorage, isSet := serviceConfig.GetBoolAtPath(p); isSet {
if err := guiConfig.SetBoolAtPath(p, uiMonsterStorage); err != nil {
errs = append(errs, err)
}
}
p = "stellar.lastSentXLM"
if stellarLastSentXLM, isSet := serviceConfig.GetBoolAtPath(p); isSet {
if err := guiConfig.SetBoolAtPath(p, stellarLastSentXLM); err != nil {
errs = append(errs, err)
}
}
p = "ui.importContacts"
syncSettings, err := serviceConfig.GetInterfaceAtPath(p)
if err != nil {
if !isJSONNoSuchKeyError(err) {
errs = append(errs, err)
}
} else {
syncSettings, ok := syncSettings.(map[string]interface{})
if !ok {
errs = append(errs, fmt.Errorf("Failed to coerce ui.importContacts in migration"))
} else {
for username, syncEnabled := range syncSettings {
syncEnabled, ok := syncEnabled.(bool)
if !ok {
errs = append(errs, fmt.Errorf("Failed to coerce syncEnabled in migration for %s", username))
}
err := guiConfig.SetBoolAtPath(fmt.Sprintf("%s.%s", p, username), syncEnabled)
if err != nil {
errs = append(errs, err)
}
}
}
}
return CombineErrors(errs...)
}
func (g *GlobalContext) ConfigureGUIConfig() error {
guiConfig := NewJSONFile(g, g.Env.GetGUIConfigFilename(), "gui config")
found, err := guiConfig.LoadCheckFound()
if err == nil {
if !found {
err := guiConfig.SetBoolAtPath("gui", true)
if err != nil {
return err
}
// If this is the first time creating this file, manually migrate
// old GUI config values from the main config file best-effort.
serviceConfig := g.Env.GetConfig()
if migrateErr := migrateGUIConfig(serviceConfig, guiConfig); migrateErr != nil {
g.Log.Debug("Failed to migrate config to new GUI config file: %s", migrateErr)
}
}
g.Env.SetGUIConfig(guiConfig)
}
return err
}
func (g *GlobalContext) ConfigureUpdaterConfig() error {
c := NewJSONUpdaterConfigFile(g)
err := c.Load(false)
if err == nil {
g.Env.SetUpdaterConfig(c)
} else {
g.Log.Debug("Failed to open update config: %s\n", err)
}
return err
}
func (g *GlobalContext) ConfigureTimers() error {
g.Timers = NewTimerSet(g)
return nil
}
func (g *GlobalContext) ConfigureKeyring() error {
g.Keyrings = NewKeyrings(g)
return nil
}
func VersionMessage(linefn func(string)) {
linefn(fmt.Sprintf("Keybase CLI %s", VersionString()))
linefn(fmt.Sprintf("- Built with %s", runtime.Version()))
linefn("- Visit https://keybase.io for more details")
}
func (g *GlobalContext) StartupMessage() {
VersionMessage(func(s string) { g.Log.Debug(s) })
}
func (g *GlobalContext) ConfigureAPI() error {
iapi, xapi, err := NewAPIEngines(g)
if err != nil {
return fmt.Errorf("Failed to configure API access: %s", err)
}
g.API = iapi
g.XAPI = xapi
return nil
}
// shutdownCachesLocked shutdown any non-nil caches that have running goroutines
// in them. It can be called from either configureMemCachesLocked (via logout or flush),
// or via Shutdown. In either case, callers must hold g.cacheMu.
func (g *GlobalContext) shutdownCachesLocked() {
// shutdown and nil out any existing caches.
if g.trackCache != nil {
g.trackCache.Shutdown()
}
if g.identify2Cache != nil {
g.identify2Cache.Shutdown()
}
if g.linkCache != nil {
g.linkCache.Shutdown()
}
if g.cardCache != nil {
g.cardCache.Shutdown()
}
}
func (g *GlobalContext) TrackCache() *TrackCache {
g.cacheMu.Lock()
defer g.cacheMu.Unlock()
return g.trackCache
}
func (g *GlobalContext) Identify2Cache() Identify2Cacher {
g.cacheMu.Lock()
defer g.cacheMu.Unlock()
return g.identify2Cache
}
func (g *GlobalContext) CardCache() *UserCardCache {
g.cacheMu.Lock()
defer g.cacheMu.Unlock()
return g.cardCache
}
func (g *GlobalContext) LinkCache() *LinkCache {
g.cacheMu.Lock()
defer g.cacheMu.Unlock()
return g.linkCache
}
func (g *GlobalContext) configureMemCachesLocked(isFlush bool) {
g.shutdownCachesLocked()
g.IDLocktab = NewLockTable()
g.loadUserLockTab = NewLockTable()
g.Resolver.EnableCaching(NewMetaContextBackground(g))
g.trackCache = NewTrackCache()
g.identify2Cache = NewIdentify2Cache(g.Env.GetUserCacheMaxAge())
g.Log.Debug("Created Identify2Cache, max age: %s", g.Env.GetUserCacheMaxAge())
g.linkCache = NewLinkCache(g.Env.GetLinkCacheSize(), g.Env.GetLinkCacheCleanDur())
g.Log.Debug("Created LinkCache, max size: %d, clean dur: %s", g.Env.GetLinkCacheSize(), g.Env.GetLinkCacheCleanDur())
g.cardCache = NewUserCardCache(g.Env.GetUserCacheMaxAge())
g.Log.Debug("Created CardCache, max age: %s", g.Env.GetUserCacheMaxAge())
// If we're just flushing the caches, and already have a Proof cache, then the right idea
// is just to reset what's in the ProofCache. Otherwise, we make a new one.
if isFlush && g.ProofCache != nil {
_ = g.ProofCache.Reset()
} else {
g.ProofCache = NewProofCache(g, g.Env.GetProofCacheSize())
}
// If it's startup (and not a "flush"), then install a new full selfer
// cache. Otherwise, just make a new instance of the kind that's already there.
if isFlush {
g.fullSelfer = g.fullSelfer.New()
} else {
g.fullSelfer = NewCachedFullSelf(g)
}
g.Log.Debug("made a new full self cache")
g.upakLoader = NewCachedUPAKLoader(g, CachedUserTimeout)
g.Log.Debug("made a new cached UPAK loader (timeout=%v)", CachedUserTimeout)
g.PayloadCache = NewPayloadCache(g, g.Env.GetPayloadCacheSize())
}
func (g *GlobalContext) ConfigureCaches() error {
g.cacheMu.Lock()
defer g.cacheMu.Unlock()
g.configureMemCachesLocked(false)
return g.configureDiskCachesLocked()
}
func (g *GlobalContext) FlushCaches() {
g.cacheMu.Lock()
defer g.cacheMu.Unlock()
g.configureMemCachesLocked(true)
g.TeamRoleMapManager.FlushCache()
}
func (g *GlobalContext) configureDiskCachesLocked() error {
// We consider the local DBs as caches; they're caching our
// fetches from the server after all (and also our cryptographic
// checking).
g.LocalDb = NewJSONLocalDb(NewLevelDb(g, g.Env.GetDbFilename))
g.LocalChatDb = NewJSONLocalDb(NewLevelDb(g, g.Env.GetChatDbFilename))
epick := FirstErrorPicker{}
epick.Push(g.LocalDb.Open())
epick.Push(g.LocalChatDb.Open())
return epick.Error()
}
func (g *GlobalContext) ConfigureMerkleClient() error {
g.MerkleClient = NewMerkleClient(g)
return nil
}
func (g *GlobalContext) GetUPAKLoader() UPAKLoader {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.upakLoader
}
func (g *GlobalContext) GetTeamLoader() TeamLoader {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.teamLoader
}
func (g *GlobalContext) GetFastTeamLoader() FastTeamLoader {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.fastTeamLoader
}
func (g *GlobalContext) GetHiddenTeamChainManager() HiddenTeamChainManager {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.hiddenTeamChainManager
}
func (g *GlobalContext) GetTeamRoleMapManager() TeamRoleMapManager {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.TeamRoleMapManager
}
func (g *GlobalContext) SetTeamRoleMapManager(r TeamRoleMapManager) {
g.cacheMu.Lock()
defer g.cacheMu.Unlock()
g.TeamRoleMapManager = r
}
func (g *GlobalContext) SetHiddenTeamChainManager(h HiddenTeamChainManager) {
g.cacheMu.Lock()
defer g.cacheMu.Unlock()
g.hiddenTeamChainManager = h
}
func (g *GlobalContext) GetTeamAuditor() TeamAuditor {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.teamAuditor
}
func (g *GlobalContext) GetTeamBoxAuditor() TeamBoxAuditor {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.teamBoxAuditor
}
func (g *GlobalContext) GetStellar() Stellar {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.stellar
}
func (g *GlobalContext) GetDeviceEKStorage() DeviceEKStorage {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.deviceEKStorage
}
func (g *GlobalContext) GetUserEKBoxStorage() UserEKBoxStorage {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.userEKBoxStorage
}
func (g *GlobalContext) GetTeamEKBoxStorage() TeamEKBoxStorage {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.teamEKBoxStorage
}
func (g *GlobalContext) GetTeambotEKBoxStorage() TeamEKBoxStorage {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.teambotEKBoxStorage
}
func (g *GlobalContext) GetImplicitTeamConflictInfoCacher() LRUer {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.itciCacher
}
func (g *GlobalContext) SetImplicitTeamConflictInfoCacher(l LRUer) {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
g.itciCacher = l
}
func (g *GlobalContext) GetImplicitTeamCacher() MemLRUer {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.iteamCacher
}
func (g *GlobalContext) SetImplicitTeamCacher(l MemLRUer) {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
g.iteamCacher = l
}
func (g *GlobalContext) GetKVRevisionCache() KVRevisionCacher {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.kvRevisionCache
}
func (g *GlobalContext) SetKVRevisionCache(kvr KVRevisionCacher) {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
g.kvRevisionCache = kvr
}
func (g *GlobalContext) GetFullSelfer() FullSelfer {
g.cacheMu.RLock()
defer g.cacheMu.RUnlock()
return g.fullSelfer
}
func (g *GlobalContext) GetParamProofStore() MerkleStore {
return g.paramProofStore
}
func (g *GlobalContext) GetExternalURLStore() MerkleStore {
return g.externalURLStore
}
// to implement ProofContext
func (g *GlobalContext) GetPvlSource() MerkleStore {
return g.pvlSource
}
// to implement ProofContext
func (g *GlobalContext) GetAppType() AppType {
return g.Env.GetAppType()
}
func (g *GlobalContext) IsMobileAppType() bool {
return g.Env.GetAppType() == MobileAppType
}
func (g *GlobalContext) ConfigureExportedStreams() error {
g.XStreams = NewExportedStreams()
return nil
}
// Shutdown is called exactly once per-process and does whatever
// cleanup is necessary to shut down the server.
func (g *GlobalContext) Shutdown(mctx MetaContext) error {
var err error
didShutdown := false
// Wrap in a Once.Do so that we don't inadvertedly
// run this code twice.
g.shutdownOnce.Do(func() {
g.Log.Debug("GlobalContext#Shutdown(%p)\n", g)
if g.PerfLog != nil {
g.PerfLog.Debug("GlobalContext#Shutdown(%p)\n", g)
}
didShutdown = true
epick := FirstErrorPicker{}
if g.hiddenTeamChainManager != nil {
g.hiddenTeamChainManager.Shutdown(mctx)
}
if g.NotifyRouter != nil {
g.NotifyRouter.Shutdown()
}
if g.UIRouter != nil {
g.UIRouter.Shutdown()
}
if g.ConnectionManager != nil {
g.ConnectionManager.Shutdown()
}
if g.UI != nil {
epick.Push(g.UI.Shutdown())
}
// Shutdown can still race with Logout, so make sure that we hold onto
// the cacheMu before shutting down the caches. See comments in
// shutdownCachesLocked
g.cacheMu.Lock()
g.shutdownCachesLocked()
g.cacheMu.Unlock()
if g.proofServices != nil {
g.proofServices.Shutdown()
}
if g.Resolver != nil {
g.Resolver.Shutdown(NewMetaContextBackground(g))
}
g.Log.Debug("executing %d shutdown hooks; errCount=%d", len(g.ShutdownHooks), epick.Count())
for _, hook := range g.ShutdownHooks {
epick.Push(hook(mctx))
}
g.Log.Debug("executed shutdown hooks; errCount=%d", epick.Count())
if g.LocalNetworkInstrumenterStorage != nil {
<-g.LocalNetworkInstrumenterStorage.Stop(mctx.Ctx())
}
if g.RemoteNetworkInstrumenterStorage != nil {
<-g.RemoteNetworkInstrumenterStorage.Stop(mctx.Ctx())
}
// shutdown the databases after the shutdown hooks run, we may want to
// flush memory caches to disk during shutdown.
if g.LocalDb != nil {
epick.Push(g.LocalDb.Close())
}
if g.LocalChatDb != nil {
epick.Push(g.LocalChatDb.Close())
}
if g.GUILogFile != nil {
epick.Push(g.GUILogFile.Close())
}
<-g.Identify3State.Shutdown()
err = epick.Error()
g.Log.Debug("exiting shutdown code=%d; errCount=%d; firstErr=%v", g.ExitCode, epick.Count(), err)
})
// Make a little bit of a statement if we wind up here a second time
// (which is a bug).
if !didShutdown {
g.Log.Debug("Skipped shutdown on second call")
}
return err
}
func (u Usage) UseKeyring() bool {
return u.KbKeyring || u.GpgKeyring
}
// If changed, make sure to correct standalone usage in g.Configure below
var ServiceUsage = Usage{
Config: true,
KbKeyring: true,
GpgKeyring: true,
API: true,
Socket: true,
}
func (g *GlobalContext) ConfigureCommand(line CommandLine, cmd Command) error {
usage := cmd.GetUsage()
return g.Configure(line, usage)
}
func (g *GlobalContext) Configure(line CommandLine, usage Usage) error {
g.SetCommandLine(line)
if err := g.ConfigureLogging(&usage); err != nil {
return err
}
if g.Env.GetStandalone() {
// If standalone, override the usage to be the same as in a service
// If changed, make sure to correct ServiceUsage above.
usage.Config = ServiceUsage.Config
usage.KbKeyring = ServiceUsage.KbKeyring
usage.GpgKeyring = ServiceUsage.GpgKeyring
usage.API = ServiceUsage.API
usage.Socket = ServiceUsage.Socket
}
if err := g.ConfigureUsage(usage); err != nil {
return err
}
// secretStore must be created after SetCommandLine and ConfigureUsage in
// order to correctly use -H,-home flag and config vars for
// remember_passphrase.
g.secretStoreMu.Lock()
g.secretStore = NewSecretStoreLocked(NewMetaContextBackground(g))
g.secretStoreMu.Unlock()
return nil
}
func (g *GlobalContext) ConfigureUsage(usage Usage) error {
var err error
if usage.Config {
if err = g.ConfigReload(); err != nil {
return err
}
}
if usage.UseKeyring() {
if err = g.ConfigureKeyring(); err != nil {
return err
}
}
if usage.API {
if err = g.ConfigureAPI(); err != nil {
return err
}
}
if usage.Socket || !g.Env.GetStandalone() {
if err = g.ConfigureSocketInfo(); err != nil {
return err
}
}
if err = g.ConfigureExportedStreams(); err != nil {
return err
}
if err = g.ConfigureCaches(); err != nil {
return err
}
g.LocalNetworkInstrumenterStorage.Start(context.TODO())
g.RemoteNetworkInstrumenterStorage.Start(context.TODO())
if err = g.ConfigureMerkleClient(); err != nil {
return err
}
if g.UI != nil {
if err = g.UI.Configure(); err != nil {
return err