controller.go 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846
  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. "errors"
  27. "fmt"
  28. "math/rand"
  29. "net"
  30. "sync"
  31. "time"
  32. "github.com/Psiphon-Labs/goarista/monotime"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  38. )
  39. // Controller is a tunnel lifecycle coordinator. It manages lists of servers to
  40. // connect to; establishes and monitors tunnels; and runs local proxies which
  41. // route traffic through the tunnels.
  42. type Controller struct {
  43. config *Config
  44. sessionId string
  45. runCtx context.Context
  46. stopRunning context.CancelFunc
  47. runWaitGroup *sync.WaitGroup
  48. connectedTunnels chan *Tunnel
  49. failedTunnels chan *Tunnel
  50. tunnelMutex sync.Mutex
  51. establishedOnce bool
  52. tunnels []*Tunnel
  53. nextTunnel int
  54. startedConnectedReporter bool
  55. isEstablishing bool
  56. concurrentEstablishTunnelsMutex sync.Mutex
  57. concurrentEstablishTunnels int
  58. concurrentMeekEstablishTunnels int
  59. peakConcurrentEstablishTunnels int
  60. peakConcurrentMeekEstablishTunnels int
  61. establishCtx context.Context
  62. stopEstablish context.CancelFunc
  63. establishWaitGroup *sync.WaitGroup
  64. candidateServerEntries chan *candidateServerEntry
  65. untunneledDialConfig *DialConfig
  66. splitTunnelClassifier *SplitTunnelClassifier
  67. signalFetchCommonRemoteServerList chan struct{}
  68. signalFetchObfuscatedServerLists chan struct{}
  69. signalDownloadUpgrade chan string
  70. impairedProtocolClassification map[string]int
  71. signalReportConnected chan struct{}
  72. serverAffinityDoneBroadcast chan struct{}
  73. packetTunnelClient *tun.Client
  74. packetTunnelTransport *PacketTunnelTransport
  75. }
  76. type candidateServerEntry struct {
  77. serverEntry *protocol.ServerEntry
  78. isServerAffinityCandidate bool
  79. usePriorityProtocol bool
  80. impairedProtocols []string
  81. adjustedEstablishStartTime monotime.Time
  82. }
  83. // NewController initializes a new controller.
  84. func NewController(config *Config) (controller *Controller, err error) {
  85. if !config.IsCommitted() {
  86. return nil, common.ContextError(errors.New("uncommitted config"))
  87. }
  88. // Needed by regen, at least
  89. rand.Seed(int64(time.Now().Nanosecond()))
  90. // The session ID for the Psiphon server API is used across all
  91. // tunnels established by the controller.
  92. NoticeSessionId(config.SessionID)
  93. untunneledDialConfig := &DialConfig{
  94. UpstreamProxyURL: config.UpstreamProxyURL,
  95. CustomHeaders: config.CustomHeaders,
  96. DeviceBinder: config.deviceBinder,
  97. DnsServerGetter: config.DnsServerGetter,
  98. IPv6Synthesizer: config.IPv6Synthesizer,
  99. UseIndistinguishableTLS: config.UseIndistinguishableTLS,
  100. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  101. }
  102. controller = &Controller{
  103. config: config,
  104. sessionId: config.SessionID,
  105. runWaitGroup: new(sync.WaitGroup),
  106. // connectedTunnels and failedTunnels buffer sizes are large enough to
  107. // receive full pools of tunnels without blocking. Senders should not block.
  108. connectedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  109. failedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  110. tunnels: make([]*Tunnel, 0),
  111. establishedOnce: false,
  112. startedConnectedReporter: false,
  113. isEstablishing: false,
  114. untunneledDialConfig: untunneledDialConfig,
  115. impairedProtocolClassification: make(map[string]int),
  116. // TODO: Add a buffer of 1 so we don't miss a signal while receiver is
  117. // starting? Trade-off is potential back-to-back fetch remotes. As-is,
  118. // establish will eventually signal another fetch remote.
  119. signalFetchCommonRemoteServerList: make(chan struct{}),
  120. signalFetchObfuscatedServerLists: make(chan struct{}),
  121. signalDownloadUpgrade: make(chan string),
  122. signalReportConnected: make(chan struct{}),
  123. }
  124. controller.splitTunnelClassifier = NewSplitTunnelClassifier(config, controller)
  125. if config.PacketTunnelTunFileDescriptor > 0 {
  126. // Run a packet tunnel client. The lifetime of the tun.Client is the
  127. // lifetime of the Controller, so it exists across tunnel establishments
  128. // and reestablishments. The PacketTunnelTransport provides a layer
  129. // that presents a continuosuly existing transport to the tun.Client;
  130. // it's set to use new SSH channels after new SSH tunnel establishes.
  131. packetTunnelTransport := NewPacketTunnelTransport()
  132. packetTunnelClient, err := tun.NewClient(&tun.ClientConfig{
  133. Logger: NoticeCommonLogger(),
  134. TunFileDescriptor: config.PacketTunnelTunFileDescriptor,
  135. Transport: packetTunnelTransport,
  136. })
  137. if err != nil {
  138. return nil, common.ContextError(err)
  139. }
  140. controller.packetTunnelClient = packetTunnelClient
  141. controller.packetTunnelTransport = packetTunnelTransport
  142. }
  143. return controller, nil
  144. }
  145. // Run executes the controller. Run exits if a controller
  146. // component fails or the parent context is canceled.
  147. func (controller *Controller) Run(ctx context.Context) {
  148. // Ensure fresh repetitive notice state for each run, so the
  149. // client will always get an AvailableEgressRegions notice,
  150. // an initial instance of any repetitive error notice, etc.
  151. ResetRepetitiveNotices()
  152. runCtx, stopRunning := context.WithCancel(ctx)
  153. defer stopRunning()
  154. controller.runCtx = runCtx
  155. controller.stopRunning = stopRunning
  156. // Start components
  157. // TODO: IPv6 support
  158. var listenIP string
  159. if controller.config.ListenInterface == "" {
  160. listenIP = "127.0.0.1"
  161. } else if controller.config.ListenInterface == "any" {
  162. listenIP = "0.0.0.0"
  163. } else {
  164. IPv4Address, _, err := common.GetInterfaceIPAddresses(controller.config.ListenInterface)
  165. if err == nil && IPv4Address == nil {
  166. err = fmt.Errorf("no IPv4 address for interface %s", controller.config.ListenInterface)
  167. }
  168. if err != nil {
  169. NoticeError("error getting listener IP: %s", err)
  170. return
  171. }
  172. listenIP = IPv4Address.String()
  173. }
  174. if !controller.config.DisableLocalSocksProxy {
  175. socksProxy, err := NewSocksProxy(controller.config, controller, listenIP)
  176. if err != nil {
  177. NoticeAlert("error initializing local SOCKS proxy: %s", err)
  178. return
  179. }
  180. defer socksProxy.Close()
  181. }
  182. if !controller.config.DisableLocalHTTPProxy {
  183. httpProxy, err := NewHttpProxy(controller.config, controller, listenIP)
  184. if err != nil {
  185. NoticeAlert("error initializing local HTTP proxy: %s", err)
  186. return
  187. }
  188. defer httpProxy.Close()
  189. }
  190. if !controller.config.DisableRemoteServerListFetcher {
  191. if controller.config.RemoteServerListURLs != nil {
  192. controller.runWaitGroup.Add(1)
  193. go controller.remoteServerListFetcher(
  194. "common",
  195. FetchCommonRemoteServerList,
  196. controller.signalFetchCommonRemoteServerList)
  197. }
  198. if controller.config.ObfuscatedServerListRootURLs != nil {
  199. controller.runWaitGroup.Add(1)
  200. go controller.remoteServerListFetcher(
  201. "obfuscated",
  202. FetchObfuscatedServerLists,
  203. controller.signalFetchObfuscatedServerLists)
  204. }
  205. }
  206. if controller.config.UpgradeDownloadURLs != nil {
  207. controller.runWaitGroup.Add(1)
  208. go controller.upgradeDownloader()
  209. }
  210. /// Note: the connected reporter isn't started until a tunnel is
  211. // established
  212. controller.runWaitGroup.Add(1)
  213. go controller.runTunnels()
  214. controller.runWaitGroup.Add(1)
  215. go controller.establishTunnelWatcher()
  216. if controller.packetTunnelClient != nil {
  217. controller.packetTunnelClient.Start()
  218. }
  219. // Wait while running
  220. <-controller.runCtx.Done()
  221. NoticeInfo("controller stopped")
  222. if controller.packetTunnelClient != nil {
  223. controller.packetTunnelClient.Stop()
  224. }
  225. // All workers -- runTunnels, establishment workers, and auxilliary
  226. // workers such as fetch remote server list and untunneled uprade
  227. // download -- operate with the controller run context and will all
  228. // be interrupted when the run context is done.
  229. controller.runWaitGroup.Wait()
  230. controller.splitTunnelClassifier.Shutdown()
  231. NoticeInfo("exiting controller")
  232. NoticeExiting()
  233. }
  234. // SignalComponentFailure notifies the controller that an associated component has failed.
  235. // This will terminate the controller.
  236. func (controller *Controller) SignalComponentFailure() {
  237. NoticeAlert("controller shutdown due to component failure")
  238. controller.stopRunning()
  239. }
  240. // SetDynamicConfig overrides the sponsor ID and authorizations fields of the
  241. // Controller config with the input values. The new values will be used in the
  242. // next tunnel connection.
  243. func (controller *Controller) SetDynamicConfig(sponsorID string, authorizations []string) {
  244. controller.config.SetDynamicConfig(sponsorID, authorizations)
  245. }
  246. // TerminateNextActiveTunnel terminates the active tunnel, which will initiate
  247. // establishment of a new tunnel.
  248. func (controller *Controller) TerminateNextActiveTunnel() {
  249. tunnel := controller.getNextActiveTunnel()
  250. if tunnel != nil {
  251. controller.SignalTunnelFailure(tunnel)
  252. NoticeInfo("terminated tunnel: %s", tunnel.serverEntry.IpAddress)
  253. }
  254. }
  255. // remoteServerListFetcher fetches an out-of-band list of server entries
  256. // for more tunnel candidates. It fetches when signalled, with retries
  257. // on failure.
  258. func (controller *Controller) remoteServerListFetcher(
  259. name string,
  260. fetcher RemoteServerListFetcher,
  261. signal <-chan struct{}) {
  262. defer controller.runWaitGroup.Done()
  263. var lastFetchTime monotime.Time
  264. fetcherLoop:
  265. for {
  266. // Wait for a signal before fetching
  267. select {
  268. case <-signal:
  269. case <-controller.runCtx.Done():
  270. break fetcherLoop
  271. }
  272. // Skip fetch entirely (i.e., send no request at all, even when ETag would save
  273. // on response size) when a recent fetch was successful
  274. stalePeriod := controller.config.clientParameters.Get().Duration(
  275. parameters.FetchRemoteServerListStalePeriod)
  276. if lastFetchTime != 0 &&
  277. lastFetchTime.Add(stalePeriod).After(monotime.Now()) {
  278. continue
  279. }
  280. retryLoop:
  281. for attempt := 0; ; attempt++ {
  282. // Don't attempt to fetch while there is no network connectivity,
  283. // to avoid alert notice noise.
  284. if !WaitForNetworkConnectivity(
  285. controller.runCtx,
  286. controller.config.NetworkConnectivityChecker) {
  287. break fetcherLoop
  288. }
  289. // Pick any active tunnel and make the next fetch attempt. If there's
  290. // no active tunnel, the untunneledDialConfig will be used.
  291. tunnel := controller.getNextActiveTunnel()
  292. err := fetcher(
  293. controller.runCtx,
  294. controller.config,
  295. attempt,
  296. tunnel,
  297. controller.untunneledDialConfig)
  298. if err == nil {
  299. lastFetchTime = monotime.Now()
  300. break retryLoop
  301. }
  302. NoticeAlert("failed to fetch %s remote server list: %s", name, err)
  303. retryPeriod := controller.config.clientParameters.Get().Duration(
  304. parameters.FetchRemoteServerListRetryPeriod)
  305. timer := time.NewTimer(retryPeriod)
  306. select {
  307. case <-timer.C:
  308. case <-controller.runCtx.Done():
  309. timer.Stop()
  310. break fetcherLoop
  311. }
  312. }
  313. }
  314. NoticeInfo("exiting %s remote server list fetcher", name)
  315. }
  316. // establishTunnelWatcher terminates the controller if a tunnel
  317. // has not been established in the configured time period. This
  318. // is regardless of how many tunnels are presently active -- meaning
  319. // that if an active tunnel was established and lost the controller
  320. // is left running (to re-establish).
  321. func (controller *Controller) establishTunnelWatcher() {
  322. defer controller.runWaitGroup.Done()
  323. timeout := controller.config.clientParameters.Get().Duration(
  324. parameters.EstablishTunnelTimeout)
  325. if timeout > 0 {
  326. timer := time.NewTimer(timeout)
  327. defer timer.Stop()
  328. select {
  329. case <-timer.C:
  330. if !controller.hasEstablishedOnce() {
  331. NoticeAlert("failed to establish tunnel before timeout")
  332. controller.SignalComponentFailure()
  333. }
  334. case <-controller.runCtx.Done():
  335. }
  336. }
  337. NoticeInfo("exiting establish tunnel watcher")
  338. }
  339. // connectedReporter sends periodic "connected" requests to the Psiphon API.
  340. // These requests are for server-side unique user stats calculation. See the
  341. // comment in DoConnectedRequest for a description of the request mechanism.
  342. // To ensure we don't over- or under-count unique users, only one connected
  343. // request is made across all simultaneous multi-tunnels; and the connected
  344. // request is repeated periodically for very long-lived tunnels.
  345. // The signalReportConnected mechanism is used to trigger another connected
  346. // request immediately after a reconnect.
  347. func (controller *Controller) connectedReporter() {
  348. defer controller.runWaitGroup.Done()
  349. loop:
  350. for {
  351. // Pick any active tunnel and make the next connected request. No error
  352. // is logged if there's no active tunnel, as that's not an unexpected condition.
  353. reported := false
  354. tunnel := controller.getNextActiveTunnel()
  355. if tunnel != nil {
  356. err := tunnel.serverContext.DoConnectedRequest()
  357. if err == nil {
  358. reported = true
  359. } else {
  360. NoticeAlert("failed to make connected request: %s", err)
  361. }
  362. }
  363. // Schedule the next connected request and wait.
  364. // Note: this duration is not a dynamic ClientParameter as
  365. // the daily unique user stats logic specifically requires
  366. // a "connected" request no more or less often than every
  367. // 24 hours.
  368. var duration time.Duration
  369. if reported {
  370. duration = 24 * time.Hour
  371. } else {
  372. duration = controller.config.clientParameters.Get().Duration(
  373. parameters.PsiphonAPIConnectedRequestRetryPeriod)
  374. }
  375. timer := time.NewTimer(duration)
  376. doBreak := false
  377. select {
  378. case <-controller.signalReportConnected:
  379. case <-timer.C:
  380. // Make another connected request
  381. case <-controller.runCtx.Done():
  382. doBreak = true
  383. }
  384. timer.Stop()
  385. if doBreak {
  386. break loop
  387. }
  388. }
  389. NoticeInfo("exiting connected reporter")
  390. }
  391. func (controller *Controller) startOrSignalConnectedReporter() {
  392. // session is nil when DisableApi is set
  393. if controller.config.DisableApi {
  394. return
  395. }
  396. // Start the connected reporter after the first tunnel is established.
  397. // Concurrency note: only the runTunnels goroutine may access startedConnectedReporter.
  398. if !controller.startedConnectedReporter {
  399. controller.startedConnectedReporter = true
  400. controller.runWaitGroup.Add(1)
  401. go controller.connectedReporter()
  402. } else {
  403. select {
  404. case controller.signalReportConnected <- *new(struct{}):
  405. default:
  406. }
  407. }
  408. }
  409. // upgradeDownloader makes periodic attempts to complete a client upgrade
  410. // download. DownloadUpgrade() is resumable, so each attempt has potential for
  411. // getting closer to completion, even in conditions where the download or
  412. // tunnel is repeatedly interrupted.
  413. // An upgrade download is triggered by either a handshake response indicating
  414. // that a new version is available; or after failing to connect, in which case
  415. // it's useful to check, out-of-band, for an upgrade with new circumvention
  416. // capabilities.
  417. // Once the download operation completes successfully, the downloader exits
  418. // and is not run again: either there is not a newer version, or the upgrade
  419. // has been downloaded and is ready to be applied.
  420. // We're assuming that the upgrade will be applied and the entire system
  421. // restarted before another upgrade is to be downloaded.
  422. //
  423. // TODO: refactor upgrade downloader and remote server list fetcher to use
  424. // common code (including the resumable download routines).
  425. //
  426. func (controller *Controller) upgradeDownloader() {
  427. defer controller.runWaitGroup.Done()
  428. var lastDownloadTime monotime.Time
  429. downloadLoop:
  430. for {
  431. // Wait for a signal before downloading
  432. var handshakeVersion string
  433. select {
  434. case handshakeVersion = <-controller.signalDownloadUpgrade:
  435. case <-controller.runCtx.Done():
  436. break downloadLoop
  437. }
  438. stalePeriod := controller.config.clientParameters.Get().Duration(
  439. parameters.FetchUpgradeStalePeriod)
  440. // Unless handshake is explicitly advertizing a new version, skip
  441. // checking entirely when a recent download was successful.
  442. if handshakeVersion == "" &&
  443. lastDownloadTime != 0 &&
  444. lastDownloadTime.Add(stalePeriod).After(monotime.Now()) {
  445. continue
  446. }
  447. retryLoop:
  448. for attempt := 0; ; attempt++ {
  449. // Don't attempt to download while there is no network connectivity,
  450. // to avoid alert notice noise.
  451. if !WaitForNetworkConnectivity(
  452. controller.runCtx,
  453. controller.config.NetworkConnectivityChecker) {
  454. break downloadLoop
  455. }
  456. // Pick any active tunnel and make the next download attempt. If there's
  457. // no active tunnel, the untunneledDialConfig will be used.
  458. tunnel := controller.getNextActiveTunnel()
  459. err := DownloadUpgrade(
  460. controller.runCtx,
  461. controller.config,
  462. attempt,
  463. handshakeVersion,
  464. tunnel,
  465. controller.untunneledDialConfig)
  466. if err == nil {
  467. lastDownloadTime = monotime.Now()
  468. break retryLoop
  469. }
  470. NoticeAlert("failed to download upgrade: %s", err)
  471. timeout := controller.config.clientParameters.Get().Duration(
  472. parameters.FetchUpgradeRetryPeriod)
  473. timer := time.NewTimer(timeout)
  474. select {
  475. case <-timer.C:
  476. case <-controller.runCtx.Done():
  477. timer.Stop()
  478. break downloadLoop
  479. }
  480. }
  481. }
  482. NoticeInfo("exiting upgrade downloader")
  483. }
  484. // runTunnels is the controller tunnel management main loop. It starts and stops
  485. // establishing tunnels based on the target tunnel pool size and the current size
  486. // of the pool. Tunnels are established asynchronously using worker goroutines.
  487. //
  488. // When there are no server entries for the target region/protocol, the
  489. // establishCandidateGenerator will yield no candidates and wait before
  490. // trying again. In the meantime, a remote server entry fetch may supply
  491. // valid candidates.
  492. //
  493. // When a tunnel is established, it's added to the active pool. The tunnel's
  494. // operateTunnel goroutine monitors the tunnel.
  495. //
  496. // When a tunnel fails, it's removed from the pool and the establish process is
  497. // restarted to fill the pool.
  498. func (controller *Controller) runTunnels() {
  499. defer controller.runWaitGroup.Done()
  500. // Start running
  501. controller.startEstablishing()
  502. loop:
  503. for {
  504. select {
  505. case failedTunnel := <-controller.failedTunnels:
  506. NoticeAlert("tunnel failed: %s", failedTunnel.serverEntry.IpAddress)
  507. controller.terminateTunnel(failedTunnel)
  508. controller.classifyImpairedProtocol(failedTunnel)
  509. // Clear the reference to this tunnel before calling startEstablishing,
  510. // which will invoke a garbage collection.
  511. failedTunnel = nil
  512. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing,
  513. // which reference controller.isEstablishing.
  514. controller.startEstablishing()
  515. case connectedTunnel := <-controller.connectedTunnels:
  516. if controller.isImpairedProtocol(connectedTunnel.protocol) {
  517. // Protocol was classified as impaired while this tunnel established.
  518. // This is most likely to occur with TunnelPoolSize > 0. We log the
  519. // event but take no action. Discarding the tunnel would break the
  520. // impaired logic unless we did that (a) only if there are other
  521. // unimpaired protocols; (b) only during the first iteration of the
  522. // ESTABLISH_TUNNEL_WORK_TIME loop. By not discarding here, a true
  523. // impaired protocol may require an extra reconnect.
  524. NoticeAlert("connected tunnel with impaired protocol: %s", connectedTunnel.protocol)
  525. }
  526. // Tunnel establishment has two phases: connection and activation.
  527. //
  528. // Connection is run concurrently by the establishTunnelWorkers, to minimize
  529. // delay when it's not yet known which server and protocol will be available
  530. // and unblocked.
  531. //
  532. // Activation is run serially, here, to minimize the overhead of making a
  533. // handshake request and starting the operateTunnel management worker for a
  534. // tunnel which may be discarded.
  535. //
  536. // When the active tunnel will complete establishment, establishment is
  537. // stopped before activation. This interrupts all connecting tunnels and
  538. // garbage collects their memory. The purpose is to minimize memory
  539. // pressure when the handshake request is made. In the unlikely case that the
  540. // handshake fails, establishment is restarted.
  541. //
  542. // Any delays in stopEstablishing will delay the handshake for the last
  543. // active tunnel.
  544. //
  545. // In the typical case of TunnelPoolSize of 1, only a single handshake is
  546. // performed and the homepages notices file, when used, will not be modifed
  547. // after the NoticeTunnels(1) [i.e., connected] until NoticeTunnels(0) [i.e.,
  548. // disconnected]. For TunnelPoolSize > 1, serial handshakes only ensures that
  549. // each set of emitted NoticeHomepages is contiguous.
  550. active, outstanding := controller.numTunnels()
  551. // discardTunnel will be true here when already fully established.
  552. discardTunnel := (outstanding <= 0)
  553. isFirstTunnel := (active == 0)
  554. isLastTunnel := (outstanding == 1)
  555. if !discardTunnel {
  556. if isLastTunnel {
  557. controller.stopEstablishing()
  558. }
  559. err := connectedTunnel.Activate(controller.runCtx, controller)
  560. if err != nil {
  561. // Assume the Activate failed due to a broken tunnel connection,
  562. // currently the most likely case, and classify as impaired, as in
  563. // the failed tunnel case above.
  564. // TODO: distinguish between network and other errors
  565. controller.classifyImpairedProtocol(connectedTunnel)
  566. NoticeAlert("failed to activate %s: %s", connectedTunnel.serverEntry.IpAddress, err)
  567. discardTunnel = true
  568. } else {
  569. // It's unlikely that registerTunnel will fail, since only this goroutine
  570. // calls registerTunnel -- and after checking numTunnels; so failure is not
  571. // expected.
  572. if !controller.registerTunnel(connectedTunnel) {
  573. NoticeAlert("failed to register %s: %s", connectedTunnel.serverEntry.IpAddress)
  574. discardTunnel = true
  575. }
  576. }
  577. // May need to replace this tunnel
  578. if isLastTunnel && discardTunnel {
  579. controller.startEstablishing()
  580. }
  581. }
  582. if discardTunnel {
  583. controller.discardTunnel(connectedTunnel)
  584. // Clear the reference to this discarded tunnel and immediately run
  585. // a garbage collection to reclaim its memory.
  586. connectedTunnel = nil
  587. defaultGarbageCollection()
  588. // Skip the rest of this case
  589. break
  590. }
  591. NoticeActiveTunnel(
  592. connectedTunnel.serverEntry.IpAddress,
  593. connectedTunnel.protocol,
  594. connectedTunnel.serverEntry.SupportsSSHAPIRequests())
  595. if isFirstTunnel {
  596. // The split tunnel classifier is started once the first tunnel is
  597. // established. This first tunnel is passed in to be used to make
  598. // the routes data request.
  599. // A long-running controller may run while the host device is present
  600. // in different regions. In this case, we want the split tunnel logic
  601. // to switch to routes for new regions and not classify traffic based
  602. // on routes installed for older regions.
  603. // We assume that when regions change, the host network will also
  604. // change, and so all tunnels will fail and be re-established. Under
  605. // that assumption, the classifier will be re-Start()-ed here when
  606. // the region has changed.
  607. controller.splitTunnelClassifier.Start(connectedTunnel)
  608. // Signal a connected request on each 1st tunnel establishment. For
  609. // multi-tunnels, the session is connected as long as at least one
  610. // tunnel is established.
  611. controller.startOrSignalConnectedReporter()
  612. // If the handshake indicated that a new client version is available,
  613. // trigger an upgrade download.
  614. // Note: serverContext is nil when DisableApi is set
  615. if connectedTunnel.serverContext != nil &&
  616. connectedTunnel.serverContext.clientUpgradeVersion != "" {
  617. handshakeVersion := connectedTunnel.serverContext.clientUpgradeVersion
  618. select {
  619. case controller.signalDownloadUpgrade <- handshakeVersion:
  620. default:
  621. }
  622. }
  623. }
  624. // Set the new tunnel as the transport for the packet tunnel. The packet tunnel
  625. // client remains up when reestablishing, but no packets are relayed while there
  626. // is no connected tunnel. UseTunnel will establish a new packet tunnel SSH
  627. // channel over the new SSH tunnel and configure the packet tunnel client to use
  628. // the new SSH channel as its transport.
  629. //
  630. // Note: as is, this logic is suboptimal for TunnelPoolSize > 1, as this would
  631. // continuously initialize new packet tunnel sessions for each established
  632. // server. For now, config validation requires TunnelPoolSize == 1 when
  633. // the packet tunnel is used.
  634. if controller.packetTunnelTransport != nil {
  635. controller.packetTunnelTransport.UseTunnel(connectedTunnel)
  636. }
  637. // TODO: design issue -- might not be enough server entries with region/caps to ever fill tunnel slots;
  638. // possible solution is establish target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  639. if controller.isFullyEstablished() {
  640. controller.stopEstablishing()
  641. }
  642. case <-controller.runCtx.Done():
  643. break loop
  644. }
  645. }
  646. // Stop running
  647. controller.stopEstablishing()
  648. controller.terminateAllTunnels()
  649. // Drain tunnel channels
  650. close(controller.connectedTunnels)
  651. for tunnel := range controller.connectedTunnels {
  652. controller.discardTunnel(tunnel)
  653. }
  654. close(controller.failedTunnels)
  655. for tunnel := range controller.failedTunnels {
  656. controller.discardTunnel(tunnel)
  657. }
  658. NoticeInfo("exiting run tunnels")
  659. }
  660. // classifyImpairedProtocol tracks "impaired" protocol classifications for failed
  661. // tunnels. A protocol is classified as impaired if a tunnel using that protocol
  662. // fails, repeatedly, shortly after the start of the connection. During tunnel
  663. // establishment, impaired protocols are briefly skipped.
  664. //
  665. // One purpose of this measure is to defend against an attack where the adversary,
  666. // for example, tags an OSSH TCP connection as an "unidentified" protocol; allows
  667. // it to connect; but then kills the underlying TCP connection after a short time.
  668. // Since OSSH has less latency than other protocols that may bypass an "unidentified"
  669. // filter, these other protocols might never be selected for use.
  670. //
  671. // Concurrency note: only the runTunnels() goroutine may call classifyImpairedProtocol
  672. func (controller *Controller) classifyImpairedProtocol(failedTunnel *Tunnel) {
  673. // If the tunnel failed while activating, its establishedTime will be 0.
  674. duration := controller.config.clientParameters.Get().Duration(
  675. parameters.ImpairedProtocolClassificationDuration)
  676. if failedTunnel.establishedTime == 0 ||
  677. failedTunnel.establishedTime.Add(duration).After(monotime.Now()) {
  678. controller.impairedProtocolClassification[failedTunnel.protocol] += 1
  679. } else {
  680. controller.impairedProtocolClassification[failedTunnel.protocol] = 0
  681. }
  682. // Reset classification once all known protocols are classified as impaired, as
  683. // there is now no way to proceed with only unimpaired protocols. The network
  684. // situation (or attack) resulting in classification may not be protocol-specific.
  685. if CountNonImpairedProtocols(
  686. controller.config.EgressRegion,
  687. controller.config.clientParameters.Get().TunnelProtocols(
  688. parameters.LimitTunnelProtocols),
  689. controller.getImpairedProtocols()) == 0 {
  690. controller.impairedProtocolClassification = make(map[string]int)
  691. }
  692. }
  693. // getImpairedProtocols returns a list of protocols that have sufficient
  694. // classifications to be considered impaired protocols.
  695. //
  696. // Concurrency note: only the runTunnels() goroutine may call getImpairedProtocols
  697. func (controller *Controller) getImpairedProtocols() []string {
  698. NoticeImpairedProtocolClassification(controller.impairedProtocolClassification)
  699. threshold := controller.config.clientParameters.Get().Int(
  700. parameters.ImpairedProtocolClassificationThreshold)
  701. impairedProtocols := make([]string, 0)
  702. for protocol, count := range controller.impairedProtocolClassification {
  703. if count >= threshold {
  704. impairedProtocols = append(impairedProtocols, protocol)
  705. }
  706. }
  707. return impairedProtocols
  708. }
  709. // isImpairedProtocol checks if the specified protocol is classified as impaired.
  710. //
  711. // Concurrency note: only the runTunnels() goroutine may call isImpairedProtocol
  712. func (controller *Controller) isImpairedProtocol(protocol string) bool {
  713. threshold := controller.config.clientParameters.Get().Int(
  714. parameters.ImpairedProtocolClassificationThreshold)
  715. count, ok := controller.impairedProtocolClassification[protocol]
  716. return ok && count >= threshold
  717. }
  718. // SignalSeededNewSLOK implements the TunnelOwner interface. This function
  719. // is called by Tunnel.operateTunnel when the tunnel has received a new,
  720. // previously unknown SLOK from the server. The Controller triggers an OSL
  721. // fetch, as the new SLOK may be sufficient to access new OSLs.
  722. func (controller *Controller) SignalSeededNewSLOK() {
  723. select {
  724. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  725. default:
  726. }
  727. }
  728. // SignalTunnelFailure implements the TunnelOwner interface. This function
  729. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  730. // has failed. The Controller will signal runTunnels to create a new
  731. // tunnel and/or remove the tunnel from the list of active tunnels.
  732. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  733. // Don't block. Assumes the receiver has a buffer large enough for
  734. // the typical number of operated tunnels. In case there's no room,
  735. // terminate the tunnel (runTunnels won't get a signal in this case,
  736. // but the tunnel will be removed from the list of active tunnels).
  737. select {
  738. case controller.failedTunnels <- tunnel:
  739. default:
  740. controller.terminateTunnel(tunnel)
  741. }
  742. }
  743. // discardTunnel disposes of a successful connection that is no longer required.
  744. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  745. NoticeInfo("discard tunnel: %s", tunnel.serverEntry.IpAddress)
  746. // TODO: not calling PromoteServerEntry, since that would rank the
  747. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  748. // be promoted (since it connects), but with lower rank than all active
  749. // tunnels?
  750. tunnel.Close(true)
  751. }
  752. // registerTunnel adds the connected tunnel to the pool of active tunnels
  753. // which are candidates for port forwarding. Returns true if the pool has an
  754. // empty slot and false if the pool is full (caller should discard the tunnel).
  755. func (controller *Controller) registerTunnel(tunnel *Tunnel) bool {
  756. controller.tunnelMutex.Lock()
  757. defer controller.tunnelMutex.Unlock()
  758. if len(controller.tunnels) >= controller.config.TunnelPoolSize {
  759. return false
  760. }
  761. // Perform a final check just in case we've established
  762. // a duplicate connection.
  763. for _, activeTunnel := range controller.tunnels {
  764. if activeTunnel.serverEntry.IpAddress == tunnel.serverEntry.IpAddress {
  765. NoticeAlert("duplicate tunnel: %s", tunnel.serverEntry.IpAddress)
  766. return false
  767. }
  768. }
  769. controller.establishedOnce = true
  770. controller.tunnels = append(controller.tunnels, tunnel)
  771. NoticeTunnels(len(controller.tunnels))
  772. // Promote this successful tunnel to first rank so it's one
  773. // of the first candidates next time establish runs.
  774. // Connecting to a TargetServerEntry does not change the
  775. // ranking.
  776. if controller.config.TargetServerEntry == "" {
  777. PromoteServerEntry(controller.config, tunnel.serverEntry.IpAddress)
  778. }
  779. return true
  780. }
  781. // hasEstablishedOnce indicates if at least one active tunnel has
  782. // been established up to this point. This is regardeless of how many
  783. // tunnels are presently active.
  784. func (controller *Controller) hasEstablishedOnce() bool {
  785. controller.tunnelMutex.Lock()
  786. defer controller.tunnelMutex.Unlock()
  787. return controller.establishedOnce
  788. }
  789. // isFullyEstablished indicates if the pool of active tunnels is full.
  790. func (controller *Controller) isFullyEstablished() bool {
  791. controller.tunnelMutex.Lock()
  792. defer controller.tunnelMutex.Unlock()
  793. return len(controller.tunnels) >= controller.config.TunnelPoolSize
  794. }
  795. // numTunnels returns the number of active and outstanding tunnels.
  796. // Oustanding is the number of tunnels required to fill the pool of
  797. // active tunnels.
  798. func (controller *Controller) numTunnels() (int, int) {
  799. controller.tunnelMutex.Lock()
  800. defer controller.tunnelMutex.Unlock()
  801. active := len(controller.tunnels)
  802. outstanding := controller.config.TunnelPoolSize - len(controller.tunnels)
  803. return active, outstanding
  804. }
  805. // terminateTunnel removes a tunnel from the pool of active tunnels
  806. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  807. // is adjusted as required.
  808. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  809. controller.tunnelMutex.Lock()
  810. defer controller.tunnelMutex.Unlock()
  811. for index, activeTunnel := range controller.tunnels {
  812. if tunnel == activeTunnel {
  813. controller.tunnels = append(
  814. controller.tunnels[:index], controller.tunnels[index+1:]...)
  815. if controller.nextTunnel > index {
  816. controller.nextTunnel--
  817. }
  818. if controller.nextTunnel >= len(controller.tunnels) {
  819. controller.nextTunnel = 0
  820. }
  821. activeTunnel.Close(false)
  822. NoticeTunnels(len(controller.tunnels))
  823. break
  824. }
  825. }
  826. }
  827. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  828. // This is used when shutting down the controller.
  829. func (controller *Controller) terminateAllTunnels() {
  830. controller.tunnelMutex.Lock()
  831. defer controller.tunnelMutex.Unlock()
  832. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  833. // may take a few seconds to send a final status request. We only want
  834. // to wait as long as the single slowest tunnel.
  835. closeWaitGroup := new(sync.WaitGroup)
  836. closeWaitGroup.Add(len(controller.tunnels))
  837. for _, activeTunnel := range controller.tunnels {
  838. tunnel := activeTunnel
  839. go func() {
  840. defer closeWaitGroup.Done()
  841. tunnel.Close(false)
  842. }()
  843. }
  844. closeWaitGroup.Wait()
  845. controller.tunnels = make([]*Tunnel, 0)
  846. controller.nextTunnel = 0
  847. NoticeTunnels(len(controller.tunnels))
  848. }
  849. // getNextActiveTunnel returns the next tunnel from the pool of active
  850. // tunnels. Currently, tunnel selection order is simple round-robin.
  851. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  852. controller.tunnelMutex.Lock()
  853. defer controller.tunnelMutex.Unlock()
  854. for i := len(controller.tunnels); i > 0; i-- {
  855. tunnel = controller.tunnels[controller.nextTunnel]
  856. controller.nextTunnel =
  857. (controller.nextTunnel + 1) % len(controller.tunnels)
  858. return tunnel
  859. }
  860. return nil
  861. }
  862. // isActiveTunnelServerEntry is used to check if there's already
  863. // an existing tunnel to a candidate server.
  864. func (controller *Controller) isActiveTunnelServerEntry(
  865. serverEntry *protocol.ServerEntry) bool {
  866. controller.tunnelMutex.Lock()
  867. defer controller.tunnelMutex.Unlock()
  868. for _, activeTunnel := range controller.tunnels {
  869. if activeTunnel.serverEntry.IpAddress == serverEntry.IpAddress {
  870. return true
  871. }
  872. }
  873. return false
  874. }
  875. // Dial selects an active tunnel and establishes a port forward
  876. // connection through the selected tunnel. Failure to connect is considered
  877. // a port forward failure, for the purpose of monitoring tunnel health.
  878. func (controller *Controller) Dial(
  879. remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error) {
  880. tunnel := controller.getNextActiveTunnel()
  881. if tunnel == nil {
  882. return nil, common.ContextError(errors.New("no active tunnels"))
  883. }
  884. // Perform split tunnel classification when feature is enabled, and if the remote
  885. // address is classified as untunneled, dial directly.
  886. if !alwaysTunnel && controller.config.SplitTunnelDNSServer != "" {
  887. host, _, err := net.SplitHostPort(remoteAddr)
  888. if err != nil {
  889. return nil, common.ContextError(err)
  890. }
  891. // Note: a possible optimization, when split tunnel is active and IsUntunneled performs
  892. // a DNS resolution in order to make its classification, is to reuse that IP address in
  893. // the following Dials so they do not need to make their own resolutions. However, the
  894. // way this is currently implemented ensures that, e.g., DNS geo load balancing occurs
  895. // relative to the outbound network.
  896. if controller.splitTunnelClassifier.IsUntunneled(host) {
  897. return controller.DirectDial(remoteAddr)
  898. }
  899. }
  900. tunneledConn, err := tunnel.Dial(remoteAddr, alwaysTunnel, downstreamConn)
  901. if err != nil {
  902. return nil, common.ContextError(err)
  903. }
  904. return tunneledConn, nil
  905. }
  906. // DirectDial dials an untunneled TCP connection within the controller run context.
  907. func (controller *Controller) DirectDial(remoteAddr string) (conn net.Conn, err error) {
  908. return DialTCP(controller.runCtx, remoteAddr, controller.untunneledDialConfig)
  909. }
  910. // startEstablishing creates a pool of worker goroutines which will
  911. // attempt to establish tunnels to candidate servers. The candidates
  912. // are generated by another goroutine.
  913. func (controller *Controller) startEstablishing() {
  914. if controller.isEstablishing {
  915. return
  916. }
  917. NoticeInfo("start establishing")
  918. controller.concurrentEstablishTunnelsMutex.Lock()
  919. controller.concurrentEstablishTunnels = 0
  920. controller.concurrentMeekEstablishTunnels = 0
  921. controller.peakConcurrentEstablishTunnels = 0
  922. controller.peakConcurrentMeekEstablishTunnels = 0
  923. controller.concurrentEstablishTunnelsMutex.Unlock()
  924. aggressiveGarbageCollection()
  925. emitMemoryMetrics()
  926. // Note: the establish context cancelFunc, controller.stopEstablish,
  927. // is called in controller.stopEstablishing.
  928. controller.isEstablishing = true
  929. controller.establishCtx, controller.stopEstablish = context.WithCancel(controller.runCtx)
  930. controller.establishWaitGroup = new(sync.WaitGroup)
  931. controller.candidateServerEntries = make(chan *candidateServerEntry)
  932. // The server affinity mechanism attempts to favor the previously
  933. // used server when reconnecting. This is beneficial for user
  934. // applications which expect consistency in user IP address (for
  935. // example, a web site which prompts for additional user
  936. // authentication when the IP address changes).
  937. //
  938. // Only the very first server, as determined by
  939. // datastore.PromoteServerEntry(), is the server affinity candidate.
  940. // Concurrent connections attempts to many servers are launched
  941. // without delay, in case the affinity server connection fails.
  942. // While the affinity server connection is outstanding, when any
  943. // other connection is established, there is a short grace period
  944. // delay before delivering the established tunnel; this allows some
  945. // time for the affinity server connection to succeed first.
  946. // When the affinity server connection fails, any other established
  947. // tunnel is registered without delay.
  948. //
  949. // Note: the establishTunnelWorker that receives the affinity
  950. // candidate is solely resonsible for closing
  951. // controller.serverAffinityDoneBroadcast.
  952. controller.serverAffinityDoneBroadcast = make(chan struct{})
  953. controller.establishWaitGroup.Add(1)
  954. go controller.launchEstablishing(controller.getImpairedProtocols())
  955. }
  956. func (controller *Controller) launchEstablishing(impairedProtocols []string) {
  957. defer controller.establishWaitGroup.Done()
  958. // Before starting the establish tunnel workers, get and apply
  959. // tactics, launching a tactics request if required.
  960. //
  961. // Wait only TacticsWaitPeriod for the tactics request to complete (or
  962. // fail) before proceeding with tunnel establishment, in case the tactics
  963. // request is blocked or takes very long to complete.
  964. //
  965. // An in-flight tactics request uses meek in round tripper mode, which
  966. // uses less resources than meek tunnel relay mode. For this reason, the
  967. // tactics request is not counted in concurrentMeekEstablishTunnels.
  968. //
  969. // TODO: HTTP/2 uses significantly more memory, so perhaps
  970. // concurrentMeekEstablishTunnels should be counted in that case.
  971. //
  972. // Any in-flight tactics request or pending retry will be
  973. // canceled when establishment is stopped.
  974. doTactics := !controller.config.DisableTactics &&
  975. controller.config.networkIDGetter != nil
  976. if doTactics {
  977. timeout := controller.config.clientParameters.Get().Duration(
  978. parameters.TacticsWaitPeriod)
  979. tacticsDone := make(chan struct{})
  980. tacticsWaitPeriod := time.NewTimer(timeout)
  981. defer tacticsWaitPeriod.Stop()
  982. controller.establishWaitGroup.Add(1)
  983. go controller.getTactics(tacticsDone)
  984. select {
  985. case <-tacticsDone:
  986. case <-tacticsWaitPeriod.C:
  987. }
  988. tacticsWaitPeriod.Stop()
  989. if controller.isStopEstablishing() {
  990. // This check isn't strictly required by avoids the
  991. // overhead of launching workers if establishment
  992. // stopped while awaiting a tactics request.
  993. return
  994. }
  995. }
  996. // Unconditionally report available egress regions. After a fresh install,
  997. // the outer client may not have a list of regions to display, so we
  998. // always report here. Other events that trigger ReportAvailableRegions,
  999. // are not guaranteed to occur.
  1000. //
  1001. // This report is delayed until after tactics are likely to be applied, as
  1002. // tactics can impact the list of available regions; this avoids a
  1003. // ReportAvailableRegions reporting too many regions, followed shortly by
  1004. // a ReportAvailableRegions reporting fewer regions. That sequence could
  1005. // cause issues in the outer client UI.
  1006. ReportAvailableRegions(controller.config)
  1007. // The ConnectionWorkerPoolSize may be set by tactics.
  1008. size := controller.config.clientParameters.Get().Int(
  1009. parameters.ConnectionWorkerPoolSize)
  1010. for i := 0; i < size; i++ {
  1011. controller.establishWaitGroup.Add(1)
  1012. go controller.establishTunnelWorker()
  1013. }
  1014. controller.establishWaitGroup.Add(1)
  1015. go controller.establishCandidateGenerator(impairedProtocols)
  1016. }
  1017. // stopEstablishing signals the establish goroutines to stop and waits
  1018. // for the group to halt.
  1019. func (controller *Controller) stopEstablishing() {
  1020. if !controller.isEstablishing {
  1021. return
  1022. }
  1023. NoticeInfo("stop establishing")
  1024. controller.stopEstablish()
  1025. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  1026. // (as it may be sending to that channel).
  1027. controller.establishWaitGroup.Wait()
  1028. NoticeInfo("stopped establishing")
  1029. controller.isEstablishing = false
  1030. controller.establishCtx = nil
  1031. controller.stopEstablish = nil
  1032. controller.establishWaitGroup = nil
  1033. controller.candidateServerEntries = nil
  1034. controller.serverAffinityDoneBroadcast = nil
  1035. controller.concurrentEstablishTunnelsMutex.Lock()
  1036. peakConcurrent := controller.peakConcurrentEstablishTunnels
  1037. peakConcurrentMeek := controller.peakConcurrentMeekEstablishTunnels
  1038. controller.concurrentEstablishTunnels = 0
  1039. controller.concurrentMeekEstablishTunnels = 0
  1040. controller.peakConcurrentEstablishTunnels = 0
  1041. controller.peakConcurrentMeekEstablishTunnels = 0
  1042. controller.concurrentEstablishTunnelsMutex.Unlock()
  1043. NoticeInfo("peak concurrent establish tunnels: %d", peakConcurrent)
  1044. NoticeInfo("peak concurrent meek establish tunnels: %d", peakConcurrentMeek)
  1045. emitMemoryMetrics()
  1046. standardGarbageCollection()
  1047. }
  1048. func (controller *Controller) getTactics(done chan struct{}) {
  1049. defer controller.establishWaitGroup.Done()
  1050. defer close(done)
  1051. tacticsRecord, err := tactics.UseStoredTactics(
  1052. GetTacticsStorer(),
  1053. controller.config.networkIDGetter.GetNetworkID())
  1054. if err != nil {
  1055. NoticeAlert("get stored tactics failed: %s", err)
  1056. // The error will be due to a local datastore problem.
  1057. // While we could proceed with the tactics request, this
  1058. // could result in constant tactics requests. So, abort.
  1059. return
  1060. }
  1061. if tacticsRecord == nil {
  1062. iterator, err := NewTacticsServerEntryIterator(
  1063. controller.config)
  1064. if err != nil {
  1065. NoticeAlert("tactics iterator failed: %s", err)
  1066. return
  1067. }
  1068. defer iterator.Close()
  1069. for iteration := 0; ; iteration++ {
  1070. if !WaitForNetworkConnectivity(
  1071. controller.runCtx,
  1072. controller.config.NetworkConnectivityChecker) {
  1073. return
  1074. }
  1075. serverEntry, err := iterator.Next()
  1076. if err != nil {
  1077. NoticeAlert("tactics iterator failed: %s", err)
  1078. return
  1079. }
  1080. if serverEntry == nil {
  1081. if iteration == 0 {
  1082. NoticeAlert("tactics request skipped: no capable servers")
  1083. return
  1084. }
  1085. iterator.Reset()
  1086. continue
  1087. }
  1088. tacticsRecord, err = controller.doFetchTactics(serverEntry)
  1089. if err == nil {
  1090. break
  1091. }
  1092. NoticeAlert("tactics request failed: %s", err)
  1093. // On error, proceed with a retry, as the error is likely
  1094. // due to a network failure.
  1095. //
  1096. // TODO: distinguish network and local errors and abort
  1097. // on local errors.
  1098. p := controller.config.clientParameters.Get()
  1099. timeout := common.JitterDuration(
  1100. p.Duration(parameters.TacticsRetryPeriod),
  1101. p.Float(parameters.TacticsRetryPeriodJitter))
  1102. p = nil
  1103. tacticsRetryDelay := time.NewTimer(timeout)
  1104. select {
  1105. case <-controller.establishCtx.Done():
  1106. return
  1107. case <-tacticsRetryDelay.C:
  1108. }
  1109. tacticsRetryDelay.Stop()
  1110. }
  1111. }
  1112. if tacticsRecord != nil &&
  1113. common.FlipWeightedCoin(tacticsRecord.Tactics.Probability) {
  1114. err := controller.config.SetClientParameters(
  1115. tacticsRecord.Tag, true, tacticsRecord.Tactics.Parameters)
  1116. if err != nil {
  1117. NoticeAlert("apply tactics failed: %s", err)
  1118. // The error will be due to invalid tactics values from
  1119. // the server. When ApplyClientParameters fails, all
  1120. // previous tactics values are left in place. Abort
  1121. // without retry since the server is highly unlikely
  1122. // to return different values immediately.
  1123. return
  1124. }
  1125. }
  1126. // Reclaim memory from the completed tactics request as we're likely
  1127. // to be proceeding to the memory-intensive tunnel establishment phase.
  1128. aggressiveGarbageCollection()
  1129. emitMemoryMetrics()
  1130. }
  1131. func (controller *Controller) doFetchTactics(
  1132. serverEntry *protocol.ServerEntry) (*tactics.Record, error) {
  1133. tacticsProtocols := serverEntry.GetSupportedTacticsProtocols()
  1134. index, err := common.MakeSecureRandomInt(len(tacticsProtocols))
  1135. if err != nil {
  1136. return nil, common.ContextError(err)
  1137. }
  1138. tacticsProtocol := tacticsProtocols[index]
  1139. meekConfig, err := initMeekConfig(
  1140. controller.config,
  1141. serverEntry,
  1142. tacticsProtocol,
  1143. "")
  1144. if err != nil {
  1145. return nil, common.ContextError(err)
  1146. }
  1147. meekConfig.RoundTripperOnly = true
  1148. dialConfig, dialStats := initDialConfig(controller.config, meekConfig)
  1149. NoticeRequestingTactics(
  1150. serverEntry.IpAddress,
  1151. serverEntry.Region,
  1152. tacticsProtocol,
  1153. dialStats)
  1154. // TacticsTimeout should be a very long timeout, since it's not
  1155. // adjusted by tactics in a new network context, and so clients
  1156. // with very slow connections must be accomodated. This long
  1157. // timeout will not entirely block the beginning of tunnel
  1158. // establishment, which beings after the shorter TacticsWaitPeriod.
  1159. //
  1160. // Using controller.establishCtx will cancel FetchTactics
  1161. // if tunnel establishment completes first.
  1162. timeout := controller.config.clientParameters.Get().Duration(
  1163. parameters.TacticsTimeout)
  1164. ctx, cancelFunc := context.WithTimeout(
  1165. controller.establishCtx,
  1166. timeout)
  1167. defer cancelFunc()
  1168. // DialMeek completes the TCP/TLS handshakes for HTTPS
  1169. // meek protocols but _not_ for HTTP meek protocols.
  1170. //
  1171. // TODO: pre-dial HTTP protocols to conform with speed
  1172. // test RTT spec.
  1173. //
  1174. // TODO: ensure that meek in round trip mode will fail
  1175. // the request when the pre-dial connection is broken,
  1176. // to minimize the possibility of network ID mismatches.
  1177. meekConn, err := DialMeek(ctx, meekConfig, dialConfig)
  1178. if err != nil {
  1179. return nil, common.ContextError(err)
  1180. }
  1181. defer meekConn.Close()
  1182. apiParams := getBaseAPIParameters(
  1183. controller.config,
  1184. controller.sessionId,
  1185. serverEntry,
  1186. tacticsProtocol,
  1187. dialStats)
  1188. tacticsRecord, err := tactics.FetchTactics(
  1189. ctx,
  1190. controller.config.clientParameters,
  1191. GetTacticsStorer(),
  1192. controller.config.networkIDGetter.GetNetworkID,
  1193. apiParams,
  1194. serverEntry.Region,
  1195. tacticsProtocol,
  1196. serverEntry.TacticsRequestPublicKey,
  1197. serverEntry.TacticsRequestObfuscatedKey,
  1198. meekConn.RoundTrip)
  1199. if err != nil {
  1200. return nil, common.ContextError(err)
  1201. }
  1202. NoticeRequestedTactics(
  1203. serverEntry.IpAddress,
  1204. serverEntry.Region,
  1205. tacticsProtocol,
  1206. dialStats)
  1207. return tacticsRecord, nil
  1208. }
  1209. // establishCandidateGenerator populates the candidate queue with server entries
  1210. // from the data store. Server entries are iterated in rank order, so that promoted
  1211. // servers with higher rank are priority candidates.
  1212. func (controller *Controller) establishCandidateGenerator(impairedProtocols []string) {
  1213. defer controller.establishWaitGroup.Done()
  1214. defer close(controller.candidateServerEntries)
  1215. // establishStartTime is used to calculate and report the
  1216. // client's tunnel establishment duration.
  1217. //
  1218. // networkWaitDuration is the elapsed time spent waiting
  1219. // for network connectivity. This duration will be excluded
  1220. // from reported tunnel establishment duration.
  1221. establishStartTime := monotime.Now()
  1222. var networkWaitDuration time.Duration
  1223. applyServerAffinity, iterator, err := NewServerEntryIterator(controller.config)
  1224. if err != nil {
  1225. NoticeAlert("failed to iterate over candidates: %s", err)
  1226. controller.SignalComponentFailure()
  1227. return
  1228. }
  1229. defer iterator.Close()
  1230. // TODO: reconcile server affinity scheme with multi-tunnel mode
  1231. if controller.config.TunnelPoolSize > 1 {
  1232. applyServerAffinity = false
  1233. }
  1234. isServerAffinityCandidate := true
  1235. if !applyServerAffinity {
  1236. isServerAffinityCandidate = false
  1237. close(controller.serverAffinityDoneBroadcast)
  1238. }
  1239. candidateCount := 0
  1240. loop:
  1241. // Repeat until stopped
  1242. for i := 0; ; i++ {
  1243. networkWaitStartTime := monotime.Now()
  1244. if !WaitForNetworkConnectivity(
  1245. controller.establishCtx,
  1246. controller.config.NetworkConnectivityChecker) {
  1247. break loop
  1248. }
  1249. networkWaitDuration += monotime.Since(networkWaitStartTime)
  1250. // Send each iterator server entry to the establish workers
  1251. startTime := monotime.Now()
  1252. for {
  1253. serverEntry, err := iterator.Next()
  1254. if err != nil {
  1255. NoticeAlert("failed to get next candidate: %s", err)
  1256. controller.SignalComponentFailure()
  1257. break loop
  1258. }
  1259. if serverEntry == nil {
  1260. // Completed this iteration
  1261. break
  1262. }
  1263. if controller.config.TargetApiProtocol == protocol.PSIPHON_SSH_API_PROTOCOL &&
  1264. !serverEntry.SupportsSSHAPIRequests() {
  1265. continue
  1266. }
  1267. // Use a prioritized tunnel protocol for the first
  1268. // PrioritizeTunnelProtocolsCandidateCount candidates.
  1269. // This facility can be used to favor otherwise slower
  1270. // protocols.
  1271. prioritizeCandidateCount := controller.config.clientParameters.Get().Int(
  1272. parameters.PrioritizeTunnelProtocolsCandidateCount)
  1273. usePriorityProtocol := candidateCount < prioritizeCandidateCount
  1274. // Disable impaired protocols. This is only done for the
  1275. // first iteration of the EstablishTunnelWorkTime
  1276. // loop since (a) one iteration should be sufficient to
  1277. // evade the attack; (b) there's a good chance of false
  1278. // positives (such as short tunnel durations due to network
  1279. // hopping on a mobile device).
  1280. var candidateImpairedProtocols []string
  1281. if i == 0 {
  1282. candidateImpairedProtocols = impairedProtocols
  1283. }
  1284. // adjustedEstablishStartTime is establishStartTime shifted
  1285. // to exclude time spent waiting for network connectivity.
  1286. adjustedEstablishStartTime := establishStartTime.Add(networkWaitDuration)
  1287. candidate := &candidateServerEntry{
  1288. serverEntry: serverEntry,
  1289. isServerAffinityCandidate: isServerAffinityCandidate,
  1290. usePriorityProtocol: usePriorityProtocol,
  1291. impairedProtocols: candidateImpairedProtocols,
  1292. adjustedEstablishStartTime: adjustedEstablishStartTime,
  1293. }
  1294. wasServerAffinityCandidate := isServerAffinityCandidate
  1295. // Note: there must be only one server affinity candidate, as it
  1296. // closes the serverAffinityDoneBroadcast channel.
  1297. isServerAffinityCandidate = false
  1298. // TODO: here we could generate multiple candidates from the
  1299. // server entry when there are many MeekFrontingAddresses.
  1300. candidateCount++
  1301. select {
  1302. case controller.candidateServerEntries <- candidate:
  1303. case <-controller.establishCtx.Done():
  1304. break loop
  1305. }
  1306. workTime := controller.config.clientParameters.Get().Duration(
  1307. parameters.EstablishTunnelWorkTime)
  1308. if startTime.Add(workTime).Before(monotime.Now()) {
  1309. // Start over, after a brief pause, with a new shuffle of the server
  1310. // entries, and potentially some newly fetched server entries.
  1311. break
  1312. }
  1313. if wasServerAffinityCandidate {
  1314. // Don't start the next candidate until either the server affinity
  1315. // candidate has completed (success or failure) or is still working
  1316. // and the grace period has elapsed.
  1317. gracePeriod := controller.config.clientParameters.Get().Duration(
  1318. parameters.EstablishTunnelServerAffinityGracePeriod)
  1319. if gracePeriod > 0 {
  1320. timer := time.NewTimer(gracePeriod)
  1321. select {
  1322. case <-timer.C:
  1323. case <-controller.serverAffinityDoneBroadcast:
  1324. case <-controller.establishCtx.Done():
  1325. timer.Stop()
  1326. break loop
  1327. }
  1328. timer.Stop()
  1329. }
  1330. } else {
  1331. p := controller.config.clientParameters.Get()
  1332. staggerPeriod := p.Duration(parameters.StaggerConnectionWorkersPeriod)
  1333. staggerJitter := p.Float(parameters.StaggerConnectionWorkersJitter)
  1334. p = nil
  1335. if staggerPeriod != 0 {
  1336. // Stagger concurrent connection workers.
  1337. timeout := common.JitterDuration(staggerPeriod, staggerJitter)
  1338. timer := time.NewTimer(timeout)
  1339. select {
  1340. case <-timer.C:
  1341. case <-controller.establishCtx.Done():
  1342. timer.Stop()
  1343. break loop
  1344. }
  1345. timer.Stop()
  1346. }
  1347. }
  1348. }
  1349. // Free up resources now, but don't reset until after the pause.
  1350. iterator.Close()
  1351. // Trigger a common remote server list fetch, since we may have failed
  1352. // to connect with all known servers. Don't block sending signal, since
  1353. // this signal may have already been sent.
  1354. // Don't wait for fetch remote to succeed, since it may fail and
  1355. // enter a retry loop and we're better off trying more known servers.
  1356. // TODO: synchronize the fetch response, so it can be incorporated
  1357. // into the server entry iterator as soon as available.
  1358. select {
  1359. case controller.signalFetchCommonRemoteServerList <- *new(struct{}):
  1360. default:
  1361. }
  1362. // Trigger an OSL fetch in parallel. Both fetches are run in parallel
  1363. // so that if one out of the common RLS and OSL set is large, it doesn't
  1364. // doesn't entirely block fetching the other.
  1365. select {
  1366. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  1367. default:
  1368. }
  1369. // Trigger an out-of-band upgrade availability check and download.
  1370. // Since we may have failed to connect, we may benefit from upgrading
  1371. // to a new client version with new circumvention capabilities.
  1372. select {
  1373. case controller.signalDownloadUpgrade <- "":
  1374. default:
  1375. }
  1376. // After a complete iteration of candidate servers, pause before iterating again.
  1377. // This helps avoid some busy wait loop conditions, and also allows some time for
  1378. // network conditions to change. Also allows for fetch remote to complete,
  1379. // in typical conditions (it isn't strictly necessary to wait for this, there will
  1380. // be more rounds if required).
  1381. p := controller.config.clientParameters.Get()
  1382. timeout := common.JitterDuration(
  1383. p.Duration(parameters.EstablishTunnelPausePeriod),
  1384. p.Float(parameters.EstablishTunnelPausePeriodJitter))
  1385. p = nil
  1386. timer := time.NewTimer(timeout)
  1387. select {
  1388. case <-timer.C:
  1389. // Retry iterating
  1390. case <-controller.establishCtx.Done():
  1391. timer.Stop()
  1392. break loop
  1393. }
  1394. timer.Stop()
  1395. iterator.Reset()
  1396. }
  1397. }
  1398. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  1399. // a connection to the tunnel server, and delivers the connected tunnel to a channel.
  1400. func (controller *Controller) establishTunnelWorker() {
  1401. defer controller.establishWaitGroup.Done()
  1402. loop:
  1403. for candidateServerEntry := range controller.candidateServerEntries {
  1404. // Note: don't receive from candidateServerEntries and isStopEstablishing
  1405. // in the same select, since we want to prioritize receiving the stop signal
  1406. if controller.isStopEstablishing() {
  1407. break loop
  1408. }
  1409. // There may already be a tunnel to this candidate. If so, skip it.
  1410. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  1411. continue
  1412. }
  1413. // ConnectTunnel will allocate significant memory, so first attempt to
  1414. // reclaim as much as possible.
  1415. defaultGarbageCollection()
  1416. // Select the tunnel protocol. The selection will be made at random from
  1417. // protocols supported by the server entry, optionally limited by
  1418. // LimitTunnelProtocols.
  1419. //
  1420. // When limiting concurrent meek connection workers, and at the limit,
  1421. // do not select meek since otherwise the candidate must be skipped.
  1422. //
  1423. // If at the limit and unabled to select a non-meek protocol, skip the
  1424. // candidate entirely and move on to the next. Since candidates are shuffled
  1425. // it's probable that the next candidate is not meek. In this case, a
  1426. // StaggerConnectionWorkersMilliseconds delay may still be incurred.
  1427. limitMeekConnectionWorkers := controller.config.clientParameters.Get().Int(
  1428. parameters.LimitMeekConnectionWorkers)
  1429. excludeMeek := false
  1430. controller.concurrentEstablishTunnelsMutex.Lock()
  1431. if limitMeekConnectionWorkers > 0 &&
  1432. controller.concurrentMeekEstablishTunnels >=
  1433. limitMeekConnectionWorkers {
  1434. excludeMeek = true
  1435. }
  1436. controller.concurrentEstablishTunnelsMutex.Unlock()
  1437. selectedProtocol, err := selectProtocol(
  1438. controller.config,
  1439. candidateServerEntry.serverEntry,
  1440. candidateServerEntry.impairedProtocols,
  1441. excludeMeek,
  1442. candidateServerEntry.usePriorityProtocol)
  1443. if err == errNoProtocolSupported {
  1444. // selectProtocol returns errNoProtocolSupported when the server
  1445. // does not support any protocol that remains after applying the
  1446. // LimitTunnelProtocols parameter, the impaired protocol filter,
  1447. // and the excludeMeek flag.
  1448. // Skip this candidate.
  1449. // Unblock other candidates immediately when
  1450. // server affinity candidate is skipped.
  1451. if candidateServerEntry.isServerAffinityCandidate {
  1452. close(controller.serverAffinityDoneBroadcast)
  1453. }
  1454. continue
  1455. }
  1456. var tunnel *Tunnel
  1457. if err == nil {
  1458. isMeek := protocol.TunnelProtocolUsesMeek(selectedProtocol)
  1459. controller.concurrentEstablishTunnelsMutex.Lock()
  1460. if isMeek {
  1461. // Recheck the limit now that we know we're selecting meek and
  1462. // adjusting concurrentMeekEstablishTunnels.
  1463. if limitMeekConnectionWorkers > 0 &&
  1464. controller.concurrentMeekEstablishTunnels >=
  1465. limitMeekConnectionWorkers {
  1466. // Skip this candidate.
  1467. controller.concurrentEstablishTunnelsMutex.Unlock()
  1468. continue
  1469. }
  1470. controller.concurrentMeekEstablishTunnels += 1
  1471. if controller.concurrentMeekEstablishTunnels > controller.peakConcurrentMeekEstablishTunnels {
  1472. controller.peakConcurrentMeekEstablishTunnels = controller.concurrentMeekEstablishTunnels
  1473. }
  1474. }
  1475. controller.concurrentEstablishTunnels += 1
  1476. if controller.concurrentEstablishTunnels > controller.peakConcurrentEstablishTunnels {
  1477. controller.peakConcurrentEstablishTunnels = controller.concurrentEstablishTunnels
  1478. }
  1479. controller.concurrentEstablishTunnelsMutex.Unlock()
  1480. tunnel, err = ConnectTunnel(
  1481. controller.establishCtx,
  1482. controller.config,
  1483. controller.sessionId,
  1484. candidateServerEntry.serverEntry,
  1485. selectedProtocol,
  1486. candidateServerEntry.adjustedEstablishStartTime)
  1487. controller.concurrentEstablishTunnelsMutex.Lock()
  1488. if isMeek {
  1489. controller.concurrentMeekEstablishTunnels -= 1
  1490. }
  1491. controller.concurrentEstablishTunnels -= 1
  1492. controller.concurrentEstablishTunnelsMutex.Unlock()
  1493. }
  1494. // Periodically emit memory metrics during the establishment cycle.
  1495. if !controller.isStopEstablishing() {
  1496. emitMemoryMetrics()
  1497. }
  1498. // Immediately reclaim memory allocated by the establishment. In the case
  1499. // of failure, first clear the reference to the tunnel. In the case of
  1500. // success, the garbage collection may still be effective as the initial
  1501. // phases of some protocols involve significant memory allocation that
  1502. // could now be reclaimed.
  1503. if err != nil {
  1504. tunnel = nil
  1505. }
  1506. defaultGarbageCollection()
  1507. if err != nil {
  1508. // Unblock other candidates immediately when
  1509. // server affinity candidate fails.
  1510. if candidateServerEntry.isServerAffinityCandidate {
  1511. close(controller.serverAffinityDoneBroadcast)
  1512. }
  1513. // Before emitting error, check if establish interrupted, in which
  1514. // case the error is noise.
  1515. if controller.isStopEstablishing() {
  1516. break loop
  1517. }
  1518. NoticeInfo("failed to connect to %s: %s", candidateServerEntry.serverEntry.IpAddress, err)
  1519. continue
  1520. }
  1521. // Deliver connected tunnel.
  1522. // Don't block. Assumes the receiver has a buffer large enough for
  1523. // the number of desired tunnels. If there's no room, the tunnel must
  1524. // not be required so it's discarded.
  1525. select {
  1526. case controller.connectedTunnels <- tunnel:
  1527. default:
  1528. controller.discardTunnel(tunnel)
  1529. // Clear the reference to this discarded tunnel and immediately run
  1530. // a garbage collection to reclaim its memory.
  1531. tunnel = nil
  1532. defaultGarbageCollection()
  1533. }
  1534. // Unblock other candidates only after delivering when
  1535. // server affinity candidate succeeds.
  1536. if candidateServerEntry.isServerAffinityCandidate {
  1537. close(controller.serverAffinityDoneBroadcast)
  1538. }
  1539. }
  1540. }
  1541. func (controller *Controller) isStopEstablishing() bool {
  1542. select {
  1543. case <-controller.establishCtx.Done():
  1544. return true
  1545. default:
  1546. }
  1547. return false
  1548. }