controller.go 45 KB

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