controller.go 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. // Package psiphon implements the core tunnel functionality of a Psiphon client.
  20. // The main function is RunForever, which runs a Controller that obtains lists of
  21. // servers, establishes tunnel connections, and runs local proxies through which
  22. // tunneled traffic may be sent.
  23. package psiphon
  24. import (
  25. "context"
  26. "fmt"
  27. "math/rand"
  28. "net"
  29. "runtime"
  30. "sync"
  31. "sync/atomic"
  32. "time"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/resolver"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  40. lrucache "github.com/cognusion/go-cache-lru"
  41. )
  42. // Controller is a tunnel lifecycle coordinator. It manages lists of servers to
  43. // connect to; establishes and monitors tunnels; and runs local proxies which
  44. // route traffic through the tunnels.
  45. type Controller struct {
  46. config *Config
  47. runCtx context.Context
  48. stopRunning context.CancelFunc
  49. runWaitGroup *sync.WaitGroup
  50. connectedTunnels chan *Tunnel
  51. failedTunnels chan *Tunnel
  52. tunnelMutex sync.Mutex
  53. establishedOnce bool
  54. tunnelPoolSize int
  55. tunnels []*Tunnel
  56. nextTunnel int
  57. isEstablishing bool
  58. establishStartTime time.Time
  59. protocolSelectionConstraints *protocolSelectionConstraints
  60. concurrentEstablishTunnelsMutex sync.Mutex
  61. establishConnectTunnelCount int
  62. concurrentEstablishTunnels int
  63. concurrentIntensiveEstablishTunnels int
  64. peakConcurrentEstablishTunnels int
  65. peakConcurrentIntensiveEstablishTunnels int
  66. establishCtx context.Context
  67. stopEstablish context.CancelFunc
  68. establishWaitGroup *sync.WaitGroup
  69. establishedTunnelsCount int32
  70. candidateServerEntries chan *candidateServerEntry
  71. untunneledDialConfig *DialConfig
  72. untunneledSplitTunnelClassifications *lrucache.Cache
  73. splitTunnelClassificationTTL time.Duration
  74. splitTunnelClassificationMaxEntries int
  75. signalFetchCommonRemoteServerList chan struct{}
  76. signalFetchObfuscatedServerLists chan struct{}
  77. signalDownloadUpgrade chan string
  78. signalReportServerEntries chan *serverEntriesReportRequest
  79. signalReportConnected chan struct{}
  80. signalRestartEstablishing chan struct{}
  81. serverAffinityDoneBroadcast chan struct{}
  82. packetTunnelClient *tun.Client
  83. packetTunnelTransport *PacketTunnelTransport
  84. staggerMutex sync.Mutex
  85. resolver *resolver.Resolver
  86. steeringIPCache *lrucache.Cache
  87. }
  88. // NewController initializes a new controller.
  89. func NewController(config *Config) (controller *Controller, err error) {
  90. if !config.IsCommitted() {
  91. return nil, errors.TraceNew("uncommitted config")
  92. }
  93. // Needed by regen, at least
  94. rand.Seed(int64(time.Now().Nanosecond()))
  95. // The session ID for the Psiphon server API is used across all
  96. // tunnels established by the controller.
  97. NoticeSessionId(config.SessionID)
  98. // Attempt to apply any valid, local stored tactics. The pre-done context
  99. // ensures no tactics request is attempted now.
  100. doneContext, cancelFunc := context.WithCancel(context.Background())
  101. cancelFunc()
  102. GetTactics(doneContext, config)
  103. p := config.GetParameters().Get()
  104. splitTunnelClassificationTTL :=
  105. p.Duration(parameters.SplitTunnelClassificationTTL)
  106. splitTunnelClassificationMaxEntries :=
  107. p.Int(parameters.SplitTunnelClassificationMaxEntries)
  108. steeringIPCacheTTL := p.Duration(parameters.SteeringIPCacheTTL)
  109. steeringIPCacheMaxEntries := p.Int(parameters.SteeringIPCacheMaxEntries)
  110. controller = &Controller{
  111. config: config,
  112. runWaitGroup: new(sync.WaitGroup),
  113. // connectedTunnels and failedTunnels buffer sizes are large enough to
  114. // receive full pools of tunnels without blocking. Senders should not block.
  115. connectedTunnels: make(chan *Tunnel, MAX_TUNNEL_POOL_SIZE),
  116. failedTunnels: make(chan *Tunnel, MAX_TUNNEL_POOL_SIZE),
  117. tunnelPoolSize: TUNNEL_POOL_SIZE,
  118. tunnels: make([]*Tunnel, 0),
  119. establishedOnce: false,
  120. isEstablishing: false,
  121. untunneledSplitTunnelClassifications: lrucache.NewWithLRU(
  122. splitTunnelClassificationTTL,
  123. 1*time.Minute,
  124. splitTunnelClassificationMaxEntries),
  125. // TODO: Add a buffer of 1 so we don't miss a signal while receiver is
  126. // starting? Trade-off is potential back-to-back fetch remotes. As-is,
  127. // establish will eventually signal another fetch remote.
  128. signalFetchCommonRemoteServerList: make(chan struct{}),
  129. signalFetchObfuscatedServerLists: make(chan struct{}),
  130. signalDownloadUpgrade: make(chan string),
  131. signalReportConnected: make(chan struct{}),
  132. // Using a buffer of 1 to ensure there's no race between the first signal
  133. // sent and a channel receiver initializing; a side effect is that this
  134. // allows 1 additional scan to enqueue while a scan is in progress, possibly
  135. // resulting in one unnecessary scan.
  136. signalReportServerEntries: make(chan *serverEntriesReportRequest, 1),
  137. // signalRestartEstablishing has a buffer of 1 to ensure sending the
  138. // signal doesn't block and receiving won't miss a signal.
  139. signalRestartEstablishing: make(chan struct{}, 1),
  140. steeringIPCache: lrucache.NewWithLRU(
  141. steeringIPCacheTTL,
  142. 1*time.Minute,
  143. steeringIPCacheMaxEntries),
  144. }
  145. // Initialize untunneledDialConfig, used by untunneled dials including
  146. // remote server list and upgrade downloads.
  147. controller.untunneledDialConfig = &DialConfig{
  148. UpstreamProxyURL: controller.config.UpstreamProxyURL,
  149. CustomHeaders: controller.config.CustomHeaders,
  150. DeviceBinder: controller.config.deviceBinder,
  151. IPv6Synthesizer: controller.config.IPv6Synthesizer,
  152. ResolveIP: func(ctx context.Context, hostname string) ([]net.IP, error) {
  153. // Note: when domain fronting would be used for untunneled dials a
  154. // copy of untunneledDialConfig should be used instead, which
  155. // redefines ResolveIP such that the corresponding fronting
  156. // provider ID is passed into UntunneledResolveIP to enable the use
  157. // of pre-resolved IPs.
  158. IPs, err := UntunneledResolveIP(
  159. ctx, controller.config, controller.resolver, hostname, "")
  160. if err != nil {
  161. return nil, errors.Trace(err)
  162. }
  163. return IPs, nil
  164. },
  165. TrustedCACertificatesFilename: controller.config.TrustedCACertificatesFilename,
  166. }
  167. if config.PacketTunnelTunFileDescriptor > 0 {
  168. // Run a packet tunnel client. The lifetime of the tun.Client is the
  169. // lifetime of the Controller, so it exists across tunnel establishments
  170. // and reestablishments. The PacketTunnelTransport provides a layer
  171. // that presents a continuosuly existing transport to the tun.Client;
  172. // it's set to use new SSH channels after new SSH tunnel establishes.
  173. packetTunnelTransport := NewPacketTunnelTransport()
  174. packetTunnelClient, err := tun.NewClient(&tun.ClientConfig{
  175. Logger: NoticeCommonLogger(),
  176. TunFileDescriptor: config.PacketTunnelTunFileDescriptor,
  177. TransparentDNSIPv4Address: config.PacketTunnelTransparentDNSIPv4Address,
  178. TransparentDNSIPv6Address: config.PacketTunnelTransparentDNSIPv6Address,
  179. Transport: packetTunnelTransport,
  180. })
  181. if err != nil {
  182. return nil, errors.Trace(err)
  183. }
  184. controller.packetTunnelClient = packetTunnelClient
  185. controller.packetTunnelTransport = packetTunnelTransport
  186. }
  187. return controller, nil
  188. }
  189. // Run executes the controller. Run exits if a controller
  190. // component fails or the parent context is canceled.
  191. func (controller *Controller) Run(ctx context.Context) {
  192. if controller.config.LimitCPUThreads {
  193. runtime.GOMAXPROCS(1)
  194. }
  195. pprofRun()
  196. // Ensure fresh repetitive notice state for each run, so the
  197. // client will always get an AvailableEgressRegions notice,
  198. // an initial instance of any repetitive error notice, etc.
  199. ResetRepetitiveNotices()
  200. runCtx, stopRunning := context.WithCancel(ctx)
  201. defer stopRunning()
  202. controller.runCtx = runCtx
  203. controller.stopRunning = stopRunning
  204. // Start components
  205. // Initialize a single resolver to be used by all dials. Sharing a single
  206. // resolver ensures cached results are shared, and that network state
  207. // query overhead is amortized over all dials. Multiple dials can resolve
  208. // domain concurrently.
  209. //
  210. // config.SetResolver makes this resolver available to MakeDialParameters.
  211. controller.resolver = NewResolver(controller.config, true)
  212. defer controller.resolver.Stop()
  213. controller.config.SetResolver(controller.resolver)
  214. // Maintain a cache of steering IPs to be applied to dials. A steering IP
  215. // is an alternate dial IP; for example, steering IPs may be specified by
  216. // a CDN service and used to load balance CDN traffic.
  217. controller.steeringIPCache.Flush()
  218. // TODO: IPv6 support
  219. var listenIP string
  220. if controller.config.ListenInterface == "" {
  221. listenIP = "127.0.0.1"
  222. } else if controller.config.ListenInterface == "any" {
  223. listenIP = "0.0.0.0"
  224. } else {
  225. IPv4Address, _, err := common.GetInterfaceIPAddresses(controller.config.ListenInterface)
  226. if err == nil && IPv4Address == nil {
  227. err = fmt.Errorf("no IPv4 address for interface %s", controller.config.ListenInterface)
  228. }
  229. if err != nil {
  230. NoticeError("error getting listener IP: %v", errors.Trace(err))
  231. return
  232. }
  233. listenIP = IPv4Address.String()
  234. }
  235. if !controller.config.DisableLocalSocksProxy {
  236. socksProxy, err := NewSocksProxy(controller.config, controller, listenIP)
  237. if err != nil {
  238. NoticeError("error initializing local SOCKS proxy: %v", errors.Trace(err))
  239. return
  240. }
  241. defer socksProxy.Close()
  242. }
  243. if !controller.config.DisableLocalHTTPProxy {
  244. httpProxy, err := NewHttpProxy(controller.config, controller, listenIP)
  245. if err != nil {
  246. NoticeError("error initializing local HTTP proxy: %v", errors.Trace(err))
  247. return
  248. }
  249. defer httpProxy.Close()
  250. }
  251. if !controller.config.DisableRemoteServerListFetcher {
  252. if controller.config.RemoteServerListURLs != nil {
  253. controller.runWaitGroup.Add(1)
  254. go controller.remoteServerListFetcher(
  255. "common",
  256. FetchCommonRemoteServerList,
  257. controller.signalFetchCommonRemoteServerList)
  258. }
  259. if controller.config.ObfuscatedServerListRootURLs != nil {
  260. controller.runWaitGroup.Add(1)
  261. go controller.remoteServerListFetcher(
  262. "obfuscated",
  263. FetchObfuscatedServerLists,
  264. controller.signalFetchObfuscatedServerLists)
  265. }
  266. }
  267. if controller.config.EnableUpgradeDownload {
  268. controller.runWaitGroup.Add(1)
  269. go controller.upgradeDownloader()
  270. }
  271. controller.runWaitGroup.Add(1)
  272. go controller.serverEntriesReporter()
  273. controller.runWaitGroup.Add(1)
  274. go controller.connectedReporter()
  275. controller.runWaitGroup.Add(1)
  276. go controller.establishTunnelWatcher()
  277. controller.runWaitGroup.Add(1)
  278. go controller.runTunnels()
  279. if controller.packetTunnelClient != nil {
  280. controller.packetTunnelClient.Start()
  281. }
  282. // Wait while running
  283. <-controller.runCtx.Done()
  284. NoticeInfo("controller stopped")
  285. if controller.packetTunnelClient != nil {
  286. controller.packetTunnelClient.Stop()
  287. }
  288. // All workers -- runTunnels, establishment workers, and auxilliary
  289. // workers such as fetch remote server list and untunneled uprade
  290. // download -- operate with the controller run context and will all
  291. // be interrupted when the run context is done.
  292. controller.runWaitGroup.Wait()
  293. NoticeInfo("exiting controller")
  294. NoticeExiting()
  295. }
  296. // SignalComponentFailure notifies the controller that an associated component has failed.
  297. // This will terminate the controller.
  298. func (controller *Controller) SignalComponentFailure() {
  299. NoticeWarning("controller shutdown due to component failure")
  300. controller.stopRunning()
  301. }
  302. // SetDynamicConfig overrides the sponsor ID and authorizations fields of the
  303. // Controller config with the input values. The new values will be used in the
  304. // next tunnel connection.
  305. func (controller *Controller) SetDynamicConfig(sponsorID string, authorizations []string) {
  306. controller.config.SetDynamicConfig(sponsorID, authorizations)
  307. }
  308. // TerminateNextActiveTunnel terminates the active tunnel, which will initiate
  309. // establishment of a new tunnel.
  310. func (controller *Controller) TerminateNextActiveTunnel() {
  311. tunnel := controller.getNextActiveTunnel()
  312. if tunnel != nil {
  313. controller.SignalTunnelFailure(tunnel)
  314. NoticeInfo("terminated tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  315. }
  316. }
  317. // ExportExchangePayload creates a payload for client-to-client server
  318. // connection info exchange. See the comment for psiphon.ExportExchangePayload
  319. // for more details.
  320. func (controller *Controller) ExportExchangePayload() string {
  321. return ExportExchangePayload(controller.config)
  322. }
  323. // ImportExchangePayload imports a payload generated by ExportExchangePayload.
  324. // See the comment for psiphon.ImportExchangePayload for more details about
  325. // the import.
  326. //
  327. // When the import is successful, a signal is set to trigger a restart any
  328. // establishment in progress. This will cause the newly imported server entry
  329. // to be prioritized, which it otherwise would not be in later establishment
  330. // rounds. The establishment process continues after ImportExchangePayload
  331. // returns.
  332. //
  333. // If the client already has a connected tunnel, or a tunnel connection is
  334. // established concurrently with the import, the signal has no effect as the
  335. // overall goal is establish _any_ connection.
  336. func (controller *Controller) ImportExchangePayload(payload string) bool {
  337. // Race condition: if a new tunnel connection is established concurrently
  338. // with the import, either that tunnel's server entry of the imported server
  339. // entry may end up as the affinity server.
  340. ok := ImportExchangePayload(controller.config, payload)
  341. if !ok {
  342. return false
  343. }
  344. select {
  345. case controller.signalRestartEstablishing <- struct{}{}:
  346. default:
  347. }
  348. return true
  349. }
  350. // remoteServerListFetcher fetches an out-of-band list of server entries
  351. // for more tunnel candidates. It fetches when signalled, with retries
  352. // on failure.
  353. func (controller *Controller) remoteServerListFetcher(
  354. name string,
  355. fetcher RemoteServerListFetcher,
  356. signal <-chan struct{}) {
  357. defer controller.runWaitGroup.Done()
  358. var lastFetchTime time.Time
  359. fetcherLoop:
  360. for {
  361. // Wait for a signal before fetching
  362. select {
  363. case <-signal:
  364. case <-controller.runCtx.Done():
  365. break fetcherLoop
  366. }
  367. // Skip fetch entirely (i.e., send no request at all, even when ETag would save
  368. // on response size) when a recent fetch was successful
  369. stalePeriod := controller.config.GetParameters().Get().Duration(
  370. parameters.FetchRemoteServerListStalePeriod)
  371. if !lastFetchTime.IsZero() &&
  372. lastFetchTime.Add(stalePeriod).After(time.Now()) {
  373. continue
  374. }
  375. retryLoop:
  376. for attempt := 0; ; attempt++ {
  377. // Don't attempt to fetch while there is no network connectivity,
  378. // to avoid alert notice noise.
  379. if !WaitForNetworkConnectivity(
  380. controller.runCtx,
  381. controller.config.NetworkConnectivityChecker) {
  382. break fetcherLoop
  383. }
  384. // Pick any active tunnel and make the next fetch attempt. If there's
  385. // no active tunnel, the untunneledDialConfig will be used.
  386. tunnel := controller.getNextActiveTunnel()
  387. err := fetcher(
  388. controller.runCtx,
  389. controller.config,
  390. attempt,
  391. tunnel,
  392. controller.untunneledDialConfig)
  393. if err == nil {
  394. lastFetchTime = time.Now()
  395. break retryLoop
  396. }
  397. NoticeWarning("failed to fetch %s remote server list: %v",
  398. name, errors.Trace(err))
  399. retryPeriod := controller.config.GetParameters().Get().Duration(
  400. parameters.FetchRemoteServerListRetryPeriod)
  401. timer := time.NewTimer(retryPeriod)
  402. select {
  403. case <-timer.C:
  404. case <-controller.runCtx.Done():
  405. timer.Stop()
  406. break fetcherLoop
  407. }
  408. }
  409. }
  410. NoticeInfo("exiting %s remote server list fetcher", name)
  411. }
  412. // upgradeDownloader makes periodic attempts to complete a client upgrade
  413. // download. DownloadUpgrade() is resumable, so each attempt has potential for
  414. // getting closer to completion, even in conditions where the download or
  415. // tunnel is repeatedly interrupted.
  416. // An upgrade download is triggered by either a handshake response indicating
  417. // that a new version is available; or after failing to connect, in which case
  418. // it's useful to check, out-of-band, for an upgrade with new circumvention
  419. // capabilities.
  420. // Once the download operation completes successfully, the downloader exits
  421. // and is not run again: either there is not a newer version, or the upgrade
  422. // has been downloaded and is ready to be applied.
  423. // We're assuming that the upgrade will be applied and the entire system
  424. // restarted before another upgrade is to be downloaded.
  425. //
  426. // TODO: refactor upgrade downloader and remote server list fetcher to use
  427. // common code (including the resumable download routines).
  428. func (controller *Controller) upgradeDownloader() {
  429. defer controller.runWaitGroup.Done()
  430. var lastDownloadTime time.Time
  431. downloadLoop:
  432. for {
  433. // Wait for a signal before downloading
  434. var handshakeVersion string
  435. select {
  436. case handshakeVersion = <-controller.signalDownloadUpgrade:
  437. case <-controller.runCtx.Done():
  438. break downloadLoop
  439. }
  440. stalePeriod := controller.config.GetParameters().Get().Duration(
  441. parameters.FetchUpgradeStalePeriod)
  442. // Unless handshake is explicitly advertizing a new version, skip
  443. // checking entirely when a recent download was successful.
  444. if handshakeVersion == "" &&
  445. !lastDownloadTime.IsZero() &&
  446. lastDownloadTime.Add(stalePeriod).After(time.Now()) {
  447. continue
  448. }
  449. retryLoop:
  450. for attempt := 0; ; attempt++ {
  451. // Don't attempt to download while there is no network connectivity,
  452. // to avoid alert notice noise.
  453. if !WaitForNetworkConnectivity(
  454. controller.runCtx,
  455. controller.config.NetworkConnectivityChecker) {
  456. break downloadLoop
  457. }
  458. // Pick any active tunnel and make the next download attempt. If there's
  459. // no active tunnel, the untunneledDialConfig will be used.
  460. tunnel := controller.getNextActiveTunnel()
  461. err := DownloadUpgrade(
  462. controller.runCtx,
  463. controller.config,
  464. attempt,
  465. handshakeVersion,
  466. tunnel,
  467. controller.untunneledDialConfig)
  468. if err == nil {
  469. lastDownloadTime = time.Now()
  470. break retryLoop
  471. }
  472. NoticeWarning("failed to download upgrade: %v", errors.Trace(err))
  473. timeout := controller.config.GetParameters().Get().Duration(
  474. parameters.FetchUpgradeRetryPeriod)
  475. timer := time.NewTimer(timeout)
  476. select {
  477. case <-timer.C:
  478. case <-controller.runCtx.Done():
  479. timer.Stop()
  480. break downloadLoop
  481. }
  482. }
  483. }
  484. NoticeInfo("exiting upgrade downloader")
  485. }
  486. type serverEntriesReportRequest struct {
  487. constraints *protocolSelectionConstraints
  488. awaitResponse chan *serverEntriesReportResponse
  489. }
  490. type serverEntriesReportResponse struct {
  491. err error
  492. candidates int
  493. initialCandidates int
  494. initialCandidatesAnyEgressRegion int
  495. availableEgressRegions []string
  496. }
  497. // serverEntriesReporter performs scans over all server entries to report on
  498. // available tunnel candidates, subject to protocol selection constraints, and
  499. // available egress regions.
  500. //
  501. // Because scans may be slow, depending on the client device and server entry
  502. // list size, serverEntriesReporter is used to perform asychronous, background
  503. // operations that would otherwise block establishment. This includes emitting
  504. // diagnotic notices that are informational (CandidateServers) or which do not
  505. // need to emit before establishment starts (AvailableEgressRegions).
  506. //
  507. // serverEntriesReporter also serves to combine these scans, which would
  508. // otherwise be logically independent, due to the performance impact of scans.
  509. //
  510. // The underlying datastore implementation _may_ block write transactions
  511. // while there are open read transactions. For example, bolt write
  512. // transactions which need to re-map the data file (when the datastore grows)
  513. // will block on open read transactions. In these scenarios, a slow scan will
  514. // still block other operations.
  515. //
  516. // serverEntriesReporter runs beyond the establishment phase, since it's
  517. // important for notices such as AvailableEgressRegions to eventually emit
  518. // even if already established. serverEntriesReporter scans are cancellable,
  519. // so controller shutdown is not blocked by slow scans.
  520. //
  521. // In some special cases, establishment cannot begin without candidate counts
  522. // up front. In these cases only, the request contains a non-nil
  523. // awaitResponse, a channel which is used by the requester to block until the
  524. // scan is complete and the candidate counts are available.
  525. func (controller *Controller) serverEntriesReporter() {
  526. defer controller.runWaitGroup.Done()
  527. loop:
  528. for {
  529. var request *serverEntriesReportRequest
  530. select {
  531. case request = <-controller.signalReportServerEntries:
  532. case <-controller.runCtx.Done():
  533. break loop
  534. }
  535. egressRegion := controller.config.EgressRegion
  536. constraints := request.constraints
  537. var response serverEntriesReportResponse
  538. regions := make(map[string]bool)
  539. callback := func(serverEntry *protocol.ServerEntry) bool {
  540. // In establishment, excludeIntensive depends on what set of protocols are
  541. // already being dialed. For these reports, don't exclude intensive
  542. // protocols as any intensive candidate can always be an available
  543. // candidate at some point.
  544. excludeIntensive := false
  545. isInitialCandidate := constraints.isInitialCandidate(excludeIntensive, serverEntry)
  546. isCandidate := constraints.isCandidate(excludeIntensive, serverEntry)
  547. if isInitialCandidate {
  548. response.initialCandidatesAnyEgressRegion += 1
  549. }
  550. if egressRegion == "" || serverEntry.Region == egressRegion {
  551. if isInitialCandidate {
  552. response.initialCandidates += 1
  553. }
  554. if isCandidate {
  555. response.candidates += 1
  556. }
  557. }
  558. isAvailable := isCandidate
  559. if constraints.hasInitialProtocols() {
  560. // Available egress regions is subject to an initial limit constraint, if
  561. // present: see AvailableEgressRegions comment in launchEstablishing.
  562. isAvailable = isInitialCandidate
  563. }
  564. if isAvailable {
  565. // Ignore server entries with no region field.
  566. if serverEntry.Region != "" {
  567. regions[serverEntry.Region] = true
  568. }
  569. }
  570. select {
  571. case <-controller.runCtx.Done():
  572. // Don't block controller shutdown: cancel the scan.
  573. return false
  574. default:
  575. return true
  576. }
  577. }
  578. startTime := time.Now()
  579. response.err = ScanServerEntries(callback)
  580. // Report this duration in CandidateServers as an indication of datastore
  581. // performance.
  582. duration := time.Since(startTime)
  583. response.availableEgressRegions = make([]string, 0, len(regions))
  584. for region := range regions {
  585. response.availableEgressRegions = append(response.availableEgressRegions, region)
  586. }
  587. if response.err != nil {
  588. // For diagnostics, we'll post this even when cancelled due to shutdown.
  589. NoticeWarning("ScanServerEntries failed: %v", errors.Trace(response.err))
  590. // Continue and send error reponse. Clear any partial data to avoid
  591. // misuse.
  592. response.candidates = 0
  593. response.initialCandidates = 0
  594. response.initialCandidatesAnyEgressRegion = 0
  595. response.availableEgressRegions = []string{}
  596. }
  597. if request.awaitResponse != nil {
  598. select {
  599. case request.awaitResponse <- &response:
  600. case <-controller.runCtx.Done():
  601. // The receiver may be gone when shutting down.
  602. }
  603. }
  604. if response.err == nil {
  605. NoticeCandidateServers(
  606. controller.config.EgressRegion,
  607. controller.protocolSelectionConstraints,
  608. response.initialCandidates,
  609. response.candidates,
  610. duration)
  611. NoticeAvailableEgressRegions(
  612. response.availableEgressRegions)
  613. }
  614. }
  615. NoticeInfo("exiting server entries reporter")
  616. }
  617. // signalServerEntriesReporter triggers a new server entry report. Set
  618. // request.awaitResponse to obtain the report output. When awaitResponse is
  619. // set, signalServerEntriesReporter blocks until the reporter receives the
  620. // request, guaranteeing the new report runs. Otherwise, the report is
  621. // considered to be informational and may or may not run, depending on whether
  622. // another run is already in progress.
  623. func (controller *Controller) signalServerEntriesReporter(request *serverEntriesReportRequest) {
  624. if request.awaitResponse == nil {
  625. select {
  626. case controller.signalReportServerEntries <- request:
  627. default:
  628. }
  629. } else {
  630. controller.signalReportServerEntries <- request
  631. }
  632. }
  633. // connectedReporter sends periodic "connected" requests to the Psiphon API.
  634. // These requests are for server-side unique user stats calculation. See the
  635. // comment in DoConnectedRequest for a description of the request mechanism.
  636. //
  637. // To correctly count daily unique users, only one connected request is made
  638. // across all simultaneous multi-tunnels; and the connected request is
  639. // repeated every 24h.
  640. //
  641. // The signalReportConnected mechanism is used to trigger a connected request
  642. // immediately after a reconnect. While strictly only one connected request
  643. // per 24h is required in order to count daily unique users, the connected
  644. // request also delivers the establishment duration metric (which includes
  645. // time elapsed performing the handshake request) and additional fragmentation
  646. // metrics; these metrics are measured for each tunnel.
  647. func (controller *Controller) connectedReporter() {
  648. defer controller.runWaitGroup.Done()
  649. // session is nil when DisableApi is set
  650. if controller.config.DisableApi {
  651. return
  652. }
  653. select {
  654. case <-controller.signalReportConnected:
  655. // Make the initial connected request
  656. case <-controller.runCtx.Done():
  657. return
  658. }
  659. loop:
  660. for {
  661. // Pick any active tunnel and make the next connected request. No error is
  662. // logged if there's no active tunnel, as that's not an unexpected
  663. // condition.
  664. reported := false
  665. tunnel := controller.getNextActiveTunnel()
  666. if tunnel != nil {
  667. err := tunnel.serverContext.DoConnectedRequest()
  668. if err == nil {
  669. reported = true
  670. } else {
  671. NoticeWarning("failed to make connected request: %v",
  672. errors.Trace(err))
  673. }
  674. }
  675. // Schedule the next connected request and wait. This duration is not a
  676. // dynamic ClientParameter as the daily unique user stats logic specifically
  677. // requires a "connected" request no more or less often than every 24h.
  678. var duration time.Duration
  679. if reported {
  680. duration = 24 * time.Hour
  681. } else {
  682. duration = controller.config.GetParameters().Get().Duration(
  683. parameters.PsiphonAPIConnectedRequestRetryPeriod)
  684. }
  685. timer := time.NewTimer(duration)
  686. doBreak := false
  687. select {
  688. case <-controller.signalReportConnected:
  689. case <-timer.C:
  690. // Make another connected request
  691. case <-controller.runCtx.Done():
  692. doBreak = true
  693. }
  694. timer.Stop()
  695. if doBreak {
  696. break loop
  697. }
  698. }
  699. NoticeInfo("exiting connected reporter")
  700. }
  701. func (controller *Controller) signalConnectedReporter() {
  702. // session is nil when DisableApi is set
  703. if controller.config.DisableApi {
  704. return
  705. }
  706. select {
  707. case controller.signalReportConnected <- struct{}{}:
  708. default:
  709. }
  710. }
  711. // establishTunnelWatcher terminates the controller if a tunnel
  712. // has not been established in the configured time period. This
  713. // is regardless of how many tunnels are presently active -- meaning
  714. // that if an active tunnel was established and lost the controller
  715. // is left running (to re-establish).
  716. func (controller *Controller) establishTunnelWatcher() {
  717. defer controller.runWaitGroup.Done()
  718. timeout := controller.config.GetParameters().Get().Duration(
  719. parameters.EstablishTunnelTimeout)
  720. if timeout > 0 {
  721. timer := time.NewTimer(timeout)
  722. defer timer.Stop()
  723. select {
  724. case <-timer.C:
  725. if !controller.hasEstablishedOnce() {
  726. NoticeEstablishTunnelTimeout(timeout)
  727. controller.SignalComponentFailure()
  728. }
  729. case <-controller.runCtx.Done():
  730. }
  731. }
  732. NoticeInfo("exiting establish tunnel watcher")
  733. }
  734. // runTunnels is the controller tunnel management main loop. It starts and stops
  735. // establishing tunnels based on the target tunnel pool size and the current size
  736. // of the pool. Tunnels are established asynchronously using worker goroutines.
  737. //
  738. // When there are no server entries for the target region/protocol, the
  739. // establishCandidateGenerator will yield no candidates and wait before
  740. // trying again. In the meantime, a remote server entry fetch may supply
  741. // valid candidates.
  742. //
  743. // When a tunnel is established, it's added to the active pool. The tunnel's
  744. // operateTunnel goroutine monitors the tunnel.
  745. //
  746. // When a tunnel fails, it's removed from the pool and the establish process is
  747. // restarted to fill the pool.
  748. func (controller *Controller) runTunnels() {
  749. defer controller.runWaitGroup.Done()
  750. // Start running
  751. controller.startEstablishing()
  752. loop:
  753. for {
  754. select {
  755. case <-controller.signalRestartEstablishing:
  756. // signalRestartEstablishing restarts any establishment in progress. One
  757. // use case for this is to prioritize a newly imported, exchanged server
  758. // entry, which will be in the affinity position.
  759. //
  760. // It's possible for another connection to establish concurrent to signalling;
  761. // since the overall goal remains to establish _any_ connection, we accept that
  762. // in some cases the exchanged server entry may not get used.
  763. if controller.isEstablishing {
  764. controller.stopEstablishing()
  765. controller.startEstablishing()
  766. }
  767. case failedTunnel := <-controller.failedTunnels:
  768. NoticeWarning("tunnel failed: %s", failedTunnel.dialParams.ServerEntry.GetDiagnosticID())
  769. controller.terminateTunnel(failedTunnel)
  770. // Clear the reference to this tunnel before calling startEstablishing,
  771. // which will invoke a garbage collection.
  772. failedTunnel = nil
  773. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing,
  774. // which reference controller.isEstablishing.
  775. controller.startEstablishing()
  776. case connectedTunnel := <-controller.connectedTunnels:
  777. // Tunnel establishment has two phases: connection and activation.
  778. //
  779. // Connection is run concurrently by the establishTunnelWorkers, to minimize
  780. // delay when it's not yet known which server and protocol will be available
  781. // and unblocked.
  782. //
  783. // Activation is run serially, here, to minimize the overhead of making a
  784. // handshake request and starting the operateTunnel management worker for a
  785. // tunnel which may be discarded.
  786. //
  787. // When the active tunnel will complete establishment, establishment is
  788. // stopped before activation. This interrupts all connecting tunnels and
  789. // garbage collects their memory. The purpose is to minimize memory
  790. // pressure when the handshake request is made. In the unlikely case that the
  791. // handshake fails, establishment is restarted.
  792. //
  793. // Any delays in stopEstablishing will delay the handshake for the last
  794. // active tunnel.
  795. //
  796. // In the typical case of tunnelPoolSize of 1, only a single handshake is
  797. // performed and the homepages notices file, when used, will not be modifed
  798. // after the NoticeTunnels(1) [i.e., connected] until NoticeTunnels(0) [i.e.,
  799. // disconnected]. For tunnelPoolSize > 1, serial handshakes only ensures that
  800. // each set of emitted NoticeHomepages is contiguous.
  801. active, outstanding := controller.numTunnels()
  802. // discardTunnel will be true here when already fully established.
  803. discardTunnel := (outstanding <= 0)
  804. isFirstTunnel := (active == 0)
  805. isLastTunnel := (outstanding == 1)
  806. if !discardTunnel {
  807. if isLastTunnel {
  808. controller.stopEstablishing()
  809. }
  810. err := connectedTunnel.Activate(controller.runCtx, controller)
  811. if err != nil {
  812. NoticeWarning("failed to activate %s: %v",
  813. connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(),
  814. errors.Trace(err))
  815. discardTunnel = true
  816. } else {
  817. // It's unlikely that registerTunnel will fail, since only this goroutine
  818. // calls registerTunnel -- and after checking numTunnels; so failure is not
  819. // expected.
  820. if !controller.registerTunnel(connectedTunnel) {
  821. NoticeWarning("failed to register %s: %v",
  822. connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(),
  823. errors.Trace(err))
  824. discardTunnel = true
  825. }
  826. }
  827. // May need to replace this tunnel
  828. if isLastTunnel && discardTunnel {
  829. controller.startEstablishing()
  830. }
  831. }
  832. if discardTunnel {
  833. controller.discardTunnel(connectedTunnel)
  834. // Clear the reference to this discarded tunnel and immediately run
  835. // a garbage collection to reclaim its memory.
  836. connectedTunnel = nil
  837. DoGarbageCollection()
  838. // Skip the rest of this case
  839. break
  840. }
  841. atomic.AddInt32(&controller.establishedTunnelsCount, 1)
  842. NoticeActiveTunnel(
  843. connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(),
  844. connectedTunnel.dialParams.TunnelProtocol,
  845. connectedTunnel.dialParams.ServerEntry.Region)
  846. if isFirstTunnel {
  847. // Signal a connected request on each 1st tunnel establishment. For
  848. // multi-tunnels, the session is connected as long as at least one
  849. // tunnel is established.
  850. controller.signalConnectedReporter()
  851. // If the handshake indicated that a new client version is available,
  852. // trigger an upgrade download.
  853. // Note: serverContext is nil when DisableApi is set
  854. if connectedTunnel.serverContext != nil &&
  855. connectedTunnel.serverContext.clientUpgradeVersion != "" {
  856. handshakeVersion := connectedTunnel.serverContext.clientUpgradeVersion
  857. select {
  858. case controller.signalDownloadUpgrade <- handshakeVersion:
  859. default:
  860. }
  861. }
  862. }
  863. // Set the new tunnel as the transport for the packet tunnel. The packet tunnel
  864. // client remains up when reestablishing, but no packets are relayed while there
  865. // is no connected tunnel. UseTunnel will establish a new packet tunnel SSH
  866. // channel over the new SSH tunnel and configure the packet tunnel client to use
  867. // the new SSH channel as its transport.
  868. //
  869. // Note: as is, this logic is suboptimal for tunnelPoolSize > 1, as this would
  870. // continuously initialize new packet tunnel sessions for each established
  871. // server. For now, config validation requires tunnelPoolSize == 1 when
  872. // the packet tunnel is used.
  873. if controller.packetTunnelTransport != nil {
  874. controller.packetTunnelTransport.UseTunnel(connectedTunnel)
  875. }
  876. if controller.isFullyEstablished() {
  877. controller.stopEstablishing()
  878. }
  879. case <-controller.runCtx.Done():
  880. break loop
  881. }
  882. }
  883. // Stop running
  884. controller.stopEstablishing()
  885. controller.terminateAllTunnels()
  886. // Drain tunnel channels
  887. close(controller.connectedTunnels)
  888. for tunnel := range controller.connectedTunnels {
  889. controller.discardTunnel(tunnel)
  890. }
  891. close(controller.failedTunnels)
  892. for tunnel := range controller.failedTunnels {
  893. controller.discardTunnel(tunnel)
  894. }
  895. NoticeInfo("exiting run tunnels")
  896. }
  897. // SignalSeededNewSLOK implements the TunnelOwner interface. This function
  898. // is called by Tunnel.operateTunnel when the tunnel has received a new,
  899. // previously unknown SLOK from the server. The Controller triggers an OSL
  900. // fetch, as the new SLOK may be sufficient to access new OSLs.
  901. func (controller *Controller) SignalSeededNewSLOK() {
  902. select {
  903. case controller.signalFetchObfuscatedServerLists <- struct{}{}:
  904. default:
  905. }
  906. }
  907. // SignalTunnelFailure implements the TunnelOwner interface. This function
  908. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  909. // has failed. The Controller will signal runTunnels to create a new
  910. // tunnel and/or remove the tunnel from the list of active tunnels.
  911. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  912. // Don't block. Assumes the receiver has a buffer large enough for
  913. // the typical number of operated tunnels. In case there's no room,
  914. // terminate the tunnel (runTunnels won't get a signal in this case,
  915. // but the tunnel will be removed from the list of active tunnels).
  916. select {
  917. case controller.failedTunnels <- tunnel:
  918. default:
  919. controller.terminateTunnel(tunnel)
  920. }
  921. }
  922. // discardTunnel disposes of a successful connection that is no longer required.
  923. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  924. NoticeInfo("discard tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  925. // TODO: not calling PromoteServerEntry, since that would rank the
  926. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  927. // be promoted (since it connects), but with lower rank than all active
  928. // tunnels?
  929. tunnel.Close(true)
  930. }
  931. // registerTunnel adds the connected tunnel to the pool of active tunnels
  932. // which are candidates for port forwarding. Returns true if the pool has an
  933. // empty slot and false if the pool is full (caller should discard the tunnel).
  934. func (controller *Controller) registerTunnel(tunnel *Tunnel) bool {
  935. controller.tunnelMutex.Lock()
  936. defer controller.tunnelMutex.Unlock()
  937. if len(controller.tunnels) >= controller.tunnelPoolSize {
  938. return false
  939. }
  940. // Perform a final check just in case we've established
  941. // a duplicate connection.
  942. for _, activeTunnel := range controller.tunnels {
  943. if activeTunnel.dialParams.ServerEntry.IpAddress ==
  944. tunnel.dialParams.ServerEntry.IpAddress {
  945. NoticeWarning("duplicate tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  946. return false
  947. }
  948. }
  949. controller.establishedOnce = true
  950. controller.tunnels = append(controller.tunnels, tunnel)
  951. NoticeTunnels(len(controller.tunnels))
  952. // Promote this successful tunnel to first rank so it's one
  953. // of the first candidates next time establish runs.
  954. // Connecting to a TargetServerEntry does not change the
  955. // ranking.
  956. if controller.config.TargetServerEntry == "" {
  957. PromoteServerEntry(controller.config, tunnel.dialParams.ServerEntry.IpAddress)
  958. }
  959. return true
  960. }
  961. // hasEstablishedOnce indicates if at least one active tunnel has
  962. // been established up to this point. This is regardeless of how many
  963. // tunnels are presently active.
  964. func (controller *Controller) hasEstablishedOnce() bool {
  965. controller.tunnelMutex.Lock()
  966. defer controller.tunnelMutex.Unlock()
  967. return controller.establishedOnce
  968. }
  969. // isFullyEstablished indicates if the pool of active tunnels is full.
  970. func (controller *Controller) isFullyEstablished() bool {
  971. controller.tunnelMutex.Lock()
  972. defer controller.tunnelMutex.Unlock()
  973. return len(controller.tunnels) >= controller.tunnelPoolSize
  974. }
  975. // numTunnels returns the number of active and outstanding tunnels.
  976. // Oustanding is the number of tunnels required to fill the pool of
  977. // active tunnels.
  978. func (controller *Controller) numTunnels() (int, int) {
  979. controller.tunnelMutex.Lock()
  980. defer controller.tunnelMutex.Unlock()
  981. active := len(controller.tunnels)
  982. outstanding := controller.tunnelPoolSize - len(controller.tunnels)
  983. return active, outstanding
  984. }
  985. // terminateTunnel removes a tunnel from the pool of active tunnels
  986. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  987. // is adjusted as required.
  988. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  989. controller.tunnelMutex.Lock()
  990. defer controller.tunnelMutex.Unlock()
  991. for index, activeTunnel := range controller.tunnels {
  992. if tunnel == activeTunnel {
  993. controller.tunnels = append(
  994. controller.tunnels[:index], controller.tunnels[index+1:]...)
  995. if controller.nextTunnel > index {
  996. controller.nextTunnel--
  997. }
  998. if controller.nextTunnel >= len(controller.tunnels) {
  999. controller.nextTunnel = 0
  1000. }
  1001. activeTunnel.Close(false)
  1002. NoticeTunnels(len(controller.tunnels))
  1003. break
  1004. }
  1005. }
  1006. }
  1007. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  1008. // This is used when shutting down the controller.
  1009. func (controller *Controller) terminateAllTunnels() {
  1010. controller.tunnelMutex.Lock()
  1011. defer controller.tunnelMutex.Unlock()
  1012. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  1013. // may take a few seconds to send a final status request. We only want
  1014. // to wait as long as the single slowest tunnel.
  1015. closeWaitGroup := new(sync.WaitGroup)
  1016. closeWaitGroup.Add(len(controller.tunnels))
  1017. for _, activeTunnel := range controller.tunnels {
  1018. tunnel := activeTunnel
  1019. go func() {
  1020. defer closeWaitGroup.Done()
  1021. tunnel.Close(false)
  1022. }()
  1023. }
  1024. closeWaitGroup.Wait()
  1025. controller.tunnels = make([]*Tunnel, 0)
  1026. controller.nextTunnel = 0
  1027. NoticeTunnels(len(controller.tunnels))
  1028. }
  1029. // getNextActiveTunnel returns the next tunnel from the pool of active
  1030. // tunnels. Currently, tunnel selection order is simple round-robin.
  1031. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  1032. controller.tunnelMutex.Lock()
  1033. defer controller.tunnelMutex.Unlock()
  1034. if len(controller.tunnels) == 0 {
  1035. return nil
  1036. }
  1037. tunnel = controller.tunnels[controller.nextTunnel]
  1038. controller.nextTunnel =
  1039. (controller.nextTunnel + 1) % len(controller.tunnels)
  1040. return tunnel
  1041. }
  1042. // isActiveTunnelServerEntry is used to check if there's already
  1043. // an existing tunnel to a candidate server.
  1044. func (controller *Controller) isActiveTunnelServerEntry(
  1045. serverEntry *protocol.ServerEntry) bool {
  1046. controller.tunnelMutex.Lock()
  1047. defer controller.tunnelMutex.Unlock()
  1048. for _, activeTunnel := range controller.tunnels {
  1049. if activeTunnel.dialParams.ServerEntry.IpAddress == serverEntry.IpAddress {
  1050. return true
  1051. }
  1052. }
  1053. return false
  1054. }
  1055. func (controller *Controller) setTunnelPoolSize(tunnelPoolSize int) {
  1056. controller.tunnelMutex.Lock()
  1057. defer controller.tunnelMutex.Unlock()
  1058. if tunnelPoolSize < 1 {
  1059. tunnelPoolSize = 1
  1060. }
  1061. if tunnelPoolSize > MAX_TUNNEL_POOL_SIZE {
  1062. tunnelPoolSize = MAX_TUNNEL_POOL_SIZE
  1063. }
  1064. controller.tunnelPoolSize = tunnelPoolSize
  1065. }
  1066. func (controller *Controller) getTunnelPoolSize() int {
  1067. controller.tunnelMutex.Lock()
  1068. defer controller.tunnelMutex.Unlock()
  1069. return controller.tunnelPoolSize
  1070. }
  1071. // Dial selects an active tunnel and establishes a port forward
  1072. // connection through the selected tunnel. Failure to connect is considered
  1073. // a port forward failure, for the purpose of monitoring tunnel health.
  1074. //
  1075. // When split tunnel mode is enabled, the connection may be untunneled,
  1076. // depending on GeoIP classification of the destination.
  1077. //
  1078. // downstreamConn is an optional parameter which specifies a connection to be
  1079. // explicitly closed when the dialed connection is closed. For instance, this
  1080. // is used to close downstreamConn App<->LocalProxy connections when the
  1081. // related LocalProxy<->SshPortForward connections close.
  1082. func (controller *Controller) Dial(
  1083. remoteAddr string, downstreamConn net.Conn) (conn net.Conn, err error) {
  1084. tunnel := controller.getNextActiveTunnel()
  1085. if tunnel == nil {
  1086. return nil, errors.TraceNew("no active tunnels")
  1087. }
  1088. if !tunnel.config.IsSplitTunnelEnabled() {
  1089. tunneledConn, splitTunnel, err := tunnel.DialTCPChannel(
  1090. remoteAddr, false, downstreamConn)
  1091. if err != nil {
  1092. return nil, errors.Trace(err)
  1093. }
  1094. if splitTunnel {
  1095. return nil, errors.TraceNew(
  1096. "unexpected split tunnel classification")
  1097. }
  1098. return tunneledConn, nil
  1099. }
  1100. // In split tunnel mode, TCP port forwards to destinations in the same
  1101. // country as the client are untunneled.
  1102. //
  1103. // Split tunnel is implemented with assistence from the server to classify
  1104. // destinations as being in the same country as the client. The server knows
  1105. // the client's public IP GeoIP data, and, for clients with split tunnel mode
  1106. // enabled, the server resolves the port forward destination address and
  1107. // checks the destination IP GeoIP data.
  1108. //
  1109. // When the countries match, the server "rejects" the port forward with a
  1110. // distinct response that indicates to the client that an untunneled port
  1111. // foward should be established locally.
  1112. //
  1113. // The client maintains a classification cache that allows it to make
  1114. // untunneled port forwards without requiring a round trip to the server.
  1115. // Only destinations classified as untunneled are stored in the cache: a
  1116. // destination classified as tunneled requires the same round trip as an
  1117. // unknown destination.
  1118. //
  1119. // When the countries do not match, the server establishes a port forward, as
  1120. // it does for all port forwards in non-split tunnel mode. There is no
  1121. // additional round trip for tunneled port forwards.
  1122. splitTunnelHost, _, err := net.SplitHostPort(remoteAddr)
  1123. if err != nil {
  1124. return nil, errors.Trace(err)
  1125. }
  1126. untunneledCache := controller.untunneledSplitTunnelClassifications
  1127. // If the destination hostname is in the untunneled split tunnel
  1128. // classifications cache, skip the round trip to the server and do the
  1129. // direct, untunneled dial immediately.
  1130. _, cachedUntunneled := untunneledCache.Get(splitTunnelHost)
  1131. if !cachedUntunneled {
  1132. tunneledConn, splitTunnel, err := tunnel.DialTCPChannel(
  1133. remoteAddr, false, downstreamConn)
  1134. if err != nil {
  1135. return nil, errors.Trace(err)
  1136. }
  1137. if !splitTunnel {
  1138. // Clear any cached untunneled classification entry for this destination
  1139. // hostname, as the server is now classifying it as tunneled.
  1140. untunneledCache.Delete(splitTunnelHost)
  1141. return tunneledConn, nil
  1142. }
  1143. // The server has indicated that the client should make a direct,
  1144. // untunneled dial. Cache the classification to avoid this round trip in
  1145. // the immediate future.
  1146. untunneledCache.Add(splitTunnelHost, true, lrucache.DefaultExpiration)
  1147. }
  1148. NoticeUntunneled(splitTunnelHost)
  1149. untunneledConn, err := controller.DirectDial(remoteAddr)
  1150. if err != nil {
  1151. return nil, errors.Trace(err)
  1152. }
  1153. return untunneledConn, nil
  1154. }
  1155. // DirectDial dials an untunneled TCP connection within the controller run context.
  1156. func (controller *Controller) DirectDial(remoteAddr string) (conn net.Conn, err error) {
  1157. return DialTCP(controller.runCtx, remoteAddr, controller.untunneledDialConfig)
  1158. }
  1159. // triggerFetches signals RSL, OSL, and upgrade download fetchers to begin, if
  1160. // not already running. triggerFetches is called when tunnel establishment
  1161. // fails to complete within a deadline and in other cases where local
  1162. // circumvention capabilities are lacking and we may require new server
  1163. // entries or client versions with new capabilities.
  1164. func (controller *Controller) triggerFetches() {
  1165. // Trigger a common remote server list fetch, since we may have failed
  1166. // to connect with all known servers. Don't block sending signal, since
  1167. // this signal may have already been sent.
  1168. // Don't wait for fetch remote to succeed, since it may fail and
  1169. // enter a retry loop and we're better off trying more known servers.
  1170. // TODO: synchronize the fetch response, so it can be incorporated
  1171. // into the server entry iterator as soon as available.
  1172. select {
  1173. case controller.signalFetchCommonRemoteServerList <- struct{}{}:
  1174. default:
  1175. }
  1176. // Trigger an OSL fetch in parallel. Both fetches are run in parallel
  1177. // so that if one out of the common RLS and OSL set is large, it doesn't
  1178. // doesn't entirely block fetching the other.
  1179. select {
  1180. case controller.signalFetchObfuscatedServerLists <- struct{}{}:
  1181. default:
  1182. }
  1183. // Trigger an out-of-band upgrade availability check and download.
  1184. // Since we may have failed to connect, we may benefit from upgrading
  1185. // to a new client version with new circumvention capabilities.
  1186. select {
  1187. case controller.signalDownloadUpgrade <- "":
  1188. default:
  1189. }
  1190. }
  1191. type protocolSelectionConstraints struct {
  1192. useUpstreamProxy bool
  1193. initialLimitTunnelProtocols protocol.TunnelProtocols
  1194. initialLimitTunnelProtocolsCandidateCount int
  1195. limitTunnelProtocols protocol.TunnelProtocols
  1196. limitTunnelDialPortNumbers protocol.TunnelProtocolPortLists
  1197. limitQUICVersions protocol.QUICVersions
  1198. replayCandidateCount int
  1199. }
  1200. func (p *protocolSelectionConstraints) hasInitialProtocols() bool {
  1201. return len(p.initialLimitTunnelProtocols) > 0 && p.initialLimitTunnelProtocolsCandidateCount > 0
  1202. }
  1203. func (p *protocolSelectionConstraints) isInitialCandidate(
  1204. excludeIntensive bool,
  1205. serverEntry *protocol.ServerEntry) bool {
  1206. return p.hasInitialProtocols() &&
  1207. len(serverEntry.GetSupportedProtocols(
  1208. conditionallyEnabledComponents{},
  1209. p.useUpstreamProxy,
  1210. p.initialLimitTunnelProtocols,
  1211. p.limitTunnelDialPortNumbers,
  1212. p.limitQUICVersions,
  1213. excludeIntensive)) > 0
  1214. }
  1215. func (p *protocolSelectionConstraints) isCandidate(
  1216. excludeIntensive bool,
  1217. serverEntry *protocol.ServerEntry) bool {
  1218. return len(serverEntry.GetSupportedProtocols(
  1219. conditionallyEnabledComponents{},
  1220. p.useUpstreamProxy,
  1221. p.limitTunnelProtocols,
  1222. p.limitTunnelDialPortNumbers,
  1223. p.limitQUICVersions,
  1224. excludeIntensive)) > 0
  1225. }
  1226. func (p *protocolSelectionConstraints) canReplay(
  1227. connectTunnelCount int,
  1228. excludeIntensive bool,
  1229. serverEntry *protocol.ServerEntry,
  1230. replayProtocol string) bool {
  1231. if p.replayCandidateCount != -1 && connectTunnelCount > p.replayCandidateCount {
  1232. return false
  1233. }
  1234. return common.Contains(
  1235. p.supportedProtocols(connectTunnelCount, excludeIntensive, serverEntry),
  1236. replayProtocol)
  1237. }
  1238. func (p *protocolSelectionConstraints) supportedProtocols(
  1239. connectTunnelCount int,
  1240. excludeIntensive bool,
  1241. serverEntry *protocol.ServerEntry) []string {
  1242. limitTunnelProtocols := p.limitTunnelProtocols
  1243. if len(p.initialLimitTunnelProtocols) > 0 &&
  1244. p.initialLimitTunnelProtocolsCandidateCount > connectTunnelCount {
  1245. limitTunnelProtocols = p.initialLimitTunnelProtocols
  1246. }
  1247. return serverEntry.GetSupportedProtocols(
  1248. conditionallyEnabledComponents{},
  1249. p.useUpstreamProxy,
  1250. limitTunnelProtocols,
  1251. p.limitTunnelDialPortNumbers,
  1252. p.limitQUICVersions,
  1253. excludeIntensive)
  1254. }
  1255. func (p *protocolSelectionConstraints) selectProtocol(
  1256. connectTunnelCount int,
  1257. excludeIntensive bool,
  1258. serverEntry *protocol.ServerEntry) (string, bool) {
  1259. candidateProtocols := p.supportedProtocols(connectTunnelCount, excludeIntensive, serverEntry)
  1260. if len(candidateProtocols) == 0 {
  1261. return "", false
  1262. }
  1263. // Pick at random from the supported protocols. This ensures that we'll
  1264. // eventually try all possible protocols. Depending on network
  1265. // configuration, it may be the case that some protocol is only available
  1266. // through multi-capability servers, and a simpler ranked preference of
  1267. // protocols could lead to that protocol never being selected.
  1268. index := prng.Intn(len(candidateProtocols))
  1269. return candidateProtocols[index], true
  1270. }
  1271. type candidateServerEntry struct {
  1272. serverEntry *protocol.ServerEntry
  1273. isServerAffinityCandidate bool
  1274. adjustedEstablishStartTime time.Time
  1275. }
  1276. // startEstablishing creates a pool of worker goroutines which will
  1277. // attempt to establish tunnels to candidate servers. The candidates
  1278. // are generated by another goroutine.
  1279. func (controller *Controller) startEstablishing() {
  1280. if controller.isEstablishing {
  1281. return
  1282. }
  1283. NoticeInfo("start establishing")
  1284. // establishStartTime is used to calculate and report the client's tunnel
  1285. // establishment duration. Establishment duration should include all
  1286. // initialization in launchEstablishing and establishCandidateGenerator,
  1287. // including any potentially long-running datastore iterations.
  1288. establishStartTime := time.Now()
  1289. controller.concurrentEstablishTunnelsMutex.Lock()
  1290. controller.establishConnectTunnelCount = 0
  1291. controller.concurrentEstablishTunnels = 0
  1292. controller.concurrentIntensiveEstablishTunnels = 0
  1293. controller.peakConcurrentEstablishTunnels = 0
  1294. controller.peakConcurrentIntensiveEstablishTunnels = 0
  1295. controller.concurrentEstablishTunnelsMutex.Unlock()
  1296. DoGarbageCollection()
  1297. emitMemoryMetrics()
  1298. // The establish context cancelFunc, controller.stopEstablish, is called in
  1299. // controller.stopEstablishing.
  1300. controller.isEstablishing = true
  1301. controller.establishStartTime = establishStartTime
  1302. controller.establishCtx, controller.stopEstablish = context.WithCancel(controller.runCtx)
  1303. controller.establishWaitGroup = new(sync.WaitGroup)
  1304. controller.candidateServerEntries = make(chan *candidateServerEntry)
  1305. // The server affinity mechanism attempts to favor the previously
  1306. // used server when reconnecting. This is beneficial for user
  1307. // applications which expect consistency in user IP address (for
  1308. // example, a web site which prompts for additional user
  1309. // authentication when the IP address changes).
  1310. //
  1311. // Only the very first server, as determined by
  1312. // datastore.PromoteServerEntry(), is the server affinity candidate.
  1313. // Concurrent connections attempts to many servers are launched
  1314. // without delay, in case the affinity server connection fails.
  1315. // While the affinity server connection is outstanding, when any
  1316. // other connection is established, there is a short grace period
  1317. // delay before delivering the established tunnel; this allows some
  1318. // time for the affinity server connection to succeed first.
  1319. // When the affinity server connection fails, any other established
  1320. // tunnel is registered without delay.
  1321. //
  1322. // Note: the establishTunnelWorker that receives the affinity
  1323. // candidate is solely resonsible for closing
  1324. // controller.serverAffinityDoneBroadcast.
  1325. controller.serverAffinityDoneBroadcast = make(chan struct{})
  1326. controller.establishWaitGroup.Add(1)
  1327. go controller.launchEstablishing()
  1328. }
  1329. func (controller *Controller) launchEstablishing() {
  1330. defer controller.establishWaitGroup.Done()
  1331. // Before starting the establish tunnel workers, get and apply
  1332. // tactics, launching a tactics request if required.
  1333. //
  1334. // Wait only TacticsWaitPeriod for the tactics request to complete (or
  1335. // fail) before proceeding with tunnel establishment, in case the tactics
  1336. // request is blocked or takes very long to complete.
  1337. //
  1338. // An in-flight tactics request uses meek in round tripper mode, which
  1339. // uses less resources than meek tunnel relay mode. For this reason, the
  1340. // tactics request is not counted in concurrentIntensiveEstablishTunnels.
  1341. //
  1342. // TODO: HTTP/2 uses significantly more memory, so perhaps
  1343. // concurrentIntensiveEstablishTunnels should be counted in that case.
  1344. //
  1345. // Any in-flight tactics request or pending retry will be
  1346. // canceled when establishment is stopped.
  1347. if !controller.config.DisableTactics {
  1348. timeout := controller.config.GetParameters().Get().Duration(
  1349. parameters.TacticsWaitPeriod)
  1350. tacticsDone := make(chan struct{})
  1351. tacticsWaitPeriod := time.NewTimer(timeout)
  1352. defer tacticsWaitPeriod.Stop()
  1353. controller.establishWaitGroup.Add(1)
  1354. go func() {
  1355. defer controller.establishWaitGroup.Done()
  1356. defer close(tacticsDone)
  1357. GetTactics(controller.establishCtx, controller.config)
  1358. }()
  1359. select {
  1360. case <-tacticsDone:
  1361. case <-tacticsWaitPeriod.C:
  1362. }
  1363. tacticsWaitPeriod.Stop()
  1364. if controller.isStopEstablishing() {
  1365. // This check isn't strictly required but avoids the overhead of launching
  1366. // workers if establishment stopped while awaiting a tactics request.
  1367. return
  1368. }
  1369. }
  1370. // Initial- and LimitTunnelProtocols may be set by tactics.
  1371. //
  1372. // These protocol limits are fixed once per establishment, for
  1373. // consistent application of related probabilities (applied by
  1374. // ParametersAccessor.TunnelProtocols). The
  1375. // establishLimitTunnelProtocolsState field must be read-only after this
  1376. // point, allowing concurrent reads by establishment workers.
  1377. p := controller.config.GetParameters().Get()
  1378. controller.protocolSelectionConstraints = &protocolSelectionConstraints{
  1379. useUpstreamProxy: controller.config.UseUpstreamProxy(),
  1380. initialLimitTunnelProtocols: p.TunnelProtocols(parameters.InitialLimitTunnelProtocols),
  1381. initialLimitTunnelProtocolsCandidateCount: p.Int(parameters.InitialLimitTunnelProtocolsCandidateCount),
  1382. limitTunnelProtocols: p.TunnelProtocols(parameters.LimitTunnelProtocols),
  1383. limitTunnelDialPortNumbers: protocol.TunnelProtocolPortLists(
  1384. p.TunnelProtocolPortLists(parameters.LimitTunnelDialPortNumbers)),
  1385. replayCandidateCount: p.Int(parameters.ReplayCandidateCount),
  1386. }
  1387. // ConnectionWorkerPoolSize may be set by tactics.
  1388. workerPoolSize := p.Int(parameters.ConnectionWorkerPoolSize)
  1389. // When TargetServerEntry is used, override any worker pool size config or
  1390. // tactic parameter and use a pool size of 1. The typical use case for
  1391. // TargetServerEntry is to test a specific server with a single connection
  1392. // attempt. Furthermore, too many concurrent attempts to connect to the
  1393. // same server will trigger rate limiting.
  1394. if controller.config.TargetServerEntry != "" {
  1395. workerPoolSize = 1
  1396. }
  1397. // TunnelPoolSize may be set by tactics, subject to local constraints. A pool
  1398. // size of one is forced in packet tunnel mode or when using a
  1399. // TargetServerEntry. The tunnel pool size is reduced when there are
  1400. // insufficent known server entries, within the set region and protocol
  1401. // constraints, to satisfy the target.
  1402. //
  1403. // Limitations, to simplify concurrent access to shared state: a ceiling of
  1404. // MAX_TUNNEL_POOL_SIZE is enforced by setTunnelPoolSize; the tunnel pool
  1405. // size target is not re-adjusted after an API handshake, even though the
  1406. // handshake response may deliver new tactics, or prune server entries which
  1407. // were potential candidates; nor is the target re-adjusted after fetching
  1408. // new server entries during this establishment.
  1409. tunnelPoolSize := p.Int(parameters.TunnelPoolSize)
  1410. if controller.config.PacketTunnelTunFileDescriptor > 0 ||
  1411. controller.config.TargetServerEntry != "" {
  1412. tunnelPoolSize = 1
  1413. }
  1414. p.Close()
  1415. // Trigger CandidateServers and AvailableEgressRegions notices. By default,
  1416. // this is an asynchronous operation, as the underlying full server entry
  1417. // list enumeration may be a slow operation. In certain cases, where
  1418. // candidate counts are required up front, await the result before
  1419. // proceeding.
  1420. awaitResponse := tunnelPoolSize > 1 ||
  1421. controller.protocolSelectionConstraints.initialLimitTunnelProtocolsCandidateCount > 0
  1422. // AvailableEgressRegions: after a fresh install, the outer client may not
  1423. // have a list of regions to display; and LimitTunnelProtocols may reduce the
  1424. // number of available regions.
  1425. //
  1426. // When the outer client receives NoticeAvailableEgressRegions and the
  1427. // configured EgressRegion is not included in the region list, the outer
  1428. // client _should_ stop tunnel-core and prompt the user to change the region
  1429. // selection, as there are insufficient servers/capabilities to establish a
  1430. // tunnel in the selected region.
  1431. //
  1432. // This report is delayed until after tactics are likely to be applied,
  1433. // above; this avoids a ReportAvailableRegions reporting too many regions,
  1434. // followed shortly by a ReportAvailableRegions reporting fewer regions. That
  1435. // sequence could cause issues in the outer client UI.
  1436. //
  1437. // The reported regions are limited by protocolSelectionConstraints; in the
  1438. // case where an initial limit is in place, only regions available for the
  1439. // initial limit are reported. The initial phase will not complete if
  1440. // EgressRegion is set such that there are no server entries with the
  1441. // necessary protocol capabilities (either locally or from a remote server
  1442. // list fetch).
  1443. // Concurrency note: controller.protocolSelectionConstraints may be
  1444. // overwritten before serverEntriesReporter reads it, and so cannot be
  1445. // accessed directly by serverEntriesReporter.
  1446. reportRequest := &serverEntriesReportRequest{
  1447. constraints: controller.protocolSelectionConstraints,
  1448. }
  1449. if awaitResponse {
  1450. // Buffer size of 1 ensures the sender, serverEntryReporter, won't block on
  1451. // sending the response in the case where launchEstablishing exits due to
  1452. // stopping establishment.
  1453. reportRequest.awaitResponse = make(chan *serverEntriesReportResponse, 1)
  1454. }
  1455. controller.signalServerEntriesReporter(reportRequest)
  1456. if awaitResponse {
  1457. var reportResponse *serverEntriesReportResponse
  1458. select {
  1459. case reportResponse = <-reportRequest.awaitResponse:
  1460. case <-controller.establishCtx.Done():
  1461. // The sender may be gone when shutting down, or may not send until after
  1462. // stopping establishment.
  1463. return
  1464. }
  1465. if reportResponse.err != nil {
  1466. NoticeError("failed to report server entries: %v",
  1467. errors.Trace(reportResponse.err))
  1468. controller.SignalComponentFailure()
  1469. return
  1470. }
  1471. // Make adjustments based on candidate counts.
  1472. if tunnelPoolSize > 1 {
  1473. // Initial canidate count is ignored as count candidates will eventually
  1474. // become available.
  1475. if reportResponse.candidates < tunnelPoolSize {
  1476. tunnelPoolSize = reportResponse.candidates
  1477. }
  1478. if tunnelPoolSize < 1 {
  1479. tunnelPoolSize = 1
  1480. }
  1481. }
  1482. controller.setTunnelPoolSize(tunnelPoolSize)
  1483. // If InitialLimitTunnelProtocols is configured but cannot be satisfied,
  1484. // skip the initial phase in this establishment. This avoids spinning,
  1485. // unable to connect, in this case. InitialLimitTunnelProtocols is
  1486. // intended to prioritize certain protocols, but not strictly select them.
  1487. //
  1488. // The candidate count check ignores egress region selection. When an egress
  1489. // region is selected, it's the responsibility of the outer client to react
  1490. // to the following ReportAvailableRegions output and clear the user's
  1491. // selected region to prevent spinning, unable to connect. The initial phase
  1492. // is skipped only when InitialLimitTunnelProtocols cannot be satisfied
  1493. // _regardless_ of region selection.
  1494. //
  1495. // We presume that, in practise, most clients will have embedded server
  1496. // entries with capabilities for most protocols; and that clients will
  1497. // often perform RSL checks. So clients should most often have the
  1498. // necessary capabilities to satisfy InitialLimitTunnelProtocols. When
  1499. // this check fails, RSL/OSL/upgrade checks are triggered in order to gain
  1500. // new capabilities.
  1501. //
  1502. // LimitTunnelProtocols remains a hard limit, as using prohibited
  1503. // protocols may have some bad effect, such as a firewall blocking all
  1504. // traffic from a host.
  1505. if controller.protocolSelectionConstraints.initialLimitTunnelProtocolsCandidateCount > 0 {
  1506. if reportResponse.initialCandidatesAnyEgressRegion == 0 {
  1507. NoticeWarning("skipping initial limit tunnel protocols")
  1508. controller.protocolSelectionConstraints.initialLimitTunnelProtocolsCandidateCount = 0
  1509. // Since we were unable to satisfy the InitialLimitTunnelProtocols
  1510. // tactic, trigger RSL, OSL, and upgrade fetches to potentially
  1511. // gain new capabilities.
  1512. controller.triggerFetches()
  1513. }
  1514. }
  1515. }
  1516. for i := 0; i < workerPoolSize; i++ {
  1517. controller.establishWaitGroup.Add(1)
  1518. go controller.establishTunnelWorker()
  1519. }
  1520. controller.establishWaitGroup.Add(1)
  1521. go controller.establishCandidateGenerator()
  1522. }
  1523. // stopEstablishing signals the establish goroutines to stop and waits
  1524. // for the group to halt.
  1525. func (controller *Controller) stopEstablishing() {
  1526. if !controller.isEstablishing {
  1527. return
  1528. }
  1529. NoticeInfo("stop establishing")
  1530. controller.stopEstablish()
  1531. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  1532. // (as it may be sending to that channel).
  1533. controller.establishWaitGroup.Wait()
  1534. NoticeInfo("stopped establishing")
  1535. controller.isEstablishing = false
  1536. controller.establishStartTime = time.Time{}
  1537. controller.establishCtx = nil
  1538. controller.stopEstablish = nil
  1539. controller.establishWaitGroup = nil
  1540. controller.candidateServerEntries = nil
  1541. controller.serverAffinityDoneBroadcast = nil
  1542. controller.concurrentEstablishTunnelsMutex.Lock()
  1543. peakConcurrent := controller.peakConcurrentEstablishTunnels
  1544. peakConcurrentIntensive := controller.peakConcurrentIntensiveEstablishTunnels
  1545. controller.establishConnectTunnelCount = 0
  1546. controller.concurrentEstablishTunnels = 0
  1547. controller.concurrentIntensiveEstablishTunnels = 0
  1548. controller.peakConcurrentEstablishTunnels = 0
  1549. controller.peakConcurrentIntensiveEstablishTunnels = 0
  1550. controller.concurrentEstablishTunnelsMutex.Unlock()
  1551. NoticeInfo("peak concurrent establish tunnels: %d", peakConcurrent)
  1552. NoticeInfo("peak concurrent resource intensive establish tunnels: %d", peakConcurrentIntensive)
  1553. emitMemoryMetrics()
  1554. DoGarbageCollection()
  1555. // Record datastore metrics after establishment, the phase which generates
  1556. // the bulk of all datastore transactions: iterating over server entries,
  1557. // storing new server entries, etc.
  1558. emitDatastoreMetrics()
  1559. // Similarly, establishment generates the bulk of domain resolves.
  1560. emitDNSMetrics(controller.resolver)
  1561. }
  1562. // establishCandidateGenerator populates the candidate queue with server entries
  1563. // from the data store. Server entries are iterated in rank order, so that promoted
  1564. // servers with higher rank are priority candidates.
  1565. func (controller *Controller) establishCandidateGenerator() {
  1566. defer controller.establishWaitGroup.Done()
  1567. defer close(controller.candidateServerEntries)
  1568. // networkWaitDuration is the elapsed time spent waiting
  1569. // for network connectivity. This duration will be excluded
  1570. // from reported tunnel establishment duration.
  1571. var totalNetworkWaitDuration time.Duration
  1572. applyServerAffinity, iterator, err := NewServerEntryIterator(controller.config)
  1573. if err != nil {
  1574. NoticeError("failed to iterate over candidates: %v", errors.Trace(err))
  1575. controller.SignalComponentFailure()
  1576. return
  1577. }
  1578. defer iterator.Close()
  1579. // TODO: reconcile server affinity scheme with multi-tunnel mode
  1580. if controller.getTunnelPoolSize() > 1 {
  1581. applyServerAffinity = false
  1582. }
  1583. isServerAffinityCandidate := true
  1584. if !applyServerAffinity {
  1585. isServerAffinityCandidate = false
  1586. close(controller.serverAffinityDoneBroadcast)
  1587. }
  1588. loop:
  1589. // Repeat until stopped
  1590. for {
  1591. // A "round" consists of a new shuffle of the server entries and attempted
  1592. // connections up to the end of the server entry iterator, or
  1593. // parameters.EstablishTunnelWorkTime elapsed. Time spent waiting for
  1594. // network connectivity is excluded from round elapsed time.
  1595. //
  1596. // After a round, if parameters.EstablishTunnelWorkTime has elapsed in total
  1597. // with no tunnel established, remote server list and upgrade checks are
  1598. // triggered.
  1599. //
  1600. // A complete server entry iteration does not trigger fetches since it's
  1601. // possible to have fewer than parameters.ConnectionWorkerPoolSize
  1602. // candidates, in which case rounds end instantly due to the complete server
  1603. // entry iteration. An exception is made for an empty server entry iterator;
  1604. // in that case fetches may be triggered immediately.
  1605. //
  1606. // The number of server candidates may change during this loop, due to
  1607. // remote server list fetches. Due to the performance impact, we will not
  1608. // trigger additional, informational CandidateServer notices while in the
  1609. // establishing loop. Clients typically re-establish often enough that we
  1610. // will see the effect of the remote server list fetch in diagnostics.
  1611. roundStartTime := time.Now()
  1612. var roundNetworkWaitDuration time.Duration
  1613. workTime := controller.config.GetParameters().Get().Duration(
  1614. parameters.EstablishTunnelWorkTime)
  1615. candidateServerEntryCount := 0
  1616. // Send each iterator server entry to the establish workers
  1617. for {
  1618. networkWaitStartTime := time.Now()
  1619. if !WaitForNetworkConnectivity(
  1620. controller.establishCtx,
  1621. controller.config.NetworkConnectivityChecker) {
  1622. break loop
  1623. }
  1624. networkWaitDuration := time.Since(networkWaitStartTime)
  1625. roundNetworkWaitDuration += networkWaitDuration
  1626. totalNetworkWaitDuration += networkWaitDuration
  1627. serverEntry, err := iterator.Next()
  1628. if err != nil {
  1629. NoticeError("failed to get next candidate: %v", errors.Trace(err))
  1630. controller.SignalComponentFailure()
  1631. break loop
  1632. }
  1633. if serverEntry == nil {
  1634. // Completed this iteration
  1635. NoticeInfo("completed server entry iteration")
  1636. break
  1637. }
  1638. if controller.config.TargetApiProtocol == protocol.PSIPHON_SSH_API_PROTOCOL &&
  1639. !serverEntry.SupportsSSHAPIRequests() {
  1640. continue
  1641. }
  1642. candidateServerEntryCount += 1
  1643. // adjustedEstablishStartTime is establishStartTime shifted
  1644. // to exclude time spent waiting for network connectivity.
  1645. adjustedEstablishStartTime := controller.establishStartTime.Add(
  1646. totalNetworkWaitDuration)
  1647. candidate := &candidateServerEntry{
  1648. serverEntry: serverEntry,
  1649. isServerAffinityCandidate: isServerAffinityCandidate,
  1650. adjustedEstablishStartTime: adjustedEstablishStartTime,
  1651. }
  1652. wasServerAffinityCandidate := isServerAffinityCandidate
  1653. // Note: there must be only one server affinity candidate, as it
  1654. // closes the serverAffinityDoneBroadcast channel.
  1655. isServerAffinityCandidate = false
  1656. // TODO: here we could generate multiple candidates from the
  1657. // server entry when there are many MeekFrontingAddresses.
  1658. select {
  1659. case controller.candidateServerEntries <- candidate:
  1660. case <-controller.establishCtx.Done():
  1661. break loop
  1662. }
  1663. if time.Since(roundStartTime)-roundNetworkWaitDuration > workTime {
  1664. // Start over, after a brief pause, with a new shuffle of the server
  1665. // entries, and potentially some newly fetched server entries.
  1666. break
  1667. }
  1668. if wasServerAffinityCandidate {
  1669. // Don't start the next candidate until either the server affinity
  1670. // candidate has completed (success or failure) or is still working
  1671. // and the grace period has elapsed.
  1672. gracePeriod := controller.config.GetParameters().Get().Duration(
  1673. parameters.EstablishTunnelServerAffinityGracePeriod)
  1674. if gracePeriod > 0 {
  1675. timer := time.NewTimer(gracePeriod)
  1676. select {
  1677. case <-timer.C:
  1678. case <-controller.serverAffinityDoneBroadcast:
  1679. case <-controller.establishCtx.Done():
  1680. timer.Stop()
  1681. break loop
  1682. }
  1683. timer.Stop()
  1684. }
  1685. }
  1686. }
  1687. // Free up resources now, but don't reset until after the pause.
  1688. iterator.Close()
  1689. // Trigger RSL, OSL, and upgrade checks after failing to establish a
  1690. // tunnel within parameters.EstablishTunnelWorkTime, or if there are
  1691. // no server entries present.
  1692. //
  1693. // While the trigger is made after each round,
  1694. // parameter.FetchRemoteServerListStalePeriod will limit the actual
  1695. // frequency of fetches. Continuing to trigger allows for very long running
  1696. // establishments to perhaps eventually succeed.
  1697. //
  1698. // No fetches are triggered when TargetServerEntry is specified. In that
  1699. // case, we're only trying to connect to a specific server entry.
  1700. if (candidateServerEntryCount == 0 ||
  1701. time.Since(controller.establishStartTime)-totalNetworkWaitDuration > workTime) &&
  1702. controller.config.TargetServerEntry == "" {
  1703. controller.triggerFetches()
  1704. }
  1705. // After a complete iteration of candidate servers, pause before iterating again.
  1706. // This helps avoid some busy wait loop conditions, and also allows some time for
  1707. // network conditions to change. Also allows for fetch remote to complete,
  1708. // in typical conditions (it isn't strictly necessary to wait for this, there will
  1709. // be more rounds if required).
  1710. p := controller.config.GetParameters().Get()
  1711. timeout := prng.JitterDuration(
  1712. p.Duration(parameters.EstablishTunnelPausePeriod),
  1713. p.Float(parameters.EstablishTunnelPausePeriodJitter))
  1714. p.Close()
  1715. timer := time.NewTimer(timeout)
  1716. select {
  1717. case <-timer.C:
  1718. // Retry iterating
  1719. case <-controller.establishCtx.Done():
  1720. timer.Stop()
  1721. break loop
  1722. }
  1723. timer.Stop()
  1724. iterator.Reset()
  1725. }
  1726. }
  1727. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  1728. // a connection to the tunnel server, and delivers the connected tunnel to a channel.
  1729. func (controller *Controller) establishTunnelWorker() {
  1730. defer controller.establishWaitGroup.Done()
  1731. loop:
  1732. for candidateServerEntry := range controller.candidateServerEntries {
  1733. // Note: don't receive from candidateServerEntries and isStopEstablishing
  1734. // in the same select, since we want to prioritize receiving the stop signal
  1735. if controller.isStopEstablishing() {
  1736. break loop
  1737. }
  1738. // There may already be a tunnel to this candidate. If so, skip it.
  1739. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  1740. continue
  1741. }
  1742. // TODO: we allow multiple, concurrent workers to attempt to connect to the
  1743. // same server. This is not wasteful if the server supports several
  1744. // different protocols, some of which may be blocked while others are not
  1745. // blocked. Limiting protocols with [Initial]LimitTunnelProtocols may make
  1746. // these multiple attempts redundent. Also, replay should be used only by
  1747. // the first attempt.
  1748. // upstreamProxyErrorCallback will post NoticeUpstreamProxyError when the
  1749. // tunnel dial fails due to an upstream proxy error. As the upstream proxy
  1750. // is user configured, the error message may need to be relayed to the user.
  1751. // As the callback may be invoked after establishment is over (e.g., if an
  1752. // initial dial isn't fully shutdown when ConnectTunnel returns; or a meek
  1753. // underlying TCP connection re-dial) don't access these variables
  1754. // directly.
  1755. callbackCandidateServerEntry := candidateServerEntry
  1756. callbackEstablishCtx := controller.establishCtx
  1757. upstreamProxyErrorCallback := func(err error) {
  1758. // Do not post the notice when overall establishment context is canceled or
  1759. // timed-out: the upstream proxy connection error is likely a result of the
  1760. // cancellation, and not a condition to be fixed by the user. In the case
  1761. // of meek underlying TCP connection re-dials, this condition will always
  1762. // be true; however in this case the initial dial succeeded with the
  1763. // current upstream proxy settings, so any upstream proxy error is
  1764. // transient.
  1765. if callbackEstablishCtx.Err() != nil {
  1766. return
  1767. }
  1768. // Another class of non-fatal upstream proxy error arises from proxies
  1769. // which limit permitted proxied ports. In this case, some tunnels may fail
  1770. // due to dial port, while others may eventually succeed. To avoid this
  1771. // class of errors, delay posting the notice. If the upstream proxy works,
  1772. // _some_ tunnel should connect. If the upstream proxy configuration is
  1773. // broken, the error should persist and eventually get posted.
  1774. p := controller.config.GetParameters().Get()
  1775. workerPoolSize := p.Int(parameters.ConnectionWorkerPoolSize)
  1776. minWaitDuration := p.Duration(parameters.UpstreamProxyErrorMinWaitDuration)
  1777. maxWaitDuration := p.Duration(parameters.UpstreamProxyErrorMaxWaitDuration)
  1778. p.Close()
  1779. controller.concurrentEstablishTunnelsMutex.Lock()
  1780. establishConnectTunnelCount := controller.establishConnectTunnelCount
  1781. controller.concurrentEstablishTunnelsMutex.Unlock()
  1782. // Delay UpstreamProxyErrorMinWaitDuration (excluding time spent waiting
  1783. // for network connectivity) and then until either
  1784. // UpstreamProxyErrorMaxWaitDuration has elapsed or, to post sooner if many
  1785. // candidates are failing, at least workerPoolSize tunnel connection
  1786. // attempts have completed. We infer that at least workerPoolSize
  1787. // candidates have completed by checking that at least 2*workerPoolSize
  1788. // candidates have started.
  1789. elapsedTime := time.Since(
  1790. callbackCandidateServerEntry.adjustedEstablishStartTime)
  1791. if elapsedTime < minWaitDuration ||
  1792. (elapsedTime < maxWaitDuration &&
  1793. establishConnectTunnelCount < 2*workerPoolSize) {
  1794. return
  1795. }
  1796. NoticeUpstreamProxyError(err)
  1797. }
  1798. // Select the tunnel protocol. The selection will be made at random
  1799. // from protocols supported by the server entry, optionally limited by
  1800. // LimitTunnelProtocols.
  1801. //
  1802. // When limiting concurrent resource intensive protocol connection
  1803. // workers, and at the limit, do not select resource intensive
  1804. // protocols since otherwise the candidate must be skipped.
  1805. //
  1806. // If at the limit and unabled to select a non-intensive protocol,
  1807. // skip the candidate entirely and move on to the next. Since
  1808. // candidates are shuffled it's likely that the next candidate is not
  1809. // intensive. In this case, a StaggerConnectionWorkersMilliseconds
  1810. // delay may still be incurred.
  1811. limitIntensiveConnectionWorkers := controller.config.GetParameters().Get().Int(
  1812. parameters.LimitIntensiveConnectionWorkers)
  1813. controller.concurrentEstablishTunnelsMutex.Lock()
  1814. excludeIntensive := false
  1815. if limitIntensiveConnectionWorkers > 0 &&
  1816. controller.concurrentIntensiveEstablishTunnels >= limitIntensiveConnectionWorkers {
  1817. excludeIntensive = true
  1818. }
  1819. canReplay := func(serverEntry *protocol.ServerEntry, replayProtocol string) bool {
  1820. return controller.protocolSelectionConstraints.canReplay(
  1821. controller.establishConnectTunnelCount,
  1822. excludeIntensive,
  1823. serverEntry,
  1824. replayProtocol)
  1825. }
  1826. selectProtocol := func(serverEntry *protocol.ServerEntry) (string, bool) {
  1827. return controller.protocolSelectionConstraints.selectProtocol(
  1828. controller.establishConnectTunnelCount,
  1829. excludeIntensive,
  1830. serverEntry)
  1831. }
  1832. // MakeDialParameters may return a replay instance, if the server
  1833. // entry has a previous, recent successful connection and
  1834. // tactics/config has not changed.
  1835. //
  1836. // In the first round -- and later rounds, with some probability -- of
  1837. // establishing, ServerEntryIterator will move potential replay candidates
  1838. // to the front of the iterator after the random shuffle, which greatly
  1839. // prioritizes previously successful servers for that round.
  1840. //
  1841. // As ServerEntryIterator does not unmarshal and validate replay
  1842. // candidate dial parameters, some potential replay candidates may
  1843. // have expired or otherwise ineligible dial parameters; in this case
  1844. // the candidate proceeds without replay.
  1845. //
  1846. // The ReplayCandidateCount tactic determines how many candidates may use
  1847. // replay. After ReplayCandidateCount candidates of any type, replay or no,
  1848. // replay is skipped. If ReplayCandidateCount exceeds the intial round,
  1849. // replay may still be performed but the iterator may no longer move
  1850. // potential replay server entries to the front. When ReplayCandidateCount
  1851. // is set to -1, unlimited candidates may use replay.
  1852. dialParams, err := MakeDialParameters(
  1853. controller.config,
  1854. controller.steeringIPCache,
  1855. upstreamProxyErrorCallback,
  1856. canReplay,
  1857. selectProtocol,
  1858. candidateServerEntry.serverEntry,
  1859. false,
  1860. controller.establishConnectTunnelCount,
  1861. int(atomic.LoadInt32(&controller.establishedTunnelsCount)))
  1862. if dialParams == nil || err != nil {
  1863. controller.concurrentEstablishTunnelsMutex.Unlock()
  1864. // MakeDialParameters returns nil/nil when the server entry is to
  1865. // be skipped. See MakeDialParameters for skip cases and skip
  1866. // logging. Silently fail the candidate in this case. Otherwise,
  1867. // emit error.
  1868. if err != nil {
  1869. NoticeInfo("failed to make dial parameters for %s: %v",
  1870. candidateServerEntry.serverEntry.GetDiagnosticID(),
  1871. errors.Trace(err))
  1872. }
  1873. // Unblock other candidates immediately when server affinity
  1874. // candidate is skipped.
  1875. if candidateServerEntry.isServerAffinityCandidate {
  1876. close(controller.serverAffinityDoneBroadcast)
  1877. }
  1878. continue
  1879. }
  1880. // Increment establishConnectTunnelCount only after selectProtocol has
  1881. // succeeded to ensure InitialLimitTunnelProtocolsCandidateCount
  1882. // candidates use InitialLimitTunnelProtocols.
  1883. establishConnectTunnelCount := controller.establishConnectTunnelCount
  1884. controller.establishConnectTunnelCount += 1
  1885. isIntensive := protocol.TunnelProtocolIsResourceIntensive(dialParams.TunnelProtocol)
  1886. if isIntensive {
  1887. controller.concurrentIntensiveEstablishTunnels += 1
  1888. if controller.concurrentIntensiveEstablishTunnels > controller.peakConcurrentIntensiveEstablishTunnels {
  1889. controller.peakConcurrentIntensiveEstablishTunnels = controller.concurrentIntensiveEstablishTunnels
  1890. }
  1891. }
  1892. controller.concurrentEstablishTunnels += 1
  1893. if controller.concurrentEstablishTunnels > controller.peakConcurrentEstablishTunnels {
  1894. controller.peakConcurrentEstablishTunnels = controller.concurrentEstablishTunnels
  1895. }
  1896. controller.concurrentEstablishTunnelsMutex.Unlock()
  1897. // Apply stagger only now that we're past MakeDialParameters and
  1898. // protocol selection logic which may have caused the candidate to be
  1899. // skipped. The stagger logic delays dialing, and we don't want to
  1900. // incur that delay that when skipping.
  1901. //
  1902. // Locking staggerMutex serializes staggers, so that multiple workers
  1903. // don't simply sleep in parallel.
  1904. //
  1905. // The stagger is applied when establishConnectTunnelCount > 0 -- that
  1906. // is, for all but the first dial.
  1907. p := controller.config.GetParameters().Get()
  1908. staggerPeriod := p.Duration(parameters.StaggerConnectionWorkersPeriod)
  1909. staggerJitter := p.Float(parameters.StaggerConnectionWorkersJitter)
  1910. p.Close()
  1911. if establishConnectTunnelCount > 0 && staggerPeriod != 0 {
  1912. controller.staggerMutex.Lock()
  1913. timer := time.NewTimer(prng.JitterDuration(staggerPeriod, staggerJitter))
  1914. select {
  1915. case <-timer.C:
  1916. case <-controller.establishCtx.Done():
  1917. }
  1918. timer.Stop()
  1919. controller.staggerMutex.Unlock()
  1920. }
  1921. // ConnectTunnel will allocate significant memory, so first attempt to
  1922. // reclaim as much as possible.
  1923. DoGarbageCollection()
  1924. tunnel, err := ConnectTunnel(
  1925. controller.establishCtx,
  1926. controller.config,
  1927. candidateServerEntry.adjustedEstablishStartTime,
  1928. dialParams)
  1929. controller.concurrentEstablishTunnelsMutex.Lock()
  1930. if isIntensive {
  1931. controller.concurrentIntensiveEstablishTunnels -= 1
  1932. }
  1933. controller.concurrentEstablishTunnels -= 1
  1934. controller.concurrentEstablishTunnelsMutex.Unlock()
  1935. // Periodically emit memory metrics during the establishment cycle.
  1936. if !controller.isStopEstablishing() {
  1937. emitMemoryMetrics()
  1938. }
  1939. // Immediately reclaim memory allocated by the establishment. In the case
  1940. // of failure, first clear the reference to the tunnel. In the case of
  1941. // success, the garbage collection may still be effective as the initial
  1942. // phases of some protocols involve significant memory allocation that
  1943. // could now be reclaimed.
  1944. if err != nil {
  1945. tunnel = nil
  1946. }
  1947. DoGarbageCollection()
  1948. if err != nil {
  1949. // Unblock other candidates immediately when server affinity
  1950. // candidate fails.
  1951. if candidateServerEntry.isServerAffinityCandidate {
  1952. close(controller.serverAffinityDoneBroadcast)
  1953. }
  1954. // Before emitting error, check if establish interrupted, in which
  1955. // case the error is noise.
  1956. if controller.isStopEstablishing() {
  1957. break loop
  1958. }
  1959. NoticeInfo("failed to connect to %s: %v",
  1960. candidateServerEntry.serverEntry.GetDiagnosticID(),
  1961. errors.Trace(err))
  1962. continue
  1963. }
  1964. // Deliver connected tunnel.
  1965. // Don't block. Assumes the receiver has a buffer large enough for
  1966. // the number of desired tunnels. If there's no room, the tunnel must
  1967. // not be required so it's discarded.
  1968. select {
  1969. case controller.connectedTunnels <- tunnel:
  1970. default:
  1971. controller.discardTunnel(tunnel)
  1972. // Clear the reference to this discarded tunnel and immediately run
  1973. // a garbage collection to reclaim its memory.
  1974. tunnel = nil
  1975. DoGarbageCollection()
  1976. }
  1977. // Unblock other candidates only after delivering when
  1978. // server affinity candidate succeeds.
  1979. if candidateServerEntry.isServerAffinityCandidate {
  1980. close(controller.serverAffinityDoneBroadcast)
  1981. }
  1982. }
  1983. }
  1984. func (controller *Controller) isStopEstablishing() bool {
  1985. select {
  1986. case <-controller.establishCtx.Done():
  1987. return true
  1988. default:
  1989. }
  1990. return false
  1991. }