controller.go 45 KB

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