controller.go 45 KB

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