controller.go 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  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. "errors"
  26. "math/rand"
  27. "net"
  28. "sync"
  29. "time"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  31. )
  32. // Controller is a tunnel lifecycle coordinator. It manages lists of servers to
  33. // connect to; establishes and monitors tunnels; and runs local proxies which
  34. // route traffic through the tunnels.
  35. type Controller struct {
  36. config *Config
  37. sessionId string
  38. componentFailureSignal chan struct{}
  39. shutdownBroadcast chan struct{}
  40. runWaitGroup *sync.WaitGroup
  41. establishedTunnels chan *Tunnel
  42. failedTunnels chan *Tunnel
  43. tunnelMutex sync.Mutex
  44. establishedOnce bool
  45. tunnels []*Tunnel
  46. nextTunnel int
  47. startedConnectedReporter bool
  48. isEstablishing bool
  49. establishWaitGroup *sync.WaitGroup
  50. stopEstablishingBroadcast chan struct{}
  51. candidateServerEntries chan *candidateServerEntry
  52. establishPendingConns *common.Conns
  53. untunneledPendingConns *common.Conns
  54. untunneledDialConfig *DialConfig
  55. splitTunnelClassifier *SplitTunnelClassifier
  56. signalFetchRemoteServerList chan struct{}
  57. signalDownloadUpgrade chan string
  58. impairedProtocolClassification map[string]int
  59. signalReportConnected chan struct{}
  60. serverAffinityDoneBroadcast chan struct{}
  61. newClientVerificationPayload chan string
  62. }
  63. type candidateServerEntry struct {
  64. serverEntry *ServerEntry
  65. isServerAffinityCandidate bool
  66. establishStartTime time.Time
  67. networkWaitDuration time.Duration
  68. }
  69. // NewController initializes a new controller.
  70. func NewController(config *Config) (controller *Controller, err error) {
  71. // Needed by regen, at least
  72. rand.Seed(int64(time.Now().Nanosecond()))
  73. // Supply a default HostNameTransformer
  74. if config.HostNameTransformer == nil {
  75. config.HostNameTransformer = &IdentityHostNameTransformer{}
  76. }
  77. // Generate a session ID for the Psiphon server API. This session ID is
  78. // used across all tunnels established by the controller.
  79. sessionId, err := MakeSessionId()
  80. if err != nil {
  81. return nil, common.ContextError(err)
  82. }
  83. NoticeSessionId(sessionId)
  84. // untunneledPendingConns may be used to interrupt the fetch remote server list
  85. // request and other untunneled connection establishments. BindToDevice may be
  86. // used to exclude these requests and connection from VPN routing.
  87. // TODO: fetch remote server list and untunneled upgrade download should remove
  88. // their completed conns from untunneledPendingConns.
  89. untunneledPendingConns := new(common.Conns)
  90. untunneledDialConfig := &DialConfig{
  91. UpstreamProxyUrl: config.UpstreamProxyUrl,
  92. UpstreamProxyCustomHeaders: config.UpstreamProxyCustomHeaders,
  93. PendingConns: untunneledPendingConns,
  94. DeviceBinder: config.DeviceBinder,
  95. DnsServerGetter: config.DnsServerGetter,
  96. UseIndistinguishableTLS: config.UseIndistinguishableTLS,
  97. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  98. DeviceRegion: config.DeviceRegion,
  99. }
  100. controller = &Controller{
  101. config: config,
  102. sessionId: sessionId,
  103. // componentFailureSignal receives a signal from a component (including socks and
  104. // http local proxies) if they unexpectedly fail. Senders should not block.
  105. // Buffer allows at least one stop signal to be sent before there is a receiver.
  106. componentFailureSignal: make(chan struct{}, 1),
  107. shutdownBroadcast: make(chan struct{}),
  108. runWaitGroup: new(sync.WaitGroup),
  109. // establishedTunnels and failedTunnels buffer sizes are large enough to
  110. // receive full pools of tunnels without blocking. Senders should not block.
  111. establishedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  112. failedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  113. tunnels: make([]*Tunnel, 0),
  114. establishedOnce: false,
  115. startedConnectedReporter: false,
  116. isEstablishing: false,
  117. establishPendingConns: new(common.Conns),
  118. untunneledPendingConns: untunneledPendingConns,
  119. untunneledDialConfig: untunneledDialConfig,
  120. impairedProtocolClassification: make(map[string]int),
  121. // TODO: Add a buffer of 1 so we don't miss a signal while receiver is
  122. // starting? Trade-off is potential back-to-back fetch remotes. As-is,
  123. // establish will eventually signal another fetch remote.
  124. signalFetchRemoteServerList: make(chan struct{}),
  125. signalDownloadUpgrade: make(chan string),
  126. signalReportConnected: make(chan struct{}),
  127. // Buffer allows SetClientVerificationPayloadForActiveTunnels to submit one
  128. // new payload without blocking or dropping it.
  129. newClientVerificationPayload: make(chan string, 1),
  130. }
  131. controller.splitTunnelClassifier = NewSplitTunnelClassifier(config, controller)
  132. return controller, nil
  133. }
  134. // Run executes the controller. It launches components and then monitors
  135. // for a shutdown signal; after receiving the signal it shuts down the
  136. // controller.
  137. // The components include:
  138. // - the periodic remote server list fetcher
  139. // - the connected reporter
  140. // - the tunnel manager
  141. // - a local SOCKS proxy that port forwards through the pool of tunnels
  142. // - a local HTTP proxy that port forwards through the pool of tunnels
  143. func (controller *Controller) Run(shutdownBroadcast <-chan struct{}) {
  144. ReportAvailableRegions()
  145. // Start components
  146. listenIP, err := GetInterfaceIPAddress(controller.config.ListenInterface)
  147. if err != nil {
  148. NoticeError("error getting listener IP: %s", err)
  149. return
  150. }
  151. socksProxy, err := NewSocksProxy(controller.config, controller, listenIP)
  152. if err != nil {
  153. NoticeAlert("error initializing local SOCKS proxy: %s", err)
  154. return
  155. }
  156. defer socksProxy.Close()
  157. httpProxy, err := NewHttpProxy(
  158. controller.config, controller.untunneledDialConfig, controller, listenIP)
  159. if err != nil {
  160. NoticeAlert("error initializing local HTTP proxy: %s", err)
  161. return
  162. }
  163. defer httpProxy.Close()
  164. if !controller.config.DisableRemoteServerListFetcher {
  165. controller.runWaitGroup.Add(1)
  166. go controller.remoteServerListFetcher()
  167. }
  168. if controller.config.UpgradeDownloadUrl != "" &&
  169. controller.config.UpgradeDownloadFilename != "" {
  170. controller.runWaitGroup.Add(1)
  171. go controller.upgradeDownloader()
  172. }
  173. /// Note: the connected reporter isn't started until a tunnel is
  174. // established
  175. controller.runWaitGroup.Add(1)
  176. go controller.runTunnels()
  177. if *controller.config.EstablishTunnelTimeoutSeconds != 0 {
  178. controller.runWaitGroup.Add(1)
  179. go controller.establishTunnelWatcher()
  180. }
  181. // Wait while running
  182. select {
  183. case <-shutdownBroadcast:
  184. NoticeInfo("controller shutdown by request")
  185. case <-controller.componentFailureSignal:
  186. NoticeAlert("controller shutdown due to component failure")
  187. }
  188. close(controller.shutdownBroadcast)
  189. // Interrupts and stops establish workers blocking on
  190. // tunnel establishment network operations.
  191. controller.establishPendingConns.CloseAll()
  192. // Interrupts and stops workers blocking on untunneled
  193. // network operations. This includes fetch remote server
  194. // list and untunneled uprade download.
  195. // Note: this doesn't interrupt the final, untunneled status
  196. // requests started in operateTunnel after shutdownBroadcast.
  197. // This is by design -- we want to give these requests a short
  198. // timer period to succeed and deliver stats. These particular
  199. // requests opt out of untunneledPendingConns and use the
  200. // PSIPHON_API_SHUTDOWN_SERVER_TIMEOUT timeout (see
  201. // doUntunneledStatusRequest).
  202. controller.untunneledPendingConns.CloseAll()
  203. // Now with all workers signaled to stop and with all
  204. // blocking network operations interrupted, wait for
  205. // all workers to terminate.
  206. controller.runWaitGroup.Wait()
  207. controller.splitTunnelClassifier.Shutdown()
  208. NoticeInfo("exiting controller")
  209. NoticeExiting()
  210. }
  211. // SignalComponentFailure notifies the controller that an associated component has failed.
  212. // This will terminate the controller.
  213. func (controller *Controller) SignalComponentFailure() {
  214. select {
  215. case controller.componentFailureSignal <- *new(struct{}):
  216. default:
  217. }
  218. }
  219. // SetClientVerificationPayloadForActiveTunnels sets the client verification
  220. // payload that is to be sent in client verification requests to all established
  221. // tunnels.
  222. //
  223. // Client verification is used to verify that the client is a
  224. // valid Psiphon client, which will determine how the server treats
  225. // the client traffic. The proof-of-validity is platform-specific
  226. // and the payload is opaque to this function but assumed to be JSON.
  227. //
  228. // Since, in some cases, verification payload cannot be determined until
  229. // after tunnel-core starts, the payload cannot be simply specified in
  230. // the Config.
  231. //
  232. // SetClientVerificationPayloadForActiveTunnels will not block enqueuing a new verification
  233. // payload. One new payload can be enqueued, after which additional payloads
  234. // will be dropped if a payload is still enqueued.
  235. func (controller *Controller) SetClientVerificationPayloadForActiveTunnels(clientVerificationPayload string) {
  236. select {
  237. case controller.newClientVerificationPayload <- clientVerificationPayload:
  238. default:
  239. }
  240. }
  241. // remoteServerListFetcher fetches an out-of-band list of server entries
  242. // for more tunnel candidates. It fetches when signalled, with retries
  243. // on failure.
  244. func (controller *Controller) remoteServerListFetcher() {
  245. defer controller.runWaitGroup.Done()
  246. if controller.config.RemoteServerListUrl == "" {
  247. NoticeAlert("remote server list URL is blank")
  248. return
  249. }
  250. if controller.config.RemoteServerListSignaturePublicKey == "" {
  251. NoticeAlert("remote server list signature public key blank")
  252. return
  253. }
  254. var lastFetchTime time.Time
  255. fetcherLoop:
  256. for {
  257. // Wait for a signal before fetching
  258. select {
  259. case <-controller.signalFetchRemoteServerList:
  260. case <-controller.shutdownBroadcast:
  261. break fetcherLoop
  262. }
  263. // Skip fetch entirely (i.e., send no request at all, even when ETag would save
  264. // on response size) when a recent fetch was successful
  265. if time.Now().Before(lastFetchTime.Add(FETCH_REMOTE_SERVER_LIST_STALE_PERIOD)) {
  266. continue
  267. }
  268. retryLoop:
  269. for {
  270. // Don't attempt to fetch while there is no network connectivity,
  271. // to avoid alert notice noise.
  272. if !WaitForNetworkConnectivity(
  273. controller.config.NetworkConnectivityChecker,
  274. controller.shutdownBroadcast) {
  275. break fetcherLoop
  276. }
  277. // Pick any active tunnel and make the next fetch attempt. If there's
  278. // no active tunnel, the untunneledDialConfig will be used.
  279. tunnel := controller.getNextActiveTunnel()
  280. err := FetchRemoteServerList(
  281. controller.config,
  282. tunnel,
  283. controller.untunneledDialConfig)
  284. if err == nil {
  285. lastFetchTime = time.Now()
  286. break retryLoop
  287. }
  288. NoticeAlert("failed to fetch remote server list: %s", err)
  289. timeout := time.After(
  290. time.Duration(*controller.config.FetchRemoteServerListRetryPeriodSeconds) * time.Second)
  291. select {
  292. case <-timeout:
  293. case <-controller.shutdownBroadcast:
  294. break fetcherLoop
  295. }
  296. }
  297. }
  298. NoticeInfo("exiting remote server list fetcher")
  299. }
  300. // establishTunnelWatcher terminates the controller if a tunnel
  301. // has not been established in the configured time period. This
  302. // is regardless of how many tunnels are presently active -- meaning
  303. // that if an active tunnel was established and lost the controller
  304. // is left running (to re-establish).
  305. func (controller *Controller) establishTunnelWatcher() {
  306. defer controller.runWaitGroup.Done()
  307. timeout := time.After(
  308. time.Duration(*controller.config.EstablishTunnelTimeoutSeconds) * time.Second)
  309. select {
  310. case <-timeout:
  311. if !controller.hasEstablishedOnce() {
  312. NoticeAlert("failed to establish tunnel before timeout")
  313. controller.SignalComponentFailure()
  314. }
  315. case <-controller.shutdownBroadcast:
  316. }
  317. NoticeInfo("exiting establish tunnel watcher")
  318. }
  319. // connectedReporter sends periodic "connected" requests to the Psiphon API.
  320. // These requests are for server-side unique user stats calculation. See the
  321. // comment in DoConnectedRequest for a description of the request mechanism.
  322. // To ensure we don't over- or under-count unique users, only one connected
  323. // request is made across all simultaneous multi-tunnels; and the connected
  324. // request is repeated periodically for very long-lived tunnels.
  325. // The signalReportConnected mechanism is used to trigger another connected
  326. // request immediately after a reconnect.
  327. func (controller *Controller) connectedReporter() {
  328. defer controller.runWaitGroup.Done()
  329. loop:
  330. for {
  331. // Pick any active tunnel and make the next connected request. No error
  332. // is logged if there's no active tunnel, as that's not an unexpected condition.
  333. reported := false
  334. tunnel := controller.getNextActiveTunnel()
  335. if tunnel != nil {
  336. err := tunnel.serverContext.DoConnectedRequest()
  337. if err == nil {
  338. reported = true
  339. } else {
  340. NoticeAlert("failed to make connected request: %s", err)
  341. }
  342. }
  343. // Schedule the next connected request and wait.
  344. var duration time.Duration
  345. if reported {
  346. duration = PSIPHON_API_CONNECTED_REQUEST_PERIOD
  347. } else {
  348. duration = PSIPHON_API_CONNECTED_REQUEST_RETRY_PERIOD
  349. }
  350. timeout := time.After(duration)
  351. select {
  352. case <-controller.signalReportConnected:
  353. case <-timeout:
  354. // Make another connected request
  355. case <-controller.shutdownBroadcast:
  356. break loop
  357. }
  358. }
  359. NoticeInfo("exiting connected reporter")
  360. }
  361. func (controller *Controller) startOrSignalConnectedReporter() {
  362. // session is nil when DisableApi is set
  363. if controller.config.DisableApi {
  364. return
  365. }
  366. // Start the connected reporter after the first tunnel is established.
  367. // Concurrency note: only the runTunnels goroutine may access startedConnectedReporter.
  368. if !controller.startedConnectedReporter {
  369. controller.startedConnectedReporter = true
  370. controller.runWaitGroup.Add(1)
  371. go controller.connectedReporter()
  372. } else {
  373. select {
  374. case controller.signalReportConnected <- *new(struct{}):
  375. default:
  376. }
  377. }
  378. }
  379. // upgradeDownloader makes periodic attemps to complete a client upgrade
  380. // download. DownloadUpgrade() is resumable, so each attempt has potential for
  381. // getting closer to completion, even in conditions where the download or
  382. // tunnel is repeatedly interrupted.
  383. // An upgrade download is triggered by either a handshake response indicating
  384. // that a new version is available; or after failing to connect, in which case
  385. // it's useful to check, out-of-band, for an upgrade with new circumvention
  386. // capabilities.
  387. // Once the download operation completes successfully, the downloader exits
  388. // and is not run again: either there is not a newer version, or the upgrade
  389. // has been downloaded and is ready to be applied.
  390. // We're assuming that the upgrade will be applied and the entire system
  391. // restarted before another upgrade is to be downloaded.
  392. //
  393. // TODO: refactor upgrade downloader and remote server list fetcher to use
  394. // common code (including the resumable download routines).
  395. //
  396. func (controller *Controller) upgradeDownloader() {
  397. defer controller.runWaitGroup.Done()
  398. var lastDownloadTime time.Time
  399. downloadLoop:
  400. for {
  401. // Wait for a signal before downloading
  402. var handshakeVersion string
  403. select {
  404. case handshakeVersion = <-controller.signalDownloadUpgrade:
  405. case <-controller.shutdownBroadcast:
  406. break downloadLoop
  407. }
  408. // Unless handshake is explicitly advertizing a new version, skip
  409. // checking entirely when a recent download was successful.
  410. if handshakeVersion == "" &&
  411. time.Now().Before(lastDownloadTime.Add(DOWNLOAD_UPGRADE_STALE_PERIOD)) {
  412. continue
  413. }
  414. retryLoop:
  415. for {
  416. // Don't attempt to download while there is no network connectivity,
  417. // to avoid alert notice noise.
  418. if !WaitForNetworkConnectivity(
  419. controller.config.NetworkConnectivityChecker,
  420. controller.shutdownBroadcast) {
  421. break downloadLoop
  422. }
  423. // Pick any active tunnel and make the next download attempt. If there's
  424. // no active tunnel, the untunneledDialConfig will be used.
  425. tunnel := controller.getNextActiveTunnel()
  426. err := DownloadUpgrade(
  427. controller.config,
  428. handshakeVersion,
  429. tunnel,
  430. controller.untunneledDialConfig)
  431. if err == nil {
  432. lastDownloadTime = time.Now()
  433. break retryLoop
  434. }
  435. NoticeAlert("failed to download upgrade: %s", err)
  436. timeout := time.After(
  437. time.Duration(*controller.config.DownloadUpgradeRetryPeriodSeconds) * time.Second)
  438. select {
  439. case <-timeout:
  440. case <-controller.shutdownBroadcast:
  441. break downloadLoop
  442. }
  443. }
  444. }
  445. NoticeInfo("exiting upgrade downloader")
  446. }
  447. // runTunnels is the controller tunnel management main loop. It starts and stops
  448. // establishing tunnels based on the target tunnel pool size and the current size
  449. // of the pool. Tunnels are established asynchronously using worker goroutines.
  450. //
  451. // When there are no server entries for the target region/protocol, the
  452. // establishCandidateGenerator will yield no candidates and wait before
  453. // trying again. In the meantime, a remote server entry fetch may supply
  454. // valid candidates.
  455. //
  456. // When a tunnel is established, it's added to the active pool. The tunnel's
  457. // operateTunnel goroutine monitors the tunnel.
  458. //
  459. // When a tunnel fails, it's removed from the pool and the establish process is
  460. // restarted to fill the pool.
  461. func (controller *Controller) runTunnels() {
  462. defer controller.runWaitGroup.Done()
  463. var clientVerificationPayload string
  464. // Start running
  465. controller.startEstablishing()
  466. loop:
  467. for {
  468. select {
  469. case failedTunnel := <-controller.failedTunnels:
  470. NoticeAlert("tunnel failed: %s", failedTunnel.serverEntry.IpAddress)
  471. controller.terminateTunnel(failedTunnel)
  472. // Note: we make this extra check to ensure the shutdown signal takes priority
  473. // and that we do not start establishing. Critically, startEstablishing() calls
  474. // establishPendingConns.Reset() which clears the closed flag in
  475. // establishPendingConns; this causes the pendingConns.Add() within
  476. // interruptibleTCPDial to succeed instead of aborting, and the result
  477. // is that it's possible for establish goroutines to run all the way through
  478. // NewServerContext before being discarded... delaying shutdown.
  479. select {
  480. case <-controller.shutdownBroadcast:
  481. break loop
  482. default:
  483. }
  484. controller.classifyImpairedProtocol(failedTunnel)
  485. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing
  486. // and access isEstablishing.
  487. if !controller.isEstablishing {
  488. controller.startEstablishing()
  489. }
  490. case establishedTunnel := <-controller.establishedTunnels:
  491. if controller.isImpairedProtocol(establishedTunnel.protocol) {
  492. NoticeAlert("established tunnel with impaired protocol: %s", establishedTunnel.protocol)
  493. // Protocol was classified as impaired while this tunnel
  494. // established, so discard.
  495. controller.discardTunnel(establishedTunnel)
  496. // Reset establish generator to stop producing tunnels
  497. // with impaired protocols.
  498. if controller.isEstablishing {
  499. controller.stopEstablishing()
  500. controller.startEstablishing()
  501. }
  502. break
  503. }
  504. tunnelCount, registered := controller.registerTunnel(establishedTunnel)
  505. if !registered {
  506. // Already fully established, so discard.
  507. controller.discardTunnel(establishedTunnel)
  508. break
  509. }
  510. NoticeActiveTunnel(establishedTunnel.serverEntry.IpAddress, establishedTunnel.protocol)
  511. if tunnelCount == 1 {
  512. // The split tunnel classifier is started once the first tunnel is
  513. // established. This first tunnel is passed in to be used to make
  514. // the routes data request.
  515. // A long-running controller may run while the host device is present
  516. // in different regions. In this case, we want the split tunnel logic
  517. // to switch to routes for new regions and not classify traffic based
  518. // on routes installed for older regions.
  519. // We assume that when regions change, the host network will also
  520. // change, and so all tunnels will fail and be re-established. Under
  521. // that assumption, the classifier will be re-Start()-ed here when
  522. // the region has changed.
  523. controller.splitTunnelClassifier.Start(establishedTunnel)
  524. // Signal a connected request on each 1st tunnel establishment. For
  525. // multi-tunnels, the session is connected as long as at least one
  526. // tunnel is established.
  527. controller.startOrSignalConnectedReporter()
  528. // If the handshake indicated that a new client version is available,
  529. // trigger an upgrade download.
  530. // Note: serverContext is nil when DisableApi is set
  531. if establishedTunnel.serverContext != nil &&
  532. establishedTunnel.serverContext.clientUpgradeVersion != "" {
  533. handshakeVersion := establishedTunnel.serverContext.clientUpgradeVersion
  534. select {
  535. case controller.signalDownloadUpgrade <- handshakeVersion:
  536. default:
  537. }
  538. }
  539. }
  540. // TODO: design issue -- might not be enough server entries with region/caps to ever fill tunnel slots;
  541. // possible solution is establish target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  542. if controller.isFullyEstablished() {
  543. controller.stopEstablishing()
  544. }
  545. case clientVerificationPayload = <-controller.newClientVerificationPayload:
  546. controller.setClientVerificationPayloadForActiveTunnels(clientVerificationPayload)
  547. case <-controller.shutdownBroadcast:
  548. break loop
  549. }
  550. }
  551. // Stop running
  552. controller.stopEstablishing()
  553. controller.terminateAllTunnels()
  554. // Drain tunnel channels
  555. close(controller.establishedTunnels)
  556. for tunnel := range controller.establishedTunnels {
  557. controller.discardTunnel(tunnel)
  558. }
  559. close(controller.failedTunnels)
  560. for tunnel := range controller.failedTunnels {
  561. controller.discardTunnel(tunnel)
  562. }
  563. NoticeInfo("exiting run tunnels")
  564. }
  565. // classifyImpairedProtocol tracks "impaired" protocol classifications for failed
  566. // tunnels. A protocol is classified as impaired if a tunnel using that protocol
  567. // fails, repeatedly, shortly after the start of the connection. During tunnel
  568. // establishment, impaired protocols are briefly skipped.
  569. //
  570. // One purpose of this measure is to defend against an attack where the adversary,
  571. // for example, tags an OSSH TCP connection as an "unidentified" protocol; allows
  572. // it to connect; but then kills the underlying TCP connection after a short time.
  573. // Since OSSH has less latency than other protocols that may bypass an "unidentified"
  574. // filter, these other protocols might never be selected for use.
  575. //
  576. // Concurrency note: only the runTunnels() goroutine may call classifyImpairedProtocol
  577. func (controller *Controller) classifyImpairedProtocol(failedTunnel *Tunnel) {
  578. if failedTunnel.establishedTime.Add(IMPAIRED_PROTOCOL_CLASSIFICATION_DURATION).After(time.Now()) {
  579. controller.impairedProtocolClassification[failedTunnel.protocol] += 1
  580. } else {
  581. controller.impairedProtocolClassification[failedTunnel.protocol] = 0
  582. }
  583. if len(controller.getImpairedProtocols()) == len(common.SupportedTunnelProtocols) {
  584. // Reset classification if all protocols are classified as impaired as
  585. // the network situation (or attack) may not be protocol-specific.
  586. // TODO: compare against count of distinct supported protocols for
  587. // current known server entries.
  588. controller.impairedProtocolClassification = make(map[string]int)
  589. }
  590. }
  591. // getImpairedProtocols returns a list of protocols that have sufficient
  592. // classifications to be considered impaired protocols.
  593. //
  594. // Concurrency note: only the runTunnels() goroutine may call getImpairedProtocols
  595. func (controller *Controller) getImpairedProtocols() []string {
  596. NoticeImpairedProtocolClassification(controller.impairedProtocolClassification)
  597. impairedProtocols := make([]string, 0)
  598. for protocol, count := range controller.impairedProtocolClassification {
  599. if count >= IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD {
  600. impairedProtocols = append(impairedProtocols, protocol)
  601. }
  602. }
  603. return impairedProtocols
  604. }
  605. // isImpairedProtocol checks if the specified protocol is classified as impaired.
  606. //
  607. // Concurrency note: only the runTunnels() goroutine may call isImpairedProtocol
  608. func (controller *Controller) isImpairedProtocol(protocol string) bool {
  609. count, ok := controller.impairedProtocolClassification[protocol]
  610. return ok && count >= IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD
  611. }
  612. // SignalTunnelFailure implements the TunnelOwner interface. This function
  613. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  614. // has failed. The Controller will signal runTunnels to create a new
  615. // tunnel and/or remove the tunnel from the list of active tunnels.
  616. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  617. // Don't block. Assumes the receiver has a buffer large enough for
  618. // the typical number of operated tunnels. In case there's no room,
  619. // terminate the tunnel (runTunnels won't get a signal in this case,
  620. // but the tunnel will be removed from the list of active tunnels).
  621. select {
  622. case controller.failedTunnels <- tunnel:
  623. default:
  624. controller.terminateTunnel(tunnel)
  625. }
  626. }
  627. // discardTunnel disposes of a successful connection that is no longer required.
  628. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  629. NoticeInfo("discard tunnel: %s", tunnel.serverEntry.IpAddress)
  630. // TODO: not calling PromoteServerEntry, since that would rank the
  631. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  632. // be promoted (since it connects), but with lower rank than all active
  633. // tunnels?
  634. tunnel.Close(true)
  635. }
  636. // registerTunnel adds the connected tunnel to the pool of active tunnels
  637. // which are candidates for port forwarding. Returns true if the pool has an
  638. // empty slot and false if the pool is full (caller should discard the tunnel).
  639. func (controller *Controller) registerTunnel(tunnel *Tunnel) (int, bool) {
  640. controller.tunnelMutex.Lock()
  641. defer controller.tunnelMutex.Unlock()
  642. if len(controller.tunnels) >= controller.config.TunnelPoolSize {
  643. return len(controller.tunnels), false
  644. }
  645. // Perform a final check just in case we've established
  646. // a duplicate connection.
  647. for _, activeTunnel := range controller.tunnels {
  648. if activeTunnel.serverEntry.IpAddress == tunnel.serverEntry.IpAddress {
  649. NoticeAlert("duplicate tunnel: %s", tunnel.serverEntry.IpAddress)
  650. return len(controller.tunnels), false
  651. }
  652. }
  653. controller.establishedOnce = true
  654. controller.tunnels = append(controller.tunnels, tunnel)
  655. NoticeTunnels(len(controller.tunnels))
  656. // Promote this successful tunnel to first rank so it's one
  657. // of the first candidates next time establish runs.
  658. // Connecting to a TargetServerEntry does not change the
  659. // ranking.
  660. if controller.config.TargetServerEntry == "" {
  661. PromoteServerEntry(tunnel.serverEntry.IpAddress)
  662. }
  663. return len(controller.tunnels), true
  664. }
  665. // hasEstablishedOnce indicates if at least one active tunnel has
  666. // been established up to this point. This is regardeless of how many
  667. // tunnels are presently active.
  668. func (controller *Controller) hasEstablishedOnce() bool {
  669. controller.tunnelMutex.Lock()
  670. defer controller.tunnelMutex.Unlock()
  671. return controller.establishedOnce
  672. }
  673. // isFullyEstablished indicates if the pool of active tunnels is full.
  674. func (controller *Controller) isFullyEstablished() bool {
  675. controller.tunnelMutex.Lock()
  676. defer controller.tunnelMutex.Unlock()
  677. return len(controller.tunnels) >= controller.config.TunnelPoolSize
  678. }
  679. // terminateTunnel removes a tunnel from the pool of active tunnels
  680. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  681. // is adjusted as required.
  682. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  683. controller.tunnelMutex.Lock()
  684. defer controller.tunnelMutex.Unlock()
  685. for index, activeTunnel := range controller.tunnels {
  686. if tunnel == activeTunnel {
  687. controller.tunnels = append(
  688. controller.tunnels[:index], controller.tunnels[index+1:]...)
  689. if controller.nextTunnel > index {
  690. controller.nextTunnel--
  691. }
  692. if controller.nextTunnel >= len(controller.tunnels) {
  693. controller.nextTunnel = 0
  694. }
  695. activeTunnel.Close(false)
  696. NoticeTunnels(len(controller.tunnels))
  697. break
  698. }
  699. }
  700. }
  701. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  702. // This is used when shutting down the controller.
  703. func (controller *Controller) terminateAllTunnels() {
  704. controller.tunnelMutex.Lock()
  705. defer controller.tunnelMutex.Unlock()
  706. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  707. // may take a few seconds to send a final status request. We only want
  708. // to wait as long as the single slowest tunnel.
  709. closeWaitGroup := new(sync.WaitGroup)
  710. closeWaitGroup.Add(len(controller.tunnels))
  711. for _, activeTunnel := range controller.tunnels {
  712. tunnel := activeTunnel
  713. go func() {
  714. defer closeWaitGroup.Done()
  715. tunnel.Close(false)
  716. }()
  717. }
  718. closeWaitGroup.Wait()
  719. controller.tunnels = make([]*Tunnel, 0)
  720. controller.nextTunnel = 0
  721. NoticeTunnels(len(controller.tunnels))
  722. }
  723. // getNextActiveTunnel returns the next tunnel from the pool of active
  724. // tunnels. Currently, tunnel selection order is simple round-robin.
  725. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  726. controller.tunnelMutex.Lock()
  727. defer controller.tunnelMutex.Unlock()
  728. for i := len(controller.tunnels); i > 0; i-- {
  729. tunnel = controller.tunnels[controller.nextTunnel]
  730. controller.nextTunnel =
  731. (controller.nextTunnel + 1) % len(controller.tunnels)
  732. return tunnel
  733. }
  734. return nil
  735. }
  736. // isActiveTunnelServerEntry is used to check if there's already
  737. // an existing tunnel to a candidate server.
  738. func (controller *Controller) isActiveTunnelServerEntry(serverEntry *ServerEntry) bool {
  739. controller.tunnelMutex.Lock()
  740. defer controller.tunnelMutex.Unlock()
  741. for _, activeTunnel := range controller.tunnels {
  742. if activeTunnel.serverEntry.IpAddress == serverEntry.IpAddress {
  743. return true
  744. }
  745. }
  746. return false
  747. }
  748. // setClientVerificationPayloadForActiveTunnels triggers the client verification
  749. // request for all active tunnels.
  750. func (controller *Controller) setClientVerificationPayloadForActiveTunnels(
  751. clientVerificationPayload string) {
  752. controller.tunnelMutex.Lock()
  753. defer controller.tunnelMutex.Unlock()
  754. for _, activeTunnel := range controller.tunnels {
  755. activeTunnel.SetClientVerificationPayload(clientVerificationPayload)
  756. }
  757. }
  758. // Dial selects an active tunnel and establishes a port forward
  759. // connection through the selected tunnel. Failure to connect is considered
  760. // a port foward failure, for the purpose of monitoring tunnel health.
  761. func (controller *Controller) Dial(
  762. remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error) {
  763. tunnel := controller.getNextActiveTunnel()
  764. if tunnel == nil {
  765. return nil, common.ContextError(errors.New("no active tunnels"))
  766. }
  767. // Perform split tunnel classification when feature is enabled, and if the remote
  768. // address is classified as untunneled, dial directly.
  769. if !alwaysTunnel && controller.config.SplitTunnelDnsServer != "" {
  770. host, _, err := net.SplitHostPort(remoteAddr)
  771. if err != nil {
  772. return nil, common.ContextError(err)
  773. }
  774. // Note: a possible optimization, when split tunnel is active and IsUntunneled performs
  775. // a DNS resolution in order to make its classification, is to reuse that IP address in
  776. // the following Dials so they do not need to make their own resolutions. However, the
  777. // way this is currently implemented ensures that, e.g., DNS geo load balancing occurs
  778. // relative to the outbound network.
  779. if controller.splitTunnelClassifier.IsUntunneled(host) {
  780. // TODO: track downstreamConn and close it when the DialTCP conn closes, as with tunnel.Dial conns?
  781. return DialTCP(remoteAddr, controller.untunneledDialConfig)
  782. }
  783. }
  784. tunneledConn, err := tunnel.Dial(remoteAddr, alwaysTunnel, downstreamConn)
  785. if err != nil {
  786. return nil, common.ContextError(err)
  787. }
  788. return tunneledConn, nil
  789. }
  790. // startEstablishing creates a pool of worker goroutines which will
  791. // attempt to establish tunnels to candidate servers. The candidates
  792. // are generated by another goroutine.
  793. func (controller *Controller) startEstablishing() {
  794. if controller.isEstablishing {
  795. return
  796. }
  797. NoticeInfo("start establishing")
  798. controller.isEstablishing = true
  799. controller.establishWaitGroup = new(sync.WaitGroup)
  800. controller.stopEstablishingBroadcast = make(chan struct{})
  801. controller.candidateServerEntries = make(chan *candidateServerEntry)
  802. controller.establishPendingConns.Reset()
  803. // The server affinity mechanism attempts to favor the previously
  804. // used server when reconnecting. This is beneficial for user
  805. // applications which expect consistency in user IP address (for
  806. // example, a web site which prompts for additional user
  807. // authentication when the IP address changes).
  808. //
  809. // Only the very first server, as determined by
  810. // datastore.PromoteServerEntry(), is the server affinity candidate.
  811. // Concurrent connections attempts to many servers are launched
  812. // without delay, in case the affinity server connection fails.
  813. // While the affinity server connection is outstanding, when any
  814. // other connection is established, there is a short grace period
  815. // delay before delivering the established tunnel; this allows some
  816. // time for the affinity server connection to succeed first.
  817. // When the affinity server connection fails, any other established
  818. // tunnel is registered without delay.
  819. //
  820. // Note: the establishTunnelWorker that receives the affinity
  821. // candidate is solely resonsible for closing
  822. // controller.serverAffinityDoneBroadcast.
  823. //
  824. // Note: if config.EgressRegion or config.TunnelProtocol has changed
  825. // since the top server was promoted, the first server may not actually
  826. // be the last connected server.
  827. // TODO: should not favor the first server in this case
  828. controller.serverAffinityDoneBroadcast = make(chan struct{})
  829. for i := 0; i < controller.config.ConnectionWorkerPoolSize; i++ {
  830. controller.establishWaitGroup.Add(1)
  831. go controller.establishTunnelWorker()
  832. }
  833. controller.establishWaitGroup.Add(1)
  834. go controller.establishCandidateGenerator(
  835. controller.getImpairedProtocols())
  836. }
  837. // stopEstablishing signals the establish goroutines to stop and waits
  838. // for the group to halt. pendingConns is used to interrupt any worker
  839. // blocked on a socket connect.
  840. func (controller *Controller) stopEstablishing() {
  841. if !controller.isEstablishing {
  842. return
  843. }
  844. NoticeInfo("stop establishing")
  845. close(controller.stopEstablishingBroadcast)
  846. // Note: interruptibleTCPClose doesn't really interrupt socket connects
  847. // and may leave goroutines running for a time after the Wait call.
  848. controller.establishPendingConns.CloseAll()
  849. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  850. // (as it may be sending to that channel).
  851. controller.establishWaitGroup.Wait()
  852. controller.isEstablishing = false
  853. controller.establishWaitGroup = nil
  854. controller.stopEstablishingBroadcast = nil
  855. controller.candidateServerEntries = nil
  856. controller.serverAffinityDoneBroadcast = nil
  857. }
  858. // establishCandidateGenerator populates the candidate queue with server entries
  859. // from the data store. Server entries are iterated in rank order, so that promoted
  860. // servers with higher rank are priority candidates.
  861. func (controller *Controller) establishCandidateGenerator(impairedProtocols []string) {
  862. defer controller.establishWaitGroup.Done()
  863. defer close(controller.candidateServerEntries)
  864. // establishStartTime is used to calculate and report the
  865. // client's tunnel establishment duration.
  866. //
  867. // networkWaitDuration is the elapsed time spent waiting
  868. // for network connectivity. This duration will be excluded
  869. // from reported tunnel establishment duration.
  870. // networkWaitDuration may include device sleep time.
  871. establishStartTime := time.Now()
  872. var networkWaitDuration time.Duration
  873. iterator, err := NewServerEntryIterator(controller.config)
  874. if err != nil {
  875. NoticeAlert("failed to iterate over candidates: %s", err)
  876. controller.SignalComponentFailure()
  877. return
  878. }
  879. defer iterator.Close()
  880. isServerAffinityCandidate := true
  881. // TODO: reconcile server affinity scheme with multi-tunnel mode
  882. if controller.config.TunnelPoolSize > 1 {
  883. isServerAffinityCandidate = false
  884. close(controller.serverAffinityDoneBroadcast)
  885. }
  886. loop:
  887. // Repeat until stopped
  888. for i := 0; ; i++ {
  889. networkWaitStartTime := time.Now()
  890. if !WaitForNetworkConnectivity(
  891. controller.config.NetworkConnectivityChecker,
  892. controller.stopEstablishingBroadcast,
  893. controller.shutdownBroadcast) {
  894. break loop
  895. }
  896. networkWaitDuration += time.Since(networkWaitStartTime)
  897. // Send each iterator server entry to the establish workers
  898. startTime := time.Now()
  899. for {
  900. serverEntry, err := iterator.Next()
  901. if err != nil {
  902. NoticeAlert("failed to get next candidate: %s", err)
  903. controller.SignalComponentFailure()
  904. break loop
  905. }
  906. if serverEntry == nil {
  907. // Completed this iteration
  908. break
  909. }
  910. // Disable impaired protocols. This is only done for the
  911. // first iteration of the ESTABLISH_TUNNEL_WORK_TIME
  912. // loop since (a) one iteration should be sufficient to
  913. // evade the attack; (b) there's a good chance of false
  914. // positives (such as short tunnel durations due to network
  915. // hopping on a mobile device).
  916. // Impaired protocols logic is not applied when
  917. // config.TunnelProtocol is specified.
  918. // The edited serverEntry is temporary copy which is not
  919. // stored or reused.
  920. if i == 0 && controller.config.TunnelProtocol == "" {
  921. serverEntry.DisableImpairedProtocols(impairedProtocols)
  922. if len(serverEntry.GetSupportedProtocols()) == 0 {
  923. // Skip this server entry, as it has no supported
  924. // protocols after disabling the impaired ones
  925. // TODO: modify ServerEntryIterator to skip these?
  926. continue
  927. }
  928. }
  929. candidate := &candidateServerEntry{
  930. serverEntry: serverEntry,
  931. isServerAffinityCandidate: isServerAffinityCandidate,
  932. establishStartTime: establishStartTime,
  933. networkWaitDuration: networkWaitDuration,
  934. }
  935. // Note: there must be only one server affinity candidate, as it
  936. // closes the serverAffinityDoneBroadcast channel.
  937. isServerAffinityCandidate = false
  938. // TODO: here we could generate multiple candidates from the
  939. // server entry when there are many MeekFrontingAddresses.
  940. select {
  941. case controller.candidateServerEntries <- candidate:
  942. case <-controller.stopEstablishingBroadcast:
  943. break loop
  944. case <-controller.shutdownBroadcast:
  945. break loop
  946. }
  947. if time.Now().After(startTime.Add(ESTABLISH_TUNNEL_WORK_TIME)) {
  948. // Start over, after a brief pause, with a new shuffle of the server
  949. // entries, and potentially some newly fetched server entries.
  950. break
  951. }
  952. }
  953. // Free up resources now, but don't reset until after the pause.
  954. iterator.Close()
  955. // Trigger a fetch remote server list, since we may have failed to
  956. // connect with all known servers. Don't block sending signal, since
  957. // this signal may have already been sent.
  958. // Don't wait for fetch remote to succeed, since it may fail and
  959. // enter a retry loop and we're better off trying more known servers.
  960. // TODO: synchronize the fetch response, so it can be incorporated
  961. // into the server entry iterator as soon as available.
  962. select {
  963. case controller.signalFetchRemoteServerList <- *new(struct{}):
  964. default:
  965. }
  966. // Trigger an out-of-band upgrade availability check and download.
  967. // Since we may have failed to connect, we may benefit from upgrading
  968. // to a new client version with new circumvention capabilities.
  969. select {
  970. case controller.signalDownloadUpgrade <- "":
  971. default:
  972. }
  973. // After a complete iteration of candidate servers, pause before iterating again.
  974. // This helps avoid some busy wait loop conditions, and also allows some time for
  975. // network conditions to change. Also allows for fetch remote to complete,
  976. // in typical conditions (it isn't strictly necessary to wait for this, there will
  977. // be more rounds if required).
  978. timeout := time.After(
  979. time.Duration(*controller.config.EstablishTunnelPausePeriodSeconds) * time.Second)
  980. select {
  981. case <-timeout:
  982. // Retry iterating
  983. case <-controller.stopEstablishingBroadcast:
  984. break loop
  985. case <-controller.shutdownBroadcast:
  986. break loop
  987. }
  988. iterator.Reset()
  989. }
  990. NoticeInfo("stopped candidate generator")
  991. }
  992. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  993. // a connection to the tunnel server, and delivers the established tunnel to a channel.
  994. func (controller *Controller) establishTunnelWorker() {
  995. defer controller.establishWaitGroup.Done()
  996. loop:
  997. for candidateServerEntry := range controller.candidateServerEntries {
  998. // Note: don't receive from candidateServerEntries and stopEstablishingBroadcast
  999. // in the same select, since we want to prioritize receiving the stop signal
  1000. if controller.isStopEstablishingBroadcast() {
  1001. break loop
  1002. }
  1003. // There may already be a tunnel to this candidate. If so, skip it.
  1004. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  1005. continue
  1006. }
  1007. tunnel, err := EstablishTunnel(
  1008. controller.config,
  1009. controller.untunneledDialConfig,
  1010. controller.sessionId,
  1011. controller.establishPendingConns,
  1012. candidateServerEntry.serverEntry,
  1013. candidateServerEntry.establishStartTime,
  1014. candidateServerEntry.networkWaitDuration,
  1015. controller) // TunnelOwner
  1016. if err != nil {
  1017. // Unblock other candidates immediately when
  1018. // server affinity candidate fails.
  1019. if candidateServerEntry.isServerAffinityCandidate {
  1020. close(controller.serverAffinityDoneBroadcast)
  1021. }
  1022. // Before emitting error, check if establish interrupted, in which
  1023. // case the error is noise.
  1024. if controller.isStopEstablishingBroadcast() {
  1025. break loop
  1026. }
  1027. NoticeInfo("failed to connect to %s: %s", candidateServerEntry.serverEntry.IpAddress, err)
  1028. continue
  1029. }
  1030. // Block for server affinity grace period before delivering.
  1031. if !candidateServerEntry.isServerAffinityCandidate {
  1032. timer := time.NewTimer(ESTABLISH_TUNNEL_SERVER_AFFINITY_GRACE_PERIOD)
  1033. select {
  1034. case <-timer.C:
  1035. case <-controller.serverAffinityDoneBroadcast:
  1036. case <-controller.stopEstablishingBroadcast:
  1037. }
  1038. }
  1039. // Deliver established tunnel.
  1040. // Don't block. Assumes the receiver has a buffer large enough for
  1041. // the number of desired tunnels. If there's no room, the tunnel must
  1042. // not be required so it's discarded.
  1043. select {
  1044. case controller.establishedTunnels <- tunnel:
  1045. default:
  1046. controller.discardTunnel(tunnel)
  1047. }
  1048. // Unblock other candidates only after delivering when
  1049. // server affinity candidate succeeds.
  1050. if candidateServerEntry.isServerAffinityCandidate {
  1051. close(controller.serverAffinityDoneBroadcast)
  1052. }
  1053. }
  1054. NoticeInfo("stopped establish worker")
  1055. }
  1056. func (controller *Controller) isStopEstablishingBroadcast() bool {
  1057. select {
  1058. case <-controller.stopEstablishingBroadcast:
  1059. return true
  1060. default:
  1061. }
  1062. return false
  1063. }