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