controller.go 44 KB

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