forked from Psiphon-Labs/psiphon-tunnel-core
-
Notifications
You must be signed in to change notification settings - Fork 1
/
controller.go
executable file
·2305 lines (1944 loc) · 80.3 KB
/
controller.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 implements the core tunnel functionality of a Psiphon client.
// The main function is RunForever, which runs a Controller that obtains lists of
// servers, establishes tunnel connections, and runs local proxies through which
// tunneled traffic may be sent.
package psiphon
import (
"context"
"fmt"
"math/rand"
"net"
"sync"
"sync/atomic"
"time"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
"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"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
lrucache "github.com/cognusion/go-cache-lru"
)
// Controller is a tunnel lifecycle coordinator. It manages lists of servers to
// connect to; establishes and monitors tunnels; and runs local proxies which
// route traffic through the tunnels.
type Controller struct {
config *Config
runCtx context.Context
stopRunning context.CancelFunc
runWaitGroup *sync.WaitGroup
connectedTunnels chan *Tunnel
failedTunnels chan *Tunnel
tunnelMutex sync.Mutex
establishedOnce bool
tunnelPoolSize int
tunnels []*Tunnel
nextTunnel int
isEstablishing bool
establishStartTime time.Time
protocolSelectionConstraints *protocolSelectionConstraints
concurrentEstablishTunnelsMutex sync.Mutex
establishConnectTunnelCount int
concurrentEstablishTunnels int
concurrentIntensiveEstablishTunnels int
peakConcurrentEstablishTunnels int
peakConcurrentIntensiveEstablishTunnels int
establishCtx context.Context
stopEstablish context.CancelFunc
establishWaitGroup *sync.WaitGroup
establishedTunnelsCount int32
candidateServerEntries chan *candidateServerEntry
untunneledDialConfig *DialConfig
untunneledSplitTunnelClassifications *lrucache.Cache
splitTunnelClassificationTTL time.Duration
splitTunnelClassificationMaxEntries int
signalFetchCommonRemoteServerList chan struct{}
signalFetchObfuscatedServerLists chan struct{}
signalDownloadUpgrade chan string
signalReportServerEntries chan *serverEntriesReportRequest
signalReportConnected chan struct{}
signalRestartEstablishing chan struct{}
serverAffinityDoneBroadcast chan struct{}
packetTunnelClient *tun.Client
packetTunnelTransport *PacketTunnelTransport
staggerMutex sync.Mutex
}
// NewController initializes a new controller.
func NewController(config *Config) (controller *Controller, err error) {
if !config.IsCommitted() {
return nil, errors.TraceNew("uncommitted config")
}
// Needed by regen, at least
rand.Seed(int64(time.Now().Nanosecond()))
// The session ID for the Psiphon server API is used across all
// tunnels established by the controller.
NoticeSessionId(config.SessionID)
untunneledDialConfig := &DialConfig{
UpstreamProxyURL: config.UpstreamProxyURL,
CustomHeaders: config.CustomHeaders,
DeviceBinder: config.deviceBinder,
DnsServerGetter: config.DnsServerGetter,
IPv6Synthesizer: config.IPv6Synthesizer,
TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
}
// Attempt to apply any valid, local stored tactics. The pre-done context
// ensures no tactics request is attempted now.
doneContext, cancelFunc := context.WithCancel(context.Background())
cancelFunc()
GetTactics(doneContext, config)
p := config.GetParameters().Get()
splitTunnelClassificationTTL :=
p.Duration(parameters.SplitTunnelClassificationTTL)
splitTunnelClassificationMaxEntries :=
p.Int(parameters.SplitTunnelClassificationMaxEntries)
controller = &Controller{
config: config,
runWaitGroup: new(sync.WaitGroup),
// connectedTunnels and failedTunnels buffer sizes are large enough to
// receive full pools of tunnels without blocking. Senders should not block.
connectedTunnels: make(chan *Tunnel, MAX_TUNNEL_POOL_SIZE),
failedTunnels: make(chan *Tunnel, MAX_TUNNEL_POOL_SIZE),
tunnelPoolSize: TUNNEL_POOL_SIZE,
tunnels: make([]*Tunnel, 0),
establishedOnce: false,
isEstablishing: false,
untunneledDialConfig: untunneledDialConfig,
untunneledSplitTunnelClassifications: lrucache.NewWithLRU(
splitTunnelClassificationTTL,
1*time.Minute,
splitTunnelClassificationMaxEntries),
// TODO: Add a buffer of 1 so we don't miss a signal while receiver is
// starting? Trade-off is potential back-to-back fetch remotes. As-is,
// establish will eventually signal another fetch remote.
signalFetchCommonRemoteServerList: make(chan struct{}),
signalFetchObfuscatedServerLists: make(chan struct{}),
signalDownloadUpgrade: make(chan string),
signalReportConnected: make(chan struct{}),
// Using a buffer of 1 to ensure there's no race between the first signal
// sent and a channel receiver initializing; a side effect is that this
// allows 1 additional scan to enqueue while a scan is in progress, possibly
// resulting in one unnecessary scan.
signalReportServerEntries: make(chan *serverEntriesReportRequest, 1),
// signalRestartEstablishing has a buffer of 1 to ensure sending the
// signal doesn't block and receiving won't miss a signal.
signalRestartEstablishing: make(chan struct{}, 1),
}
if config.PacketTunnelTunFileDescriptor > 0 {
// Run a packet tunnel client. The lifetime of the tun.Client is the
// lifetime of the Controller, so it exists across tunnel establishments
// and reestablishments. The PacketTunnelTransport provides a layer
// that presents a continuosuly existing transport to the tun.Client;
// it's set to use new SSH channels after new SSH tunnel establishes.
packetTunnelTransport := NewPacketTunnelTransport()
packetTunnelClient, err := tun.NewClient(&tun.ClientConfig{
Logger: NoticeCommonLogger(),
TunFileDescriptor: config.PacketTunnelTunFileDescriptor,
Transport: packetTunnelTransport,
})
if err != nil {
return nil, errors.Trace(err)
}
controller.packetTunnelClient = packetTunnelClient
controller.packetTunnelTransport = packetTunnelTransport
}
return controller, nil
}
// Run executes the controller. Run exits if a controller
// component fails or the parent context is canceled.
func (controller *Controller) Run(ctx context.Context) {
pprofRun()
// Ensure fresh repetitive notice state for each run, so the
// client will always get an AvailableEgressRegions notice,
// an initial instance of any repetitive error notice, etc.
ResetRepetitiveNotices()
runCtx, stopRunning := context.WithCancel(ctx)
defer stopRunning()
controller.runCtx = runCtx
controller.stopRunning = stopRunning
// Start components
// TODO: IPv6 support
var listenIP string
if controller.config.ListenInterface == "" {
listenIP = "127.0.0.1"
} else if controller.config.ListenInterface == "any" {
listenIP = "0.0.0.0"
} else {
IPv4Address, _, err := common.GetInterfaceIPAddresses(controller.config.ListenInterface)
if err == nil && IPv4Address == nil {
err = fmt.Errorf("no IPv4 address for interface %s", controller.config.ListenInterface)
}
if err != nil {
NoticeError("error getting listener IP: %v", errors.Trace(err))
return
}
listenIP = IPv4Address.String()
}
if !controller.config.DisableLocalSocksProxy {
socksProxy, err := NewSocksProxy(controller.config, controller, listenIP)
if err != nil {
NoticeError("error initializing local SOCKS proxy: %v", errors.Trace(err))
return
}
defer socksProxy.Close()
}
if !controller.config.DisableLocalHTTPProxy {
httpProxy, err := NewHttpProxy(controller.config, controller, listenIP)
if err != nil {
NoticeError("error initializing local HTTP proxy: %v", errors.Trace(err))
return
}
defer httpProxy.Close()
}
if !controller.config.DisableRemoteServerListFetcher {
if controller.config.RemoteServerListURLs != nil {
controller.runWaitGroup.Add(1)
go controller.remoteServerListFetcher(
"common",
FetchCommonRemoteServerList,
controller.signalFetchCommonRemoteServerList)
}
if controller.config.ObfuscatedServerListRootURLs != nil {
controller.runWaitGroup.Add(1)
go controller.remoteServerListFetcher(
"obfuscated",
FetchObfuscatedServerLists,
controller.signalFetchObfuscatedServerLists)
}
}
if controller.config.UpgradeDownloadURLs != nil {
controller.runWaitGroup.Add(1)
go controller.upgradeDownloader()
}
controller.runWaitGroup.Add(1)
go controller.serverEntriesReporter()
controller.runWaitGroup.Add(1)
go controller.connectedReporter()
controller.runWaitGroup.Add(1)
go controller.establishTunnelWatcher()
controller.runWaitGroup.Add(1)
go controller.runTunnels()
if controller.packetTunnelClient != nil {
controller.packetTunnelClient.Start()
}
// Wait while running
<-controller.runCtx.Done()
NoticeInfo("controller stopped")
if controller.packetTunnelClient != nil {
controller.packetTunnelClient.Stop()
}
// All workers -- runTunnels, establishment workers, and auxilliary
// workers such as fetch remote server list and untunneled uprade
// download -- operate with the controller run context and will all
// be interrupted when the run context is done.
controller.runWaitGroup.Wait()
NoticeInfo("exiting controller")
NoticeExiting()
}
// SignalComponentFailure notifies the controller that an associated component has failed.
// This will terminate the controller.
func (controller *Controller) SignalComponentFailure() {
NoticeWarning("controller shutdown due to component failure")
controller.stopRunning()
}
// SetDynamicConfig overrides the sponsor ID and authorizations fields of the
// Controller config with the input values. The new values will be used in the
// next tunnel connection.
func (controller *Controller) SetDynamicConfig(sponsorID string, authorizations []string) {
controller.config.SetDynamicConfig(sponsorID, authorizations)
}
// TerminateNextActiveTunnel terminates the active tunnel, which will initiate
// establishment of a new tunnel.
func (controller *Controller) TerminateNextActiveTunnel() {
tunnel := controller.getNextActiveTunnel()
if tunnel != nil {
controller.SignalTunnelFailure(tunnel)
NoticeInfo("terminated tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
}
}
// ExportExchangePayload creates a payload for client-to-client server
// connection info exchange. See the comment for psiphon.ExportExchangePayload
// for more details.
func (controller *Controller) ExportExchangePayload() string {
return ExportExchangePayload(controller.config)
}
// ImportExchangePayload imports a payload generated by ExportExchangePayload.
// See the comment for psiphon.ImportExchangePayload for more details about
// the import.
//
// When the import is successful, a signal is set to trigger a restart any
// establishment in progress. This will cause the newly imported server entry
// to be prioritized, which it otherwise would not be in later establishment
// rounds. The establishment process continues after ImportExchangePayload
// returns.
//
// If the client already has a connected tunnel, or a tunnel connection is
// established concurrently with the import, the signal has no effect as the
// overall goal is establish _any_ connection.
func (controller *Controller) ImportExchangePayload(payload string) bool {
// Race condition: if a new tunnel connection is established concurrently
// with the import, either that tunnel's server entry of the imported server
// entry may end up as the affinity server.
ok := ImportExchangePayload(controller.config, payload)
if !ok {
return false
}
select {
case controller.signalRestartEstablishing <- struct{}{}:
default:
}
return true
}
// remoteServerListFetcher fetches an out-of-band list of server entries
// for more tunnel candidates. It fetches when signalled, with retries
// on failure.
func (controller *Controller) remoteServerListFetcher(
name string,
fetcher RemoteServerListFetcher,
signal <-chan struct{}) {
defer controller.runWaitGroup.Done()
var lastFetchTime time.Time
fetcherLoop:
for {
// Wait for a signal before fetching
select {
case <-signal:
case <-controller.runCtx.Done():
break fetcherLoop
}
// Skip fetch entirely (i.e., send no request at all, even when ETag would save
// on response size) when a recent fetch was successful
stalePeriod := controller.config.GetParameters().Get().Duration(
parameters.FetchRemoteServerListStalePeriod)
if !lastFetchTime.IsZero() &&
lastFetchTime.Add(stalePeriod).After(time.Now()) {
continue
}
retryLoop:
for attempt := 0; ; attempt++ {
// Don't attempt to fetch while there is no network connectivity,
// to avoid alert notice noise.
if !WaitForNetworkConnectivity(
controller.runCtx,
controller.config.NetworkConnectivityChecker) {
break fetcherLoop
}
// Pick any active tunnel and make the next fetch attempt. If there's
// no active tunnel, the untunneledDialConfig will be used.
tunnel := controller.getNextActiveTunnel()
err := fetcher(
controller.runCtx,
controller.config,
attempt,
tunnel,
controller.untunneledDialConfig)
if err == nil {
lastFetchTime = time.Now()
break retryLoop
}
NoticeWarning("failed to fetch %s remote server list: %v",
name, errors.Trace(err))
retryPeriod := controller.config.GetParameters().Get().Duration(
parameters.FetchRemoteServerListRetryPeriod)
timer := time.NewTimer(retryPeriod)
select {
case <-timer.C:
case <-controller.runCtx.Done():
timer.Stop()
break fetcherLoop
}
}
}
NoticeInfo("exiting %s remote server list fetcher", name)
}
// upgradeDownloader makes periodic attempts to complete a client upgrade
// download. DownloadUpgrade() is resumable, so each attempt has potential for
// getting closer to completion, even in conditions where the download or
// tunnel is repeatedly interrupted.
// An upgrade download is triggered by either a handshake response indicating
// that a new version is available; or after failing to connect, in which case
// it's useful to check, out-of-band, for an upgrade with new circumvention
// capabilities.
// Once the download operation completes successfully, the downloader exits
// and is not run again: either there is not a newer version, or the upgrade
// has been downloaded and is ready to be applied.
// We're assuming that the upgrade will be applied and the entire system
// restarted before another upgrade is to be downloaded.
//
// TODO: refactor upgrade downloader and remote server list fetcher to use
// common code (including the resumable download routines).
//
func (controller *Controller) upgradeDownloader() {
defer controller.runWaitGroup.Done()
var lastDownloadTime time.Time
downloadLoop:
for {
// Wait for a signal before downloading
var handshakeVersion string
select {
case handshakeVersion = <-controller.signalDownloadUpgrade:
case <-controller.runCtx.Done():
break downloadLoop
}
stalePeriod := controller.config.GetParameters().Get().Duration(
parameters.FetchUpgradeStalePeriod)
// Unless handshake is explicitly advertizing a new version, skip
// checking entirely when a recent download was successful.
if handshakeVersion == "" &&
!lastDownloadTime.IsZero() &&
lastDownloadTime.Add(stalePeriod).After(time.Now()) {
continue
}
retryLoop:
for attempt := 0; ; attempt++ {
// Don't attempt to download while there is no network connectivity,
// to avoid alert notice noise.
if !WaitForNetworkConnectivity(
controller.runCtx,
controller.config.NetworkConnectivityChecker) {
break downloadLoop
}
// Pick any active tunnel and make the next download attempt. If there's
// no active tunnel, the untunneledDialConfig will be used.
tunnel := controller.getNextActiveTunnel()
err := DownloadUpgrade(
controller.runCtx,
controller.config,
attempt,
handshakeVersion,
tunnel,
controller.untunneledDialConfig)
if err == nil {
lastDownloadTime = time.Now()
break retryLoop
}
NoticeWarning("failed to download upgrade: %v", errors.Trace(err))
timeout := controller.config.GetParameters().Get().Duration(
parameters.FetchUpgradeRetryPeriod)
timer := time.NewTimer(timeout)
select {
case <-timer.C:
case <-controller.runCtx.Done():
timer.Stop()
break downloadLoop
}
}
}
NoticeInfo("exiting upgrade downloader")
}
type serverEntriesReportRequest struct {
constraints *protocolSelectionConstraints
awaitResponse chan *serverEntriesReportResponse
}
type serverEntriesReportResponse struct {
err error
candidates int
initialCandidates int
initialCandidatesAnyEgressRegion int
availableEgressRegions []string
}
// serverEntriesReporter performs scans over all server entries to report on
// available tunnel candidates, subject to protocol selection constraints, and
// available egress regions.
//
// Because scans may be slow, depending on the client device and server entry
// list size, serverEntriesReporter is used to perform asychronous, background
// operations that would otherwise block establishment. This includes emitting
// diagnotic notices that are informational (CandidateServers) or which do not
// need to emit before establishment starts (AvailableEgressRegions).
//
// serverEntriesReporter also serves to combine these scans, which would
// otherwise be logically independent, due to the performance impact of scans.
//
// The underlying datastore implementation _may_ block write transactions
// while there are open read transactions. For example, bolt write
// transactions which need to re-map the data file (when the datastore grows)
// will block on open read transactions. In these scenarios, a slow scan will
// still block other operations.
//
// serverEntriesReporter runs beyond the establishment phase, since it's
// important for notices such as AvailableEgressRegions to eventually emit
// even if already established. serverEntriesReporter scans are cancellable,
// so controller shutdown is not blocked by slow scans.
//
// In some special cases, establishment cannot begin without candidate counts
// up front. In these cases only, the request contains a non-nil
// awaitResponse, a channel which is used by the requester to block until the
// scan is complete and the candidate counts are available.
func (controller *Controller) serverEntriesReporter() {
defer controller.runWaitGroup.Done()
loop:
for {
var request *serverEntriesReportRequest
select {
case request = <-controller.signalReportServerEntries:
case <-controller.runCtx.Done():
break loop
}
egressRegion := controller.config.EgressRegion
constraints := request.constraints
var response serverEntriesReportResponse
regions := make(map[string]bool)
callback := func(serverEntry *protocol.ServerEntry) bool {
// In establishment, excludeIntensive depends on what set of protocols are
// already being dialed. For these reports, don't exclude intensive
// protocols as any intensive candidate can always be an available
// candidate at some point.
excludeIntensive := false
isInitialCandidate := constraints.isInitialCandidate(excludeIntensive, serverEntry)
isCandidate := constraints.isCandidate(excludeIntensive, serverEntry)
if isInitialCandidate {
response.initialCandidatesAnyEgressRegion += 1
}
if egressRegion == "" || serverEntry.Region == egressRegion {
if isInitialCandidate {
response.initialCandidates += 1
}
if isCandidate {
response.candidates += 1
}
}
isAvailable := isCandidate
if constraints.hasInitialProtocols() {
// Available egress regions is subject to an initial limit constraint, if
// present: see AvailableEgressRegions comment in launchEstablishing.
isAvailable = isInitialCandidate
}
if isAvailable {
// Ignore server entries with no region field.
if serverEntry.Region != "" {
regions[serverEntry.Region] = true
}
}
select {
case <-controller.runCtx.Done():
// Don't block controller shutdown: cancel the scan.
return false
default:
return true
}
}
startTime := time.Now()
response.err = ScanServerEntries(callback)
// Report this duration in CandidateServers as an indication of datastore
// performance.
duration := time.Since(startTime)
response.availableEgressRegions = make([]string, 0, len(regions))
for region := range regions {
response.availableEgressRegions = append(response.availableEgressRegions, region)
}
if response.err != nil {
// For diagnostics, we'll post this even when cancelled due to shutdown.
NoticeWarning("ScanServerEntries failed: %v", errors.Trace(response.err))
// Continue and send error reponse. Clear any partial data to avoid
// misuse.
response.candidates = 0
response.initialCandidates = 0
response.initialCandidatesAnyEgressRegion = 0
response.availableEgressRegions = []string{}
}
if request.awaitResponse != nil {
select {
case request.awaitResponse <- &response:
case <-controller.runCtx.Done():
// The receiver may be gone when shutting down.
}
}
if response.err == nil {
NoticeCandidateServers(
controller.config.EgressRegion,
controller.protocolSelectionConstraints,
response.initialCandidates,
response.candidates,
duration)
NoticeAvailableEgressRegions(
response.availableEgressRegions)
}
}
NoticeInfo("exiting server entries reporter")
}
// signalServerEntriesReporter triggers a new server entry report. Set
// request.awaitResponse to obtain the report output. When awaitResponse is
// set, signalServerEntriesReporter blocks until the reporter receives the
// request, guaranteeing the new report runs. Otherwise, the report is
// considered to be informational and may or may not run, depending on whether
// another run is already in progress.
func (controller *Controller) signalServerEntriesReporter(request *serverEntriesReportRequest) {
if request.awaitResponse == nil {
select {
case controller.signalReportServerEntries <- request:
default:
}
} else {
controller.signalReportServerEntries <- request
}
}
// connectedReporter sends periodic "connected" requests to the Psiphon API.
// These requests are for server-side unique user stats calculation. See the
// comment in DoConnectedRequest for a description of the request mechanism.
//
// To correctly count daily unique users, only one connected request is made
// across all simultaneous multi-tunnels; and the connected request is
// repeated every 24h.
//
// The signalReportConnected mechanism is used to trigger a connected request
// immediately after a reconnect. While strictly only one connected request
// per 24h is required in order to count daily unique users, the connected
// request also delivers the establishment duration metric (which includes
// time elapsed performing the handshake request) and additional fragmentation
// metrics; these metrics are measured for each tunnel.
func (controller *Controller) connectedReporter() {
defer controller.runWaitGroup.Done()
// session is nil when DisableApi is set
if controller.config.DisableApi {
return
}
loop:
for {
select {
case <-controller.signalReportConnected:
// Make the initial connected request
case <-controller.runCtx.Done():
break loop
}
// Pick any active tunnel and make the next connected request. No error is
// logged if there's no active tunnel, as that's not an unexpected
// condition.
reported := false
tunnel := controller.getNextActiveTunnel()
if tunnel != nil {
err := tunnel.serverContext.DoConnectedRequest()
if err == nil {
reported = true
} else {
NoticeWarning("failed to make connected request: %v",
errors.Trace(err))
}
}
// Schedule the next connected request and wait. This duration is not a
// dynamic ClientParameter as the daily unique user stats logic specifically
// requires a "connected" request no more or less often than every 24h.
var duration time.Duration
if reported {
duration = 24 * time.Hour
} else {
duration = controller.config.GetParameters().Get().Duration(
parameters.PsiphonAPIConnectedRequestRetryPeriod)
}
timer := time.NewTimer(duration)
doBreak := false
select {
case <-controller.signalReportConnected:
case <-timer.C:
// Make another connected request
case <-controller.runCtx.Done():
doBreak = true
}
timer.Stop()
if doBreak {
break loop
}
}
NoticeInfo("exiting connected reporter")
}
func (controller *Controller) signalConnectedReporter() {
// session is nil when DisableApi is set
if controller.config.DisableApi {
return
}
select {
case controller.signalReportConnected <- struct{}{}:
default:
}
}
// establishTunnelWatcher terminates the controller if a tunnel
// has not been established in the configured time period. This
// is regardless of how many tunnels are presently active -- meaning
// that if an active tunnel was established and lost the controller
// is left running (to re-establish).
func (controller *Controller) establishTunnelWatcher() {
defer controller.runWaitGroup.Done()
timeout := controller.config.GetParameters().Get().Duration(
parameters.EstablishTunnelTimeout)
if timeout > 0 {
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-timer.C:
if !controller.hasEstablishedOnce() {
NoticeEstablishTunnelTimeout(timeout)
controller.SignalComponentFailure()
}
case <-controller.runCtx.Done():
}
}
NoticeInfo("exiting establish tunnel watcher")
}
// runTunnels is the controller tunnel management main loop. It starts and stops
// establishing tunnels based on the target tunnel pool size and the current size
// of the pool. Tunnels are established asynchronously using worker goroutines.
//
// When there are no server entries for the target region/protocol, the
// establishCandidateGenerator will yield no candidates and wait before
// trying again. In the meantime, a remote server entry fetch may supply
// valid candidates.
//
// When a tunnel is established, it's added to the active pool. The tunnel's
// operateTunnel goroutine monitors the tunnel.
//
// When a tunnel fails, it's removed from the pool and the establish process is
// restarted to fill the pool.
func (controller *Controller) runTunnels() {
defer controller.runWaitGroup.Done()
// Start running
controller.startEstablishing()
loop:
for {
select {
case <-controller.signalRestartEstablishing:
// signalRestartEstablishing restarts any establishment in progress. One
// use case for this is to prioritize a newly imported, exchanged server
// entry, which will be in the affinity position.
//
// It's possible for another connection to establish concurrent to signalling;
// since the overall goal remains to establish _any_ connection, we accept that
// in some cases the exchanged server entry may not get used.
if controller.isEstablishing {
controller.stopEstablishing()
controller.startEstablishing()
}
case failedTunnel := <-controller.failedTunnels:
NoticeWarning("tunnel failed: %s", failedTunnel.dialParams.ServerEntry.GetDiagnosticID())
controller.terminateTunnel(failedTunnel)
// Clear the reference to this tunnel before calling startEstablishing,
// which will invoke a garbage collection.
failedTunnel = nil
// Concurrency note: only this goroutine may call startEstablishing/stopEstablishing,
// which reference controller.isEstablishing.
controller.startEstablishing()
case connectedTunnel := <-controller.connectedTunnels:
// Tunnel establishment has two phases: connection and activation.
//
// Connection is run concurrently by the establishTunnelWorkers, to minimize
// delay when it's not yet known which server and protocol will be available
// and unblocked.
//
// Activation is run serially, here, to minimize the overhead of making a
// handshake request and starting the operateTunnel management worker for a
// tunnel which may be discarded.
//
// When the active tunnel will complete establishment, establishment is
// stopped before activation. This interrupts all connecting tunnels and
// garbage collects their memory. The purpose is to minimize memory
// pressure when the handshake request is made. In the unlikely case that the
// handshake fails, establishment is restarted.
//
// Any delays in stopEstablishing will delay the handshake for the last
// active tunnel.
//
// In the typical case of tunnelPoolSize of 1, only a single handshake is
// performed and the homepages notices file, when used, will not be modifed
// after the NoticeTunnels(1) [i.e., connected] until NoticeTunnels(0) [i.e.,
// disconnected]. For tunnelPoolSize > 1, serial handshakes only ensures that
// each set of emitted NoticeHomepages is contiguous.
active, outstanding := controller.numTunnels()
// discardTunnel will be true here when already fully established.
discardTunnel := (outstanding <= 0)
isFirstTunnel := (active == 0)
isLastTunnel := (outstanding == 1)
if !discardTunnel {
if isLastTunnel {
controller.stopEstablishing()
}
err := connectedTunnel.Activate(controller.runCtx, controller)
if err != nil {
NoticeWarning("failed to activate %s: %v",
connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(),
errors.Trace(err))
discardTunnel = true
} else {
// It's unlikely that registerTunnel will fail, since only this goroutine
// calls registerTunnel -- and after checking numTunnels; so failure is not
// expected.
if !controller.registerTunnel(connectedTunnel) {
NoticeWarning("failed to register %s: %v",
connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(),
errors.Trace(err))
discardTunnel = true
}
}
// May need to replace this tunnel
if isLastTunnel && discardTunnel {
controller.startEstablishing()
}
}
if discardTunnel {
controller.discardTunnel(connectedTunnel)
// Clear the reference to this discarded tunnel and immediately run
// a garbage collection to reclaim its memory.
connectedTunnel = nil
DoGarbageCollection()
// Skip the rest of this case
break
}
atomic.AddInt32(&controller.establishedTunnelsCount, 1)
NoticeActiveTunnel(
connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(),
connectedTunnel.dialParams.TunnelProtocol,
connectedTunnel.dialParams.ServerEntry.SupportsSSHAPIRequests())
if isFirstTunnel {
// Signal a connected request on each 1st tunnel establishment. For
// multi-tunnels, the session is connected as long as at least one
// tunnel is established.
controller.signalConnectedReporter()
// If the handshake indicated that a new client version is available,
// trigger an upgrade download.
// Note: serverContext is nil when DisableApi is set
if connectedTunnel.serverContext != nil &&
connectedTunnel.serverContext.clientUpgradeVersion != "" {
handshakeVersion := connectedTunnel.serverContext.clientUpgradeVersion
select {
case controller.signalDownloadUpgrade <- handshakeVersion:
default:
}
}
}
// Set the new tunnel as the transport for the packet tunnel. The packet tunnel
// client remains up when reestablishing, but no packets are relayed while there
// is no connected tunnel. UseTunnel will establish a new packet tunnel SSH
// channel over the new SSH tunnel and configure the packet tunnel client to use
// the new SSH channel as its transport.
//
// Note: as is, this logic is suboptimal for tunnelPoolSize > 1, as this would
// continuously initialize new packet tunnel sessions for each established
// server. For now, config validation requires tunnelPoolSize == 1 when
// the packet tunnel is used.
if controller.packetTunnelTransport != nil {
controller.packetTunnelTransport.UseTunnel(connectedTunnel)
}
if controller.isFullyEstablished() {
controller.stopEstablishing()
}