controller.go 43 KB

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