controller.go 45 KB

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