-
Notifications
You must be signed in to change notification settings - Fork 267
/
dataStore.go
1736 lines (1384 loc) · 48.3 KB
/
dataStore.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 (c) 2015, Psiphon Inc.
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package psiphon
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"sync"
"time"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
)
var (
datastoreServerEntriesBucket = []byte("serverEntries")
datastoreServerEntryTagsBucket = []byte("serverEntryTags")
datastoreServerEntryTombstoneTagsBucket = []byte("serverEntryTombstoneTags")
datastoreSplitTunnelRouteETagsBucket = []byte("splitTunnelRouteETags")
datastoreSplitTunnelRouteDataBucket = []byte("splitTunnelRouteData")
datastoreUrlETagsBucket = []byte("urlETags")
datastoreKeyValueBucket = []byte("keyValues")
datastoreRemoteServerListStatsBucket = []byte("remoteServerListStats")
datastoreFailedTunnelStatsBucket = []byte("failedTunnelStats")
datastoreSLOKsBucket = []byte("SLOKs")
datastoreTacticsBucket = []byte("tactics")
datastoreSpeedTestSamplesBucket = []byte("speedTestSamples")
datastoreDialParametersBucket = []byte("dialParameters")
datastoreLastConnectedKey = "lastConnected"
datastoreLastServerEntryFilterKey = []byte("lastServerEntryFilter")
datastoreAffinityServerEntryIDKey = []byte("affinityServerEntryID")
datastorePersistentStatTypeRemoteServerList = string(datastoreRemoteServerListStatsBucket)
datastorePersistentStatTypeFailedTunnel = string(datastoreFailedTunnelStatsBucket)
datastoreServerEntryFetchGCThreshold = 20
datastoreMutex sync.RWMutex
activeDatastoreDB *datastoreDB
)
// OpenDataStore opens and initializes the singleton data store instance.
func OpenDataStore(config *Config) error {
datastoreMutex.Lock()
existingDB := activeDatastoreDB
if existingDB != nil {
datastoreMutex.Unlock()
return common.ContextError(errors.New("db already open"))
}
newDB, err := datastoreOpenDB(config.DataStoreDirectory)
if err != nil {
datastoreMutex.Unlock()
return common.ContextError(err)
}
activeDatastoreDB = newDB
datastoreMutex.Unlock()
_ = resetAllPersistentStatsToUnreported()
return nil
}
// CloseDataStore closes the singleton data store instance, if open.
func CloseDataStore() {
datastoreMutex.Lock()
defer datastoreMutex.Unlock()
if activeDatastoreDB == nil {
return
}
err := activeDatastoreDB.close()
if err != nil {
NoticeAlert("failed to close database: %s", common.ContextError(err))
}
activeDatastoreDB = nil
}
func datastoreView(fn func(tx *datastoreTx) error) error {
datastoreMutex.RLock()
defer datastoreMutex.RUnlock()
if activeDatastoreDB == nil {
return common.ContextError(errors.New("database not open"))
}
err := activeDatastoreDB.view(fn)
if err != nil {
err = common.ContextError(err)
}
return err
}
func datastoreUpdate(fn func(tx *datastoreTx) error) error {
datastoreMutex.RLock()
defer datastoreMutex.RUnlock()
if activeDatastoreDB == nil {
return common.ContextError(errors.New("database not open"))
}
err := activeDatastoreDB.update(fn)
if err != nil {
err = common.ContextError(err)
}
return err
}
// StoreServerEntry adds the server entry to the data store.
//
// When a server entry already exists for a given server, it will be
// replaced only if replaceIfExists is set or if the the ConfigurationVersion
// field of the new entry is strictly higher than the existing entry.
//
// If the server entry data is malformed, an alert notice is issued and
// the entry is skipped; no error is returned.
func StoreServerEntry(serverEntryFields protocol.ServerEntryFields, replaceIfExists bool) error {
// TODO: call serverEntryFields.VerifySignature. At this time, we do not do
// this as not all server entries have an individual signature field. All
// StoreServerEntry callers either call VerifySignature or obtain server
// entries from a trusted source (embedded in a signed client, or in a signed
// authenticated package).
// Server entries should already be validated before this point,
// so instead of skipping we fail with an error.
err := protocol.ValidateServerEntryFields(serverEntryFields)
if err != nil {
return common.ContextError(
fmt.Errorf("invalid server entry: %s", err))
}
// BoltDB implementation note:
// For simplicity, we don't maintain indexes on server entry
// region or supported protocols. Instead, we perform full-bucket
// scans with a filter. With a small enough database (thousands or
// even tens of thousand of server entries) and common enough
// values (e.g., many servers support all protocols), performance
// is expected to be acceptable.
err = datastoreUpdate(func(tx *datastoreTx) error {
serverEntries := tx.bucket(datastoreServerEntriesBucket)
serverEntryTags := tx.bucket(datastoreServerEntryTagsBucket)
serverEntryTombstoneTags := tx.bucket(datastoreServerEntryTombstoneTagsBucket)
serverEntryID := []byte(serverEntryFields.GetIPAddress())
// Check not only that the entry exists, but is valid. This
// will replace in the rare case where the data is corrupt.
existingConfigurationVersion := -1
existingData := serverEntries.get(serverEntryID)
if existingData != nil {
var existingServerEntry *protocol.ServerEntry
err := json.Unmarshal(existingData, &existingServerEntry)
if err == nil {
existingConfigurationVersion = existingServerEntry.ConfigurationVersion
}
}
exists := existingConfigurationVersion > -1
newer := exists && existingConfigurationVersion < serverEntryFields.GetConfigurationVersion()
update := !exists || replaceIfExists || newer
if !update {
return nil
}
serverEntryTag := serverEntryFields.GetTag()
// Generate a derived tag when the server entry has no tag.
if serverEntryTag == "" {
serverEntryTag = protocol.GenerateServerEntryTag(
serverEntryFields.GetIPAddress(),
serverEntryFields.GetWebServerSecret())
serverEntryFields.SetTag(serverEntryTag)
}
serverEntryTagBytes := []byte(serverEntryTag)
// Ignore the server entry if it was previously pruned and a tombstone is
// set.
//
// This logic is enforced only for embedded server entries, as all other
// sources are considered to be definitive and non-stale. These exceptions
// intentionally allow the scenario where a server is temporarily deleted
// and then restored; in this case, it's desired for pruned server entries
// to be restored.
if serverEntryFields.GetLocalSource() == protocol.SERVER_ENTRY_SOURCE_EMBEDDED {
if serverEntryTombstoneTags.get(serverEntryTagBytes) != nil {
return nil
}
}
data, err := json.Marshal(serverEntryFields)
if err != nil {
return common.ContextError(err)
}
err = serverEntries.put(serverEntryID, data)
if err != nil {
return common.ContextError(err)
}
err = serverEntryTags.put(serverEntryTagBytes, serverEntryID)
if err != nil {
return common.ContextError(err)
}
NoticeInfo("updated server %s", serverEntryFields.GetDiagnosticID())
return nil
})
if err != nil {
return common.ContextError(err)
}
return nil
}
// StoreServerEntries stores a list of server entries.
// There is an independent transaction for each entry insert/update.
func StoreServerEntries(
config *Config,
serverEntries []protocol.ServerEntryFields,
replaceIfExists bool) error {
for _, serverEntryFields := range serverEntries {
err := StoreServerEntry(serverEntryFields, replaceIfExists)
if err != nil {
return common.ContextError(err)
}
}
return nil
}
// StreamingStoreServerEntries stores a list of server entries.
// There is an independent transaction for each entry insert/update.
func StreamingStoreServerEntries(
config *Config,
serverEntries *protocol.StreamingServerEntryDecoder,
replaceIfExists bool) error {
// Note: both StreamingServerEntryDecoder.Next and StoreServerEntry
// allocate temporary memory buffers for hex/JSON decoding/encoding,
// so this isn't true constant-memory streaming (it depends on garbage
// collection).
n := 0
for {
serverEntry, err := serverEntries.Next()
if err != nil {
return common.ContextError(err)
}
if serverEntry == nil {
// No more server entries
break
}
err = StoreServerEntry(serverEntry, replaceIfExists)
if err != nil {
return common.ContextError(err)
}
n += 1
if n == datastoreServerEntryFetchGCThreshold {
DoGarbageCollection()
n = 0
}
}
return nil
}
// PromoteServerEntry sets the server affinity server entry ID to the
// specified server entry IP address.
func PromoteServerEntry(config *Config, ipAddress string) error {
err := datastoreUpdate(func(tx *datastoreTx) error {
serverEntryID := []byte(ipAddress)
// Ensure the corresponding server entry exists before
// setting server affinity.
bucket := tx.bucket(datastoreServerEntriesBucket)
data := bucket.get(serverEntryID)
if data == nil {
NoticeAlert(
"PromoteServerEntry: ignoring unknown server entry: %s",
ipAddress)
return nil
}
bucket = tx.bucket(datastoreKeyValueBucket)
err := bucket.put(datastoreAffinityServerEntryIDKey, serverEntryID)
if err != nil {
return common.ContextError(err)
}
// Store the current server entry filter (e.g, region, etc.) that
// was in use when the entry was promoted. This is used to detect
// when the top ranked server entry was promoted under a different
// filter.
currentFilter, err := makeServerEntryFilterValue(config)
if err != nil {
return common.ContextError(err)
}
return bucket.put(datastoreLastServerEntryFilterKey, currentFilter)
})
if err != nil {
return common.ContextError(err)
}
return nil
}
func makeServerEntryFilterValue(config *Config) ([]byte, error) {
// Currently, only a change of EgressRegion will "break" server affinity.
// If the tunnel protocol filter changes, any existing affinity server
// either passes the new filter, or it will be skipped anyway.
return []byte(config.EgressRegion), nil
}
func hasServerEntryFilterChanged(config *Config) (bool, error) {
currentFilter, err := makeServerEntryFilterValue(config)
if err != nil {
return false, common.ContextError(err)
}
changed := false
err = datastoreView(func(tx *datastoreTx) error {
bucket := tx.bucket(datastoreKeyValueBucket)
previousFilter := bucket.get(datastoreLastServerEntryFilterKey)
// When not found, previousFilter will be nil; ensures this
// results in "changed", even if currentFilter is len(0).
if previousFilter == nil ||
bytes.Compare(previousFilter, currentFilter) != 0 {
changed = true
}
return nil
})
if err != nil {
return false, common.ContextError(err)
}
return changed, nil
}
// ServerEntryIterator is used to iterate over
// stored server entries in rank order.
type ServerEntryIterator struct {
config *Config
applyServerAffinity bool
serverEntryIDs [][]byte
serverEntryIndex int
isTacticsServerEntryIterator bool
isTargetServerEntryIterator bool
hasNextTargetServerEntry bool
targetServerEntry *protocol.ServerEntry
}
// NewServerEntryIterator creates a new ServerEntryIterator.
//
// The boolean return value indicates whether to treat the first server(s)
// as affinity servers or not. When the server entry selection filter changes
// such as from a specific region to any region, or when there was no previous
// filter/iterator, the the first server(s) are arbitrary and should not be
// given affinity treatment.
//
// NewServerEntryIterator and any returned ServerEntryIterator are not
// designed for concurrent use as not all related datastore operations are
// performed in a single transaction.
//
func NewServerEntryIterator(config *Config) (bool, *ServerEntryIterator, error) {
// When configured, this target server entry is the only candidate
if config.TargetServerEntry != "" {
return newTargetServerEntryIterator(config, false)
}
filterChanged, err := hasServerEntryFilterChanged(config)
if err != nil {
return false, nil, common.ContextError(err)
}
applyServerAffinity := !filterChanged
iterator := &ServerEntryIterator{
config: config,
applyServerAffinity: applyServerAffinity,
}
err = iterator.reset(true)
if err != nil {
return false, nil, common.ContextError(err)
}
return applyServerAffinity, iterator, nil
}
func NewTacticsServerEntryIterator(config *Config) (*ServerEntryIterator, error) {
// When configured, this target server entry is the only candidate
if config.TargetServerEntry != "" {
_, iterator, err := newTargetServerEntryIterator(config, true)
return iterator, err
}
iterator := &ServerEntryIterator{
config: config,
isTacticsServerEntryIterator: true,
}
err := iterator.reset(true)
if err != nil {
return nil, common.ContextError(err)
}
return iterator, nil
}
// newTargetServerEntryIterator is a helper for initializing the TargetServerEntry case
func newTargetServerEntryIterator(config *Config, isTactics bool) (bool, *ServerEntryIterator, error) {
serverEntry, err := protocol.DecodeServerEntry(
config.TargetServerEntry, config.loadTimestamp, protocol.SERVER_ENTRY_SOURCE_TARGET)
if err != nil {
return false, nil, common.ContextError(err)
}
if serverEntry.Tag == "" {
serverEntry.Tag = protocol.GenerateServerEntryTag(
serverEntry.IpAddress, serverEntry.WebServerSecret)
}
if isTactics {
if len(serverEntry.GetSupportedTacticsProtocols()) == 0 {
return false, nil, common.ContextError(errors.New("TargetServerEntry does not support tactics protocols"))
}
} else {
if config.EgressRegion != "" && serverEntry.Region != config.EgressRegion {
return false, nil, common.ContextError(errors.New("TargetServerEntry does not support EgressRegion"))
}
limitTunnelProtocols := config.GetClientParametersSnapshot().TunnelProtocols(parameters.LimitTunnelProtocols)
if len(limitTunnelProtocols) > 0 {
// At the ServerEntryIterator level, only limitTunnelProtocols is applied;
// excludeIntensive is handled higher up.
if len(serverEntry.GetSupportedProtocols(
config.UseUpstreamProxy(), limitTunnelProtocols, false)) == 0 {
return false, nil, common.ContextError(errors.New("TargetServerEntry does not support LimitTunnelProtocols"))
}
}
}
iterator := &ServerEntryIterator{
isTacticsServerEntryIterator: isTactics,
isTargetServerEntryIterator: true,
hasNextTargetServerEntry: true,
targetServerEntry: serverEntry,
}
NoticeInfo("using TargetServerEntry: %s", serverEntry.GetDiagnosticID())
return false, iterator, nil
}
// Reset a NewServerEntryIterator to the start of its cycle. The next
// call to Next will return the first server entry.
func (iterator *ServerEntryIterator) Reset() error {
return iterator.reset(false)
}
func (iterator *ServerEntryIterator) reset(isInitialRound bool) error {
iterator.Close()
if iterator.isTargetServerEntryIterator {
iterator.hasNextTargetServerEntry = true
return nil
}
// BoltDB implementation note:
// We don't keep a transaction open for the duration of the iterator
// because this would expose the following semantics to consumer code:
//
// Read-only transactions and read-write transactions ... generally
// shouldn't be opened simultaneously in the same goroutine. This can
// cause a deadlock as the read-write transaction needs to periodically
// re-map the data file but it cannot do so while a read-only
// transaction is open.
// (https://github.com/boltdb/bolt)
//
// So the underlying serverEntriesBucket could change after the serverEntryIDs
// list is built.
var serverEntryIDs [][]byte
err := datastoreView(func(tx *datastoreTx) error {
bucket := tx.bucket(datastoreKeyValueBucket)
serverEntryIDs = make([][]byte, 0)
shuffleHead := 0
var affinityServerEntryID []byte
// In the first round only, move any server affinity candiate to the
// very first position.
if isInitialRound &&
iterator.applyServerAffinity {
affinityServerEntryID = bucket.get(datastoreAffinityServerEntryIDKey)
if affinityServerEntryID != nil {
serverEntryIDs = append(serverEntryIDs, append([]byte(nil), affinityServerEntryID...))
shuffleHead = 1
}
}
bucket = tx.bucket(datastoreServerEntriesBucket)
cursor := bucket.cursor()
for key := cursor.firstKey(); key != nil; key = cursor.nextKey() {
if affinityServerEntryID != nil {
if bytes.Equal(affinityServerEntryID, key) {
continue
}
}
serverEntryIDs = append(serverEntryIDs, append([]byte(nil), key...))
}
cursor.close()
// Randomly shuffle the entire list of server IDs, excluding the
// server affinity candidate.
for i := len(serverEntryIDs) - 1; i > shuffleHead-1; i-- {
j := prng.Intn(i+1-shuffleHead) + shuffleHead
serverEntryIDs[i], serverEntryIDs[j] = serverEntryIDs[j], serverEntryIDs[i]
}
// In the first round, or with some probability, move _potential_ replay
// candidates to the front of the list (excepting the server affinity slot,
// if any). This move is post-shuffle so the order is still randomized. To
// save the memory overhead of unmarshalling all dial parameters, this
// operation just moves any server with a dial parameter record to the
// front. Whether the dial parameter remains valid for replay -- TTL,
// tactics/config unchanged, etc. --- is checked later.
//
// TODO: move only up to parameters.ReplayCandidateCount to front?
if (isInitialRound ||
iterator.config.GetClientParametersSnapshot().WeightedCoinFlip(
parameters.ReplayLaterRoundMoveToFrontProbability)) &&
iterator.config.GetClientParametersSnapshot().Int(
parameters.ReplayCandidateCount) != 0 {
networkID := []byte(iterator.config.GetNetworkID())
dialParamsBucket := tx.bucket(datastoreDialParametersBucket)
i := shuffleHead
j := len(serverEntryIDs) - 1
for {
for ; i < j; i++ {
key := makeDialParametersKey(serverEntryIDs[i], networkID)
if dialParamsBucket.get(key) == nil {
break
}
}
for ; i < j; j-- {
key := makeDialParametersKey(serverEntryIDs[j], networkID)
if dialParamsBucket.get(key) != nil {
break
}
}
if i < j {
serverEntryIDs[i], serverEntryIDs[j] = serverEntryIDs[j], serverEntryIDs[i]
i++
j--
} else {
break
}
}
}
return nil
})
if err != nil {
return common.ContextError(err)
}
iterator.serverEntryIDs = serverEntryIDs
iterator.serverEntryIndex = 0
return nil
}
// Close cleans up resources associated with a ServerEntryIterator.
func (iterator *ServerEntryIterator) Close() {
iterator.serverEntryIDs = nil
iterator.serverEntryIndex = 0
}
// Next returns the next server entry, by rank, for a ServerEntryIterator.
// Returns nil with no error when there is no next item.
func (iterator *ServerEntryIterator) Next() (*protocol.ServerEntry, error) {
var serverEntry *protocol.ServerEntry
var err error
defer func() {
if err != nil {
iterator.Close()
}
}()
if iterator.isTargetServerEntryIterator {
if iterator.hasNextTargetServerEntry {
iterator.hasNextTargetServerEntry = false
return MakeCompatibleServerEntry(iterator.targetServerEntry), nil
}
return nil, nil
}
// There are no region/protocol indexes for the server entries bucket.
// Loop until we have the next server entry that matches the iterator
// filter requirements.
for {
if iterator.serverEntryIndex >= len(iterator.serverEntryIDs) {
// There is no next item
return nil, nil
}
serverEntryID := iterator.serverEntryIDs[iterator.serverEntryIndex]
iterator.serverEntryIndex += 1
serverEntry = nil
err = datastoreView(func(tx *datastoreTx) error {
serverEntries := tx.bucket(datastoreServerEntriesBucket)
value := serverEntries.get(serverEntryID)
if value == nil {
return nil
}
// Must unmarshal here as slice is only valid within transaction.
err = json.Unmarshal(value, &serverEntry)
if err != nil {
// In case of data corruption or a bug causing this condition,
// do not stop iterating.
serverEntry = nil
NoticeAlert(
"ServerEntryIterator.Next: json.Unmarshal failed: %s",
common.ContextError(err))
}
return nil
})
if err != nil {
return nil, common.ContextError(err)
}
if serverEntry == nil {
// In case of data corruption or a bug causing this condition,
// do not stop iterating.
NoticeAlert("ServerEntryIterator.Next: unexpected missing server entry")
continue
}
// Generate a derived server entry tag for server entries with no tag. Store
// back the updated server entry so that (a) the tag doesn't need to be
// regenerated; (b) the server entry can be looked up by tag (currently used
// in the status request prune case).
//
// This is a distinct transaction so as to avoid the overhead of regular
// write transactions in the iterator; once tags have been stored back, most
// iterator transactions will remain read-only.
if serverEntry.Tag == "" {
serverEntry.Tag = protocol.GenerateServerEntryTag(
serverEntry.IpAddress, serverEntry.WebServerSecret)
err = datastoreUpdate(func(tx *datastoreTx) error {
serverEntries := tx.bucket(datastoreServerEntriesBucket)
serverEntryTags := tx.bucket(datastoreServerEntryTagsBucket)
// We must reload and store back the server entry _fields_ to preserve any
// currently unrecognized fields, for future compatibility.
value := serverEntries.get(serverEntryID)
if value == nil {
return nil
}
var serverEntryFields protocol.ServerEntryFields
err := json.Unmarshal(value, &serverEntryFields)
if err != nil {
return common.ContextError(err)
}
// As there is minor race condition between loading/checking serverEntry
// and reloading/modifying serverEntryFields, this transaction references
// only the freshly loaded fields when checking and setting the tag.
serverEntryTag := serverEntryFields.GetTag()
if serverEntryTag != "" {
return nil
}
serverEntryTag = protocol.GenerateServerEntryTag(
serverEntryFields.GetIPAddress(),
serverEntryFields.GetWebServerSecret())
serverEntryFields.SetTag(serverEntryTag)
jsonServerEntryFields, err := json.Marshal(serverEntryFields)
if err != nil {
return common.ContextError(err)
}
serverEntries.put(serverEntryID, jsonServerEntryFields)
if err != nil {
return common.ContextError(err)
}
serverEntryTags.put([]byte(serverEntryTag), serverEntryID)
if err != nil {
return common.ContextError(err)
}
return nil
})
if err != nil {
// Do not stop.
NoticeAlert(
"ServerEntryIterator.Next: update server entry failed: %s",
common.ContextError(err))
}
}
if iterator.serverEntryIndex%datastoreServerEntryFetchGCThreshold == 0 {
DoGarbageCollection()
}
// Check filter requirements
if iterator.isTacticsServerEntryIterator {
// Tactics doesn't filter by egress region.
if len(serverEntry.GetSupportedTacticsProtocols()) > 0 {
break
}
} else {
if iterator.config.EgressRegion == "" ||
serverEntry.Region == iterator.config.EgressRegion {
break
}
}
}
return MakeCompatibleServerEntry(serverEntry), nil
}
// MakeCompatibleServerEntry provides backwards compatibility with old server entries
// which have a single meekFrontingDomain and not a meekFrontingAddresses array.
// By copying this one meekFrontingDomain into meekFrontingAddresses, this client effectively
// uses that single value as legacy clients do.
func MakeCompatibleServerEntry(serverEntry *protocol.ServerEntry) *protocol.ServerEntry {
if len(serverEntry.MeekFrontingAddresses) == 0 && serverEntry.MeekFrontingDomain != "" {
serverEntry.MeekFrontingAddresses =
append(serverEntry.MeekFrontingAddresses, serverEntry.MeekFrontingDomain)
}
return serverEntry
}
// PruneServerEntry deletes the server entry, along with associated data,
// corresponding to the specified server entry tag. Pruning is subject to an
// age check. In the case of an error, a notice is emitted.
func PruneServerEntry(config *Config, serverEntryTag string) {
err := pruneServerEntry(config, serverEntryTag)
if err != nil {
NoticeAlert(
"PruneServerEntry failed: %s: %s",
serverEntryTag, common.ContextError(err))
return
}
NoticePruneServerEntry(serverEntryTag)
}
func pruneServerEntry(config *Config, serverEntryTag string) error {
minimumAgeForPruning := config.GetClientParametersSnapshot().Duration(
parameters.ServerEntryMinimumAgeForPruning)
return datastoreUpdate(func(tx *datastoreTx) error {
serverEntries := tx.bucket(datastoreServerEntriesBucket)
serverEntryTags := tx.bucket(datastoreServerEntryTagsBucket)
serverEntryTombstoneTags := tx.bucket(datastoreServerEntryTombstoneTagsBucket)
keyValues := tx.bucket(datastoreKeyValueBucket)
dialParameters := tx.bucket(datastoreDialParametersBucket)
serverEntryTagBytes := []byte(serverEntryTag)
serverEntryID := serverEntryTags.get(serverEntryTagBytes)
if serverEntryID == nil {
return common.ContextError(errors.New("server entry tag not found"))
}
serverEntryJson := serverEntries.get(serverEntryID)
if serverEntryJson == nil {
return common.ContextError(errors.New("server entry not found"))
}
var serverEntry *protocol.ServerEntry
err := json.Unmarshal(serverEntryJson, &serverEntry)
if err != nil {
common.ContextError(err)
}
// Only prune sufficiently old server entries. This mitigates the case where
// stale data in psiphond will incorrectly identify brand new servers as
// being invalid/deleted.
serverEntryLocalTimestamp, err := time.Parse(time.RFC3339, serverEntry.LocalTimestamp)
if err != nil {
common.ContextError(err)
}
if serverEntryLocalTimestamp.Add(minimumAgeForPruning).After(time.Now()) {
return nil
}
// Handle the server IP recycle case where multiple serverEntryTags records
// refer to the same server IP. Only delete the server entry record when its
// tag matches the pruned tag. Otherwise, the server entry record is
// associated with another tag. The pruned tag is still deleted.
deleteServerEntry := (serverEntry.Tag == serverEntryTag)
err = serverEntryTags.delete(serverEntryTagBytes)
if err != nil {
common.ContextError(err)
}
if deleteServerEntry {
err = serverEntries.delete(serverEntryID)
if err != nil {
common.ContextError(err)
}
affinityServerEntryID := keyValues.get(datastoreAffinityServerEntryIDKey)
if 0 == bytes.Compare(affinityServerEntryID, serverEntryID) {
err = keyValues.delete(datastoreAffinityServerEntryIDKey)
if err != nil {
return common.ContextError(err)
}
}
// TODO: expose boltdb Seek functionality to skip to first matching record.
cursor := dialParameters.cursor()
defer cursor.close()
foundFirstMatch := false
for key, _ := cursor.first(); key != nil; key, _ = cursor.next() {
// Dial parameters key has serverID as a prefix; see makeDialParametersKey.
if bytes.HasPrefix(key, serverEntryID) {
foundFirstMatch = true
err := dialParameters.delete(key)
if err != nil {
return common.ContextError(err)
}
} else if foundFirstMatch {
break
}
}
}
// Tombstones prevent reimporting pruned server entries. Tombstone
// identifiers are tags, which are derived from the web server secret in
// addition to the server IP, so tombstones will not clobber recycled server
// IPs as long as new web server secrets are generated in the recycle case.
//
// Tombstones are set only for embedded server entries, as all other sources
// are expected to provide valid server entries; this also provides a fail-
// safe mechanism to restore pruned server entries through all non-embedded
// sources.
if serverEntry.LocalSource == protocol.SERVER_ENTRY_SOURCE_EMBEDDED {
err = serverEntryTombstoneTags.put(serverEntryTagBytes, []byte{1})
if err != nil {
return common.ContextError(err)
}
}
return nil
})
}
func scanServerEntries(scanner func(*protocol.ServerEntry)) error {
err := datastoreView(func(tx *datastoreTx) error {
bucket := tx.bucket(datastoreServerEntriesBucket)
cursor := bucket.cursor()
n := 0
for key, value := cursor.first(); key != nil; key, value = cursor.next() {
var serverEntry *protocol.ServerEntry
err := json.Unmarshal(value, &serverEntry)
if err != nil {
// In case of data corruption or a bug causing this condition,
// do not stop iterating.
NoticeAlert("scanServerEntries: %s", common.ContextError(err))
continue
}
scanner(serverEntry)
n += 1
if n == datastoreServerEntryFetchGCThreshold {
DoGarbageCollection()
n = 0
}
}
cursor.close()
return nil
})
if err != nil {
return common.ContextError(err)
}
return nil
}
// CountServerEntries returns a count of stored server entries.
func CountServerEntries() int {
count := 0
err := scanServerEntries(func(_ *protocol.ServerEntry) {
count += 1
})
if err != nil {
NoticeAlert("CountServerEntries failed: %s", err)
return 0
}
return count
}
// CountServerEntriesWithConstraints returns a count of stored server entries for
// the specified region and tunnel protocol limits.
func CountServerEntriesWithConstraints(
useUpstreamProxy bool,
region string,
constraints *protocolSelectionConstraints) (int, int) {
// When CountServerEntriesWithConstraints is called only
// limitTunnelProtocolState is fixed; excludeIntensive is transitory.