controller.go 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  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. CustomHeaders: config.CustomHeaders,
  91. PendingConns: untunneledPendingConns,
  92. DeviceBinder: config.DeviceBinder,
  93. DnsServerGetter: config.DnsServerGetter,
  94. IPv6Synthesizer: config.IPv6Synthesizer,
  95. UseIndistinguishableTLS: config.UseIndistinguishableTLS,
  96. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  97. DeviceRegion: config.DeviceRegion,
  98. }
  99. controller = &Controller{
  100. config: config,
  101. sessionId: sessionId,
  102. // componentFailureSignal receives a signal from a component (including socks and
  103. // http local proxies) if they unexpectedly fail. Senders should not block.
  104. // Buffer allows at least one stop signal to be sent before there is a receiver.
  105. componentFailureSignal: make(chan struct{}, 1),
  106. shutdownBroadcast: make(chan struct{}),
  107. runWaitGroup: new(sync.WaitGroup),
  108. // establishedTunnels and failedTunnels buffer sizes are large enough to
  109. // receive full pools of tunnels without blocking. Senders should not block.
  110. establishedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  111. failedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  112. tunnels: make([]*Tunnel, 0),
  113. establishedOnce: false,
  114. startedConnectedReporter: false,
  115. isEstablishing: false,
  116. establishPendingConns: new(common.Conns),
  117. untunneledPendingConns: untunneledPendingConns,
  118. untunneledDialConfig: untunneledDialConfig,
  119. impairedProtocolClassification: make(map[string]int),
  120. // TODO: Add a buffer of 1 so we don't miss a signal while receiver is
  121. // starting? Trade-off is potential back-to-back fetch remotes. As-is,
  122. // establish will eventually signal another fetch remote.
  123. signalFetchCommonRemoteServerList: make(chan struct{}),
  124. signalFetchObfuscatedServerLists: make(chan struct{}),
  125. signalDownloadUpgrade: make(chan string),
  126. signalReportConnected: make(chan struct{}),
  127. // Buffer allows SetClientVerificationPayloadForActiveTunnels to submit one
  128. // new payload without blocking or dropping it.
  129. newClientVerificationPayload: make(chan string, 1),
  130. }
  131. controller.splitTunnelClassifier = NewSplitTunnelClassifier(config, controller)
  132. return controller, nil
  133. }
  134. // Run executes the controller. It launches components and then monitors
  135. // for a shutdown signal; after receiving the signal it shuts down the
  136. // controller.
  137. // The components include:
  138. // - the periodic remote server list fetcher
  139. // - the connected reporter
  140. // - the tunnel manager
  141. // - a local SOCKS proxy that port forwards through the pool of tunnels
  142. // - a local HTTP proxy that port forwards through the pool of tunnels
  143. func (controller *Controller) Run(shutdownBroadcast <-chan struct{}) {
  144. ReportAvailableRegions()
  145. // Start components
  146. listenIP, err := common.GetInterfaceIPAddress(controller.config.ListenInterface)
  147. if err != nil {
  148. NoticeError("error getting listener IP: %s", err)
  149. return
  150. }
  151. socksProxy, err := NewSocksProxy(controller.config, controller, listenIP)
  152. if err != nil {
  153. NoticeAlert("error initializing local SOCKS proxy: %s", err)
  154. return
  155. }
  156. defer socksProxy.Close()
  157. httpProxy, err := NewHttpProxy(
  158. controller.config, controller.untunneledDialConfig, controller, listenIP)
  159. if err != nil {
  160. NoticeAlert("error initializing local HTTP proxy: %s", err)
  161. return
  162. }
  163. defer httpProxy.Close()
  164. if !controller.config.DisableRemoteServerListFetcher {
  165. retryPeriod := time.Duration(
  166. *controller.config.FetchRemoteServerListRetryPeriodSeconds) * time.Second
  167. if controller.config.RemoteServerListURLs != nil {
  168. controller.runWaitGroup.Add(1)
  169. go controller.remoteServerListFetcher(
  170. "common",
  171. FetchCommonRemoteServerList,
  172. controller.signalFetchCommonRemoteServerList,
  173. retryPeriod,
  174. FETCH_REMOTE_SERVER_LIST_STALE_PERIOD)
  175. }
  176. if controller.config.ObfuscatedServerListRootURLs != nil {
  177. controller.runWaitGroup.Add(1)
  178. go controller.remoteServerListFetcher(
  179. "obfuscated",
  180. FetchObfuscatedServerLists,
  181. controller.signalFetchObfuscatedServerLists,
  182. retryPeriod,
  183. FETCH_REMOTE_SERVER_LIST_STALE_PERIOD)
  184. }
  185. }
  186. if controller.config.UpgradeDownloadURLs != nil {
  187. controller.runWaitGroup.Add(1)
  188. go controller.upgradeDownloader()
  189. }
  190. /// Note: the connected reporter isn't started until a tunnel is
  191. // established
  192. controller.runWaitGroup.Add(1)
  193. go controller.runTunnels()
  194. if *controller.config.EstablishTunnelTimeoutSeconds != 0 {
  195. controller.runWaitGroup.Add(1)
  196. go controller.establishTunnelWatcher()
  197. }
  198. // Wait while running
  199. select {
  200. case <-shutdownBroadcast:
  201. NoticeInfo("controller shutdown by request")
  202. case <-controller.componentFailureSignal:
  203. NoticeAlert("controller shutdown due to component failure")
  204. }
  205. close(controller.shutdownBroadcast)
  206. // Interrupts and stops establish workers blocking on
  207. // tunnel establishment network operations.
  208. controller.establishPendingConns.CloseAll()
  209. // Interrupts and stops workers blocking on untunneled
  210. // network operations. This includes fetch remote server
  211. // list and untunneled uprade download.
  212. // Note: this doesn't interrupt the final, untunneled status
  213. // requests started in operateTunnel after shutdownBroadcast.
  214. // This is by design -- we want to give these requests a short
  215. // timer period to succeed and deliver stats. These particular
  216. // requests opt out of untunneledPendingConns and use the
  217. // PSIPHON_API_SHUTDOWN_SERVER_TIMEOUT timeout (see
  218. // doUntunneledStatusRequest).
  219. controller.untunneledPendingConns.CloseAll()
  220. // Now with all workers signaled to stop and with all
  221. // blocking network operations interrupted, wait for
  222. // all workers to terminate.
  223. controller.runWaitGroup.Wait()
  224. controller.splitTunnelClassifier.Shutdown()
  225. NoticeInfo("exiting controller")
  226. NoticeExiting()
  227. }
  228. // SignalComponentFailure notifies the controller that an associated component has failed.
  229. // This will terminate the controller.
  230. func (controller *Controller) SignalComponentFailure() {
  231. select {
  232. case controller.componentFailureSignal <- *new(struct{}):
  233. default:
  234. }
  235. }
  236. // SetClientVerificationPayloadForActiveTunnels sets the client verification
  237. // payload that is to be sent in client verification requests to all established
  238. // tunnels.
  239. //
  240. // Client verification is used to verify that the client is a
  241. // valid Psiphon client, which will determine how the server treats
  242. // the client traffic. The proof-of-validity is platform-specific
  243. // and the payload is opaque to this function but assumed to be JSON.
  244. //
  245. // Since, in some cases, verification payload cannot be determined until
  246. // after tunnel-core starts, the payload cannot be simply specified in
  247. // the Config.
  248. //
  249. // SetClientVerificationPayloadForActiveTunnels will not block enqueuing a new verification
  250. // payload. One new payload can be enqueued, after which additional payloads
  251. // will be dropped if a payload is still enqueued.
  252. func (controller *Controller) SetClientVerificationPayloadForActiveTunnels(clientVerificationPayload string) {
  253. select {
  254. case controller.newClientVerificationPayload <- clientVerificationPayload:
  255. default:
  256. }
  257. }
  258. // remoteServerListFetcher fetches an out-of-band list of server entries
  259. // for more tunnel candidates. It fetches when signalled, with retries
  260. // on failure.
  261. func (controller *Controller) remoteServerListFetcher(
  262. name string,
  263. fetcher RemoteServerListFetcher,
  264. signal <-chan struct{},
  265. retryPeriod, stalePeriod time.Duration) {
  266. defer controller.runWaitGroup.Done()
  267. var lastFetchTime monotime.Time
  268. fetcherLoop:
  269. for {
  270. // Wait for a signal before fetching
  271. select {
  272. case <-signal:
  273. case <-controller.shutdownBroadcast:
  274. break fetcherLoop
  275. }
  276. // Skip fetch entirely (i.e., send no request at all, even when ETag would save
  277. // on response size) when a recent fetch was successful
  278. if lastFetchTime != 0 &&
  279. lastFetchTime.Add(stalePeriod).After(monotime.Now()) {
  280. continue
  281. }
  282. retryLoop:
  283. for attempt := 0; ; attempt++ {
  284. // Don't attempt to fetch while there is no network connectivity,
  285. // to avoid alert notice noise.
  286. if !WaitForNetworkConnectivity(
  287. controller.config.NetworkConnectivityChecker,
  288. controller.shutdownBroadcast) {
  289. break fetcherLoop
  290. }
  291. // Pick any active tunnel and make the next fetch attempt. If there's
  292. // no active tunnel, the untunneledDialConfig will be used.
  293. tunnel := controller.getNextActiveTunnel()
  294. err := fetcher(
  295. controller.config,
  296. attempt,
  297. tunnel,
  298. controller.untunneledDialConfig)
  299. if err == nil {
  300. lastFetchTime = monotime.Now()
  301. break retryLoop
  302. }
  303. NoticeAlert("failed to fetch %s remote server list: %s", name, err)
  304. timeout := time.After(retryPeriod)
  305. select {
  306. case <-timeout:
  307. case <-controller.shutdownBroadcast:
  308. break fetcherLoop
  309. }
  310. }
  311. }
  312. NoticeInfo("exiting %s remote server list fetcher", name)
  313. }
  314. // establishTunnelWatcher terminates the controller if a tunnel
  315. // has not been established in the configured time period. This
  316. // is regardless of how many tunnels are presently active -- meaning
  317. // that if an active tunnel was established and lost the controller
  318. // is left running (to re-establish).
  319. func (controller *Controller) establishTunnelWatcher() {
  320. defer controller.runWaitGroup.Done()
  321. timeout := time.After(
  322. time.Duration(*controller.config.EstablishTunnelTimeoutSeconds) * time.Second)
  323. select {
  324. case <-timeout:
  325. if !controller.hasEstablishedOnce() {
  326. NoticeAlert("failed to establish tunnel before timeout")
  327. controller.SignalComponentFailure()
  328. }
  329. case <-controller.shutdownBroadcast:
  330. }
  331. NoticeInfo("exiting establish tunnel watcher")
  332. }
  333. // connectedReporter sends periodic "connected" requests to the Psiphon API.
  334. // These requests are for server-side unique user stats calculation. See the
  335. // comment in DoConnectedRequest for a description of the request mechanism.
  336. // To ensure we don't over- or under-count unique users, only one connected
  337. // request is made across all simultaneous multi-tunnels; and the connected
  338. // request is repeated periodically for very long-lived tunnels.
  339. // The signalReportConnected mechanism is used to trigger another connected
  340. // request immediately after a reconnect.
  341. func (controller *Controller) connectedReporter() {
  342. defer controller.runWaitGroup.Done()
  343. loop:
  344. for {
  345. // Pick any active tunnel and make the next connected request. No error
  346. // is logged if there's no active tunnel, as that's not an unexpected condition.
  347. reported := false
  348. tunnel := controller.getNextActiveTunnel()
  349. if tunnel != nil {
  350. err := tunnel.serverContext.DoConnectedRequest()
  351. if err == nil {
  352. reported = true
  353. } else {
  354. NoticeAlert("failed to make connected request: %s", err)
  355. }
  356. }
  357. // Schedule the next connected request and wait.
  358. var duration time.Duration
  359. if reported {
  360. duration = PSIPHON_API_CONNECTED_REQUEST_PERIOD
  361. } else {
  362. duration = PSIPHON_API_CONNECTED_REQUEST_RETRY_PERIOD
  363. }
  364. timeout := time.After(duration)
  365. select {
  366. case <-controller.signalReportConnected:
  367. case <-timeout:
  368. // Make another connected request
  369. case <-controller.shutdownBroadcast:
  370. break loop
  371. }
  372. }
  373. NoticeInfo("exiting connected reporter")
  374. }
  375. func (controller *Controller) startOrSignalConnectedReporter() {
  376. // session is nil when DisableApi is set
  377. if controller.config.DisableApi {
  378. return
  379. }
  380. // Start the connected reporter after the first tunnel is established.
  381. // Concurrency note: only the runTunnels goroutine may access startedConnectedReporter.
  382. if !controller.startedConnectedReporter {
  383. controller.startedConnectedReporter = true
  384. controller.runWaitGroup.Add(1)
  385. go controller.connectedReporter()
  386. } else {
  387. select {
  388. case controller.signalReportConnected <- *new(struct{}):
  389. default:
  390. }
  391. }
  392. }
  393. // upgradeDownloader makes periodic attemps to complete a client upgrade
  394. // download. DownloadUpgrade() is resumable, so each attempt has potential for
  395. // getting closer to completion, even in conditions where the download or
  396. // tunnel is repeatedly interrupted.
  397. // An upgrade download is triggered by either a handshake response indicating
  398. // that a new version is available; or after failing to connect, in which case
  399. // it's useful to check, out-of-band, for an upgrade with new circumvention
  400. // capabilities.
  401. // Once the download operation completes successfully, the downloader exits
  402. // and is not run again: either there is not a newer version, or the upgrade
  403. // has been downloaded and is ready to be applied.
  404. // We're assuming that the upgrade will be applied and the entire system
  405. // restarted before another upgrade is to be downloaded.
  406. //
  407. // TODO: refactor upgrade downloader and remote server list fetcher to use
  408. // common code (including the resumable download routines).
  409. //
  410. func (controller *Controller) upgradeDownloader() {
  411. defer controller.runWaitGroup.Done()
  412. var lastDownloadTime monotime.Time
  413. downloadLoop:
  414. for {
  415. // Wait for a signal before downloading
  416. var handshakeVersion string
  417. select {
  418. case handshakeVersion = <-controller.signalDownloadUpgrade:
  419. case <-controller.shutdownBroadcast:
  420. break downloadLoop
  421. }
  422. // Unless handshake is explicitly advertizing a new version, skip
  423. // checking entirely when a recent download was successful.
  424. if handshakeVersion == "" &&
  425. lastDownloadTime != 0 &&
  426. lastDownloadTime.Add(DOWNLOAD_UPGRADE_STALE_PERIOD).After(monotime.Now()) {
  427. continue
  428. }
  429. retryLoop:
  430. for attempt := 0; ; attempt++ {
  431. // Don't attempt to download while there is no network connectivity,
  432. // to avoid alert notice noise.
  433. if !WaitForNetworkConnectivity(
  434. controller.config.NetworkConnectivityChecker,
  435. controller.shutdownBroadcast) {
  436. break downloadLoop
  437. }
  438. // Pick any active tunnel and make the next download attempt. If there's
  439. // no active tunnel, the untunneledDialConfig will be used.
  440. tunnel := controller.getNextActiveTunnel()
  441. err := DownloadUpgrade(
  442. controller.config,
  443. attempt,
  444. handshakeVersion,
  445. tunnel,
  446. controller.untunneledDialConfig)
  447. if err == nil {
  448. lastDownloadTime = monotime.Now()
  449. break retryLoop
  450. }
  451. NoticeAlert("failed to download upgrade: %s", err)
  452. timeout := time.After(
  453. time.Duration(*controller.config.DownloadUpgradeRetryPeriodSeconds) * time.Second)
  454. select {
  455. case <-timeout:
  456. case <-controller.shutdownBroadcast:
  457. break downloadLoop
  458. }
  459. }
  460. }
  461. NoticeInfo("exiting upgrade downloader")
  462. }
  463. // runTunnels is the controller tunnel management main loop. It starts and stops
  464. // establishing tunnels based on the target tunnel pool size and the current size
  465. // of the pool. Tunnels are established asynchronously using worker goroutines.
  466. //
  467. // When there are no server entries for the target region/protocol, the
  468. // establishCandidateGenerator will yield no candidates and wait before
  469. // trying again. In the meantime, a remote server entry fetch may supply
  470. // valid candidates.
  471. //
  472. // When a tunnel is established, it's added to the active pool. The tunnel's
  473. // operateTunnel goroutine monitors the tunnel.
  474. //
  475. // When a tunnel fails, it's removed from the pool and the establish process is
  476. // restarted to fill the pool.
  477. func (controller *Controller) runTunnels() {
  478. defer controller.runWaitGroup.Done()
  479. var clientVerificationPayload string
  480. // Start running
  481. controller.startEstablishing()
  482. loop:
  483. for {
  484. select {
  485. case failedTunnel := <-controller.failedTunnels:
  486. NoticeAlert("tunnel failed: %s", failedTunnel.serverEntry.IpAddress)
  487. controller.terminateTunnel(failedTunnel)
  488. // Note: we make this extra check to ensure the shutdown signal takes priority
  489. // and that we do not start establishing. Critically, startEstablishing() calls
  490. // establishPendingConns.Reset() which clears the closed flag in
  491. // establishPendingConns; this causes the pendingConns.Add() within
  492. // interruptibleTCPDial to succeed instead of aborting, and the result
  493. // is that it's possible for establish goroutines to run all the way through
  494. // NewServerContext before being discarded... delaying shutdown.
  495. select {
  496. case <-controller.shutdownBroadcast:
  497. break loop
  498. default:
  499. }
  500. controller.classifyImpairedProtocol(failedTunnel)
  501. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing
  502. // and access isEstablishing.
  503. if !controller.isEstablishing {
  504. controller.startEstablishing()
  505. }
  506. case establishedTunnel := <-controller.establishedTunnels:
  507. if controller.isImpairedProtocol(establishedTunnel.protocol) {
  508. // Protocol was classified as impaired while this tunnel established.
  509. // This is most likely to occur with TunnelPoolSize > 0. We log the
  510. // event but take no action. Discarding the tunnel would break the
  511. // impaired logic unless we did that (a) only if there are other
  512. // unimpaired protocols; (b) only during the first interation of the
  513. // ESTABLISH_TUNNEL_WORK_TIME loop. By not discarding here, a true
  514. // impaired protocol may require an extra reconnect.
  515. NoticeAlert("established tunnel with impaired protocol: %s", establishedTunnel.protocol)
  516. }
  517. tunnelCount, registered := controller.registerTunnel(establishedTunnel)
  518. if !registered {
  519. // Already fully established, so discard.
  520. controller.discardTunnel(establishedTunnel)
  521. break
  522. }
  523. NoticeActiveTunnel(establishedTunnel.serverEntry.IpAddress, establishedTunnel.protocol)
  524. if tunnelCount == 1 {
  525. // The split tunnel classifier is started once the first tunnel is
  526. // established. This first tunnel is passed in to be used to make
  527. // the routes data request.
  528. // A long-running controller may run while the host device is present
  529. // in different regions. In this case, we want the split tunnel logic
  530. // to switch to routes for new regions and not classify traffic based
  531. // on routes installed for older regions.
  532. // We assume that when regions change, the host network will also
  533. // change, and so all tunnels will fail and be re-established. Under
  534. // that assumption, the classifier will be re-Start()-ed here when
  535. // the region has changed.
  536. controller.splitTunnelClassifier.Start(establishedTunnel)
  537. // Signal a connected request on each 1st tunnel establishment. For
  538. // multi-tunnels, the session is connected as long as at least one
  539. // tunnel is established.
  540. controller.startOrSignalConnectedReporter()
  541. // If the handshake indicated that a new client version is available,
  542. // trigger an upgrade download.
  543. // Note: serverContext is nil when DisableApi is set
  544. if establishedTunnel.serverContext != nil &&
  545. establishedTunnel.serverContext.clientUpgradeVersion != "" {
  546. handshakeVersion := establishedTunnel.serverContext.clientUpgradeVersion
  547. select {
  548. case controller.signalDownloadUpgrade <- handshakeVersion:
  549. default:
  550. }
  551. }
  552. }
  553. // TODO: design issue -- might not be enough server entries with region/caps to ever fill tunnel slots;
  554. // possible solution is establish target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  555. if controller.isFullyEstablished() {
  556. controller.stopEstablishing()
  557. }
  558. case clientVerificationPayload = <-controller.newClientVerificationPayload:
  559. controller.setClientVerificationPayloadForActiveTunnels(clientVerificationPayload)
  560. case <-controller.shutdownBroadcast:
  561. break loop
  562. }
  563. }
  564. // Stop running
  565. controller.stopEstablishing()
  566. controller.terminateAllTunnels()
  567. // Drain tunnel channels
  568. close(controller.establishedTunnels)
  569. for tunnel := range controller.establishedTunnels {
  570. controller.discardTunnel(tunnel)
  571. }
  572. close(controller.failedTunnels)
  573. for tunnel := range controller.failedTunnels {
  574. controller.discardTunnel(tunnel)
  575. }
  576. NoticeInfo("exiting run tunnels")
  577. }
  578. // classifyImpairedProtocol tracks "impaired" protocol classifications for failed
  579. // tunnels. A protocol is classified as impaired if a tunnel using that protocol
  580. // fails, repeatedly, shortly after the start of the connection. During tunnel
  581. // establishment, impaired protocols are briefly skipped.
  582. //
  583. // One purpose of this measure is to defend against an attack where the adversary,
  584. // for example, tags an OSSH TCP connection as an "unidentified" protocol; allows
  585. // it to connect; but then kills the underlying TCP connection after a short time.
  586. // Since OSSH has less latency than other protocols that may bypass an "unidentified"
  587. // filter, these other protocols might never be selected for use.
  588. //
  589. // Concurrency note: only the runTunnels() goroutine may call classifyImpairedProtocol
  590. func (controller *Controller) classifyImpairedProtocol(failedTunnel *Tunnel) {
  591. if failedTunnel.establishedTime.Add(IMPAIRED_PROTOCOL_CLASSIFICATION_DURATION).After(monotime.Now()) {
  592. controller.impairedProtocolClassification[failedTunnel.protocol] += 1
  593. } else {
  594. controller.impairedProtocolClassification[failedTunnel.protocol] = 0
  595. }
  596. // Reset classification once all known protocols are classified as impaired, as
  597. // there is now no way to proceed with only unimpaired protocols. The network
  598. // situation (or attack) resulting in classification may not be protocol-specific.
  599. //
  600. // Note: with controller.config.TunnelProtocol set, this will always reset once
  601. // that protocol has reached IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD.
  602. if CountNonImpairedProtocols(
  603. controller.config.EgressRegion,
  604. controller.config.TunnelProtocol,
  605. controller.getImpairedProtocols()) == 0 {
  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. // The edited serverEntry is temporary copy which is not
  949. // stored or reused.
  950. if i == 0 {
  951. serverEntry.DisableImpairedProtocols(impairedProtocols)
  952. if len(serverEntry.GetSupportedProtocols()) == 0 {
  953. // Skip this server entry, as it has no supported
  954. // protocols after disabling the impaired ones
  955. // TODO: modify ServerEntryIterator to skip these?
  956. continue
  957. }
  958. }
  959. // adjustedEstablishStartTime is establishStartTime shifted
  960. // to exclude time spent waiting for network connectivity.
  961. candidate := &candidateServerEntry{
  962. serverEntry: serverEntry,
  963. isServerAffinityCandidate: isServerAffinityCandidate,
  964. adjustedEstablishStartTime: establishStartTime.Add(networkWaitDuration),
  965. }
  966. // Note: there must be only one server affinity candidate, as it
  967. // closes the serverAffinityDoneBroadcast channel.
  968. isServerAffinityCandidate = false
  969. // TODO: here we could generate multiple candidates from the
  970. // server entry when there are many MeekFrontingAddresses.
  971. select {
  972. case controller.candidateServerEntries <- candidate:
  973. case <-controller.stopEstablishingBroadcast:
  974. break loop
  975. case <-controller.shutdownBroadcast:
  976. break loop
  977. }
  978. if startTime.Add(ESTABLISH_TUNNEL_WORK_TIME).Before(monotime.Now()) {
  979. // Start over, after a brief pause, with a new shuffle of the server
  980. // entries, and potentially some newly fetched server entries.
  981. break
  982. }
  983. }
  984. // Free up resources now, but don't reset until after the pause.
  985. iterator.Close()
  986. // Trigger a common remote server list fetch, since we may have failed
  987. // to connect with all known servers. Don't block sending signal, since
  988. // this signal may have already been sent.
  989. // Don't wait for fetch remote to succeed, since it may fail and
  990. // enter a retry loop and we're better off trying more known servers.
  991. // TODO: synchronize the fetch response, so it can be incorporated
  992. // into the server entry iterator as soon as available.
  993. select {
  994. case controller.signalFetchCommonRemoteServerList <- *new(struct{}):
  995. default:
  996. }
  997. // Trigger an OSL fetch in parallel. Both fetches are run in parallel
  998. // so that if one out of the common RLS and OSL set is large, it doesn't
  999. // doesn't entirely block fetching the other.
  1000. select {
  1001. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  1002. default:
  1003. }
  1004. // Trigger an out-of-band upgrade availability check and download.
  1005. // Since we may have failed to connect, we may benefit from upgrading
  1006. // to a new client version with new circumvention capabilities.
  1007. select {
  1008. case controller.signalDownloadUpgrade <- "":
  1009. default:
  1010. }
  1011. // After a complete iteration of candidate servers, pause before iterating again.
  1012. // This helps avoid some busy wait loop conditions, and also allows some time for
  1013. // network conditions to change. Also allows for fetch remote to complete,
  1014. // in typical conditions (it isn't strictly necessary to wait for this, there will
  1015. // be more rounds if required).
  1016. timeout := time.After(
  1017. time.Duration(*controller.config.EstablishTunnelPausePeriodSeconds) * time.Second)
  1018. select {
  1019. case <-timeout:
  1020. // Retry iterating
  1021. case <-controller.stopEstablishingBroadcast:
  1022. break loop
  1023. case <-controller.shutdownBroadcast:
  1024. break loop
  1025. }
  1026. iterator.Reset()
  1027. }
  1028. NoticeInfo("stopped candidate generator")
  1029. }
  1030. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  1031. // a connection to the tunnel server, and delivers the established tunnel to a channel.
  1032. func (controller *Controller) establishTunnelWorker() {
  1033. defer controller.establishWaitGroup.Done()
  1034. loop:
  1035. for candidateServerEntry := range controller.candidateServerEntries {
  1036. // Note: don't receive from candidateServerEntries and stopEstablishingBroadcast
  1037. // in the same select, since we want to prioritize receiving the stop signal
  1038. if controller.isStopEstablishingBroadcast() {
  1039. break loop
  1040. }
  1041. // There may already be a tunnel to this candidate. If so, skip it.
  1042. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  1043. continue
  1044. }
  1045. tunnel, err := EstablishTunnel(
  1046. controller.config,
  1047. controller.untunneledDialConfig,
  1048. controller.sessionId,
  1049. controller.establishPendingConns,
  1050. candidateServerEntry.serverEntry,
  1051. candidateServerEntry.adjustedEstablishStartTime,
  1052. controller) // TunnelOwner
  1053. if err != nil {
  1054. // Unblock other candidates immediately when
  1055. // server affinity candidate fails.
  1056. if candidateServerEntry.isServerAffinityCandidate {
  1057. close(controller.serverAffinityDoneBroadcast)
  1058. }
  1059. // Before emitting error, check if establish interrupted, in which
  1060. // case the error is noise.
  1061. if controller.isStopEstablishingBroadcast() {
  1062. break loop
  1063. }
  1064. NoticeInfo("failed to connect to %s: %s", candidateServerEntry.serverEntry.IpAddress, err)
  1065. continue
  1066. }
  1067. // Block for server affinity grace period before delivering.
  1068. if !candidateServerEntry.isServerAffinityCandidate {
  1069. timer := time.NewTimer(ESTABLISH_TUNNEL_SERVER_AFFINITY_GRACE_PERIOD)
  1070. select {
  1071. case <-timer.C:
  1072. case <-controller.serverAffinityDoneBroadcast:
  1073. case <-controller.stopEstablishingBroadcast:
  1074. }
  1075. }
  1076. // Deliver established tunnel.
  1077. // Don't block. Assumes the receiver has a buffer large enough for
  1078. // the number of desired tunnels. If there's no room, the tunnel must
  1079. // not be required so it's discarded.
  1080. select {
  1081. case controller.establishedTunnels <- tunnel:
  1082. default:
  1083. controller.discardTunnel(tunnel)
  1084. }
  1085. // Unblock other candidates only after delivering when
  1086. // server affinity candidate succeeds.
  1087. if candidateServerEntry.isServerAffinityCandidate {
  1088. close(controller.serverAffinityDoneBroadcast)
  1089. }
  1090. }
  1091. NoticeInfo("stopped establish worker")
  1092. }
  1093. func (controller *Controller) isStopEstablishingBroadcast() bool {
  1094. select {
  1095. case <-controller.stopEstablishingBroadcast:
  1096. return true
  1097. default:
  1098. }
  1099. return false
  1100. }