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 *ServerEntry
  68. isServerAffinityCandidate bool
  69. adjustedEstablishStartTime monotime.Time
  70. }
  71. // NewController initializes a new controller.
  72. func NewController(config *Config) (controller *Controller, err error) {
  73. // Needed by regen, at least
  74. rand.Seed(int64(time.Now().Nanosecond()))
  75. // Supply a default HostNameTransformer
  76. if config.HostNameTransformer == nil {
  77. config.HostNameTransformer = &IdentityHostNameTransformer{}
  78. }
  79. // Generate a session ID for the Psiphon server API. This session ID is
  80. // used across all tunnels established by the controller.
  81. sessionId, err := MakeSessionId()
  82. if err != nil {
  83. return nil, common.ContextError(err)
  84. }
  85. NoticeSessionId(sessionId)
  86. // untunneledPendingConns may be used to interrupt the fetch remote server list
  87. // request and other untunneled connection establishments. BindToDevice may be
  88. // used to exclude these requests and connection from VPN routing.
  89. // TODO: fetch remote server list and untunneled upgrade download should remove
  90. // their completed conns from untunneledPendingConns.
  91. untunneledPendingConns := new(common.Conns)
  92. untunneledDialConfig := &DialConfig{
  93. UpstreamProxyUrl: config.UpstreamProxyUrl,
  94. UpstreamProxyCustomHeaders: config.UpstreamProxyCustomHeaders,
  95. PendingConns: untunneledPendingConns,
  96. DeviceBinder: config.DeviceBinder,
  97. DnsServerGetter: config.DnsServerGetter,
  98. UseIndistinguishableTLS: config.UseIndistinguishableTLS,
  99. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  100. DeviceRegion: config.DeviceRegion,
  101. }
  102. controller = &Controller{
  103. config: config,
  104. sessionId: sessionId,
  105. // componentFailureSignal receives a signal from a component (including socks and
  106. // http local proxies) if they unexpectedly fail. Senders should not block.
  107. // Buffer allows at least one stop signal to be sent before there is a receiver.
  108. componentFailureSignal: make(chan struct{}, 1),
  109. shutdownBroadcast: make(chan struct{}),
  110. runWaitGroup: new(sync.WaitGroup),
  111. // establishedTunnels and failedTunnels buffer sizes are large enough to
  112. // receive full pools of tunnels without blocking. Senders should not block.
  113. establishedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  114. failedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  115. tunnels: make([]*Tunnel, 0),
  116. establishedOnce: false,
  117. startedConnectedReporter: false,
  118. isEstablishing: false,
  119. establishPendingConns: new(common.Conns),
  120. untunneledPendingConns: untunneledPendingConns,
  121. untunneledDialConfig: untunneledDialConfig,
  122. impairedProtocolClassification: make(map[string]int),
  123. // TODO: Add a buffer of 1 so we don't miss a signal while receiver is
  124. // starting? Trade-off is potential back-to-back fetch remotes. As-is,
  125. // establish will eventually signal another fetch remote.
  126. signalFetchCommonRemoteServerList: make(chan struct{}),
  127. signalFetchObfuscatedServerLists: make(chan struct{}),
  128. signalDownloadUpgrade: make(chan string),
  129. signalReportConnected: make(chan struct{}),
  130. // Buffer allows SetClientVerificationPayloadForActiveTunnels to submit one
  131. // new payload without blocking or dropping it.
  132. newClientVerificationPayload: make(chan string, 1),
  133. }
  134. controller.splitTunnelClassifier = NewSplitTunnelClassifier(config, controller)
  135. return controller, nil
  136. }
  137. // Run executes the controller. It launches components and then monitors
  138. // for a shutdown signal; after receiving the signal it shuts down the
  139. // controller.
  140. // The components include:
  141. // - the periodic remote server list fetcher
  142. // - the connected reporter
  143. // - the tunnel manager
  144. // - a local SOCKS proxy that port forwards through the pool of tunnels
  145. // - a local HTTP proxy that port forwards through the pool of tunnels
  146. func (controller *Controller) Run(shutdownBroadcast <-chan struct{}) {
  147. ReportAvailableRegions()
  148. // Start components
  149. listenIP, err := GetInterfaceIPAddress(controller.config.ListenInterface)
  150. if err != nil {
  151. NoticeError("error getting listener IP: %s", err)
  152. return
  153. }
  154. socksProxy, err := NewSocksProxy(controller.config, controller, listenIP)
  155. if err != nil {
  156. NoticeAlert("error initializing local SOCKS proxy: %s", err)
  157. return
  158. }
  159. defer socksProxy.Close()
  160. httpProxy, err := NewHttpProxy(
  161. controller.config, controller.untunneledDialConfig, controller, listenIP)
  162. if err != nil {
  163. NoticeAlert("error initializing local HTTP proxy: %s", err)
  164. return
  165. }
  166. defer httpProxy.Close()
  167. if !controller.config.DisableRemoteServerListFetcher {
  168. retryPeriod := time.Duration(
  169. *controller.config.FetchRemoteServerListRetryPeriodSeconds) * time.Second
  170. 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(serverEntry *ServerEntry) bool {
  767. controller.tunnelMutex.Lock()
  768. defer controller.tunnelMutex.Unlock()
  769. for _, activeTunnel := range controller.tunnels {
  770. if activeTunnel.serverEntry.IpAddress == serverEntry.IpAddress {
  771. return true
  772. }
  773. }
  774. return false
  775. }
  776. // setClientVerificationPayloadForActiveTunnels triggers the client verification
  777. // request for all active tunnels.
  778. func (controller *Controller) setClientVerificationPayloadForActiveTunnels(
  779. clientVerificationPayload string) {
  780. controller.tunnelMutex.Lock()
  781. defer controller.tunnelMutex.Unlock()
  782. for _, activeTunnel := range controller.tunnels {
  783. activeTunnel.SetClientVerificationPayload(clientVerificationPayload)
  784. }
  785. }
  786. // Dial selects an active tunnel and establishes a port forward
  787. // connection through the selected tunnel. Failure to connect is considered
  788. // a port foward failure, for the purpose of monitoring tunnel health.
  789. func (controller *Controller) Dial(
  790. remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error) {
  791. tunnel := controller.getNextActiveTunnel()
  792. if tunnel == nil {
  793. return nil, common.ContextError(errors.New("no active tunnels"))
  794. }
  795. // Perform split tunnel classification when feature is enabled, and if the remote
  796. // address is classified as untunneled, dial directly.
  797. if !alwaysTunnel && controller.config.SplitTunnelDnsServer != "" {
  798. host, _, err := net.SplitHostPort(remoteAddr)
  799. if err != nil {
  800. return nil, common.ContextError(err)
  801. }
  802. // Note: a possible optimization, when split tunnel is active and IsUntunneled performs
  803. // a DNS resolution in order to make its classification, is to reuse that IP address in
  804. // the following Dials so they do not need to make their own resolutions. However, the
  805. // way this is currently implemented ensures that, e.g., DNS geo load balancing occurs
  806. // relative to the outbound network.
  807. if controller.splitTunnelClassifier.IsUntunneled(host) {
  808. // TODO: track downstreamConn and close it when the DialTCP conn closes, as with tunnel.Dial conns?
  809. return DialTCP(remoteAddr, controller.untunneledDialConfig)
  810. }
  811. }
  812. tunneledConn, err := tunnel.Dial(remoteAddr, alwaysTunnel, downstreamConn)
  813. if err != nil {
  814. return nil, common.ContextError(err)
  815. }
  816. return tunneledConn, nil
  817. }
  818. // startEstablishing creates a pool of worker goroutines which will
  819. // attempt to establish tunnels to candidate servers. The candidates
  820. // are generated by another goroutine.
  821. func (controller *Controller) startEstablishing() {
  822. if controller.isEstablishing {
  823. return
  824. }
  825. NoticeInfo("start establishing")
  826. controller.isEstablishing = true
  827. controller.establishWaitGroup = new(sync.WaitGroup)
  828. controller.stopEstablishingBroadcast = make(chan struct{})
  829. controller.candidateServerEntries = make(chan *candidateServerEntry)
  830. controller.establishPendingConns.Reset()
  831. // The server affinity mechanism attempts to favor the previously
  832. // used server when reconnecting. This is beneficial for user
  833. // applications which expect consistency in user IP address (for
  834. // example, a web site which prompts for additional user
  835. // authentication when the IP address changes).
  836. //
  837. // Only the very first server, as determined by
  838. // datastore.PromoteServerEntry(), is the server affinity candidate.
  839. // Concurrent connections attempts to many servers are launched
  840. // without delay, in case the affinity server connection fails.
  841. // While the affinity server connection is outstanding, when any
  842. // other connection is established, there is a short grace period
  843. // delay before delivering the established tunnel; this allows some
  844. // time for the affinity server connection to succeed first.
  845. // When the affinity server connection fails, any other established
  846. // tunnel is registered without delay.
  847. //
  848. // Note: the establishTunnelWorker that receives the affinity
  849. // candidate is solely resonsible for closing
  850. // controller.serverAffinityDoneBroadcast.
  851. //
  852. // Note: if config.EgressRegion or config.TunnelProtocol has changed
  853. // since the top server was promoted, the first server may not actually
  854. // be the last connected server.
  855. // TODO: should not favor the first server in this case
  856. controller.serverAffinityDoneBroadcast = make(chan struct{})
  857. for i := 0; i < controller.config.ConnectionWorkerPoolSize; i++ {
  858. controller.establishWaitGroup.Add(1)
  859. go controller.establishTunnelWorker()
  860. }
  861. controller.establishWaitGroup.Add(1)
  862. go controller.establishCandidateGenerator(
  863. controller.getImpairedProtocols())
  864. }
  865. // stopEstablishing signals the establish goroutines to stop and waits
  866. // for the group to halt. pendingConns is used to interrupt any worker
  867. // blocked on a socket connect.
  868. func (controller *Controller) stopEstablishing() {
  869. if !controller.isEstablishing {
  870. return
  871. }
  872. NoticeInfo("stop establishing")
  873. close(controller.stopEstablishingBroadcast)
  874. // Note: interruptibleTCPClose doesn't really interrupt socket connects
  875. // and may leave goroutines running for a time after the Wait call.
  876. controller.establishPendingConns.CloseAll()
  877. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  878. // (as it may be sending to that channel).
  879. controller.establishWaitGroup.Wait()
  880. controller.isEstablishing = false
  881. controller.establishWaitGroup = nil
  882. controller.stopEstablishingBroadcast = nil
  883. controller.candidateServerEntries = nil
  884. controller.serverAffinityDoneBroadcast = nil
  885. }
  886. // establishCandidateGenerator populates the candidate queue with server entries
  887. // from the data store. Server entries are iterated in rank order, so that promoted
  888. // servers with higher rank are priority candidates.
  889. func (controller *Controller) establishCandidateGenerator(impairedProtocols []string) {
  890. defer controller.establishWaitGroup.Done()
  891. defer close(controller.candidateServerEntries)
  892. // establishStartTime is used to calculate and report the
  893. // client's tunnel establishment duration.
  894. //
  895. // networkWaitDuration is the elapsed time spent waiting
  896. // for network connectivity. This duration will be excluded
  897. // from reported tunnel establishment duration.
  898. establishStartTime := monotime.Now()
  899. var networkWaitDuration time.Duration
  900. iterator, err := NewServerEntryIterator(controller.config)
  901. if err != nil {
  902. NoticeAlert("failed to iterate over candidates: %s", err)
  903. controller.SignalComponentFailure()
  904. return
  905. }
  906. defer iterator.Close()
  907. isServerAffinityCandidate := true
  908. // TODO: reconcile server affinity scheme with multi-tunnel mode
  909. if controller.config.TunnelPoolSize > 1 {
  910. isServerAffinityCandidate = false
  911. close(controller.serverAffinityDoneBroadcast)
  912. }
  913. loop:
  914. // Repeat until stopped
  915. for i := 0; ; i++ {
  916. networkWaitStartTime := monotime.Now()
  917. if !WaitForNetworkConnectivity(
  918. controller.config.NetworkConnectivityChecker,
  919. controller.stopEstablishingBroadcast,
  920. controller.shutdownBroadcast) {
  921. break loop
  922. }
  923. networkWaitDuration += monotime.Since(networkWaitStartTime)
  924. // Send each iterator server entry to the establish workers
  925. startTime := monotime.Now()
  926. for {
  927. serverEntry, err := iterator.Next()
  928. if err != nil {
  929. NoticeAlert("failed to get next candidate: %s", err)
  930. controller.SignalComponentFailure()
  931. break loop
  932. }
  933. if serverEntry == nil {
  934. // Completed this iteration
  935. break
  936. }
  937. if controller.config.TargetApiProtocol == protocol.PSIPHON_SSH_API_PROTOCOL &&
  938. !serverEntry.SupportsSSHAPIRequests() {
  939. continue
  940. }
  941. // Disable impaired protocols. This is only done for the
  942. // first iteration of the ESTABLISH_TUNNEL_WORK_TIME
  943. // loop since (a) one iteration should be sufficient to
  944. // evade the attack; (b) there's a good chance of false
  945. // positives (such as short tunnel durations due to network
  946. // hopping on a mobile device).
  947. // Impaired protocols logic is not applied when
  948. // config.TunnelProtocol is specified.
  949. // The edited serverEntry is temporary copy which is not
  950. // stored or reused.
  951. if i == 0 && controller.config.TunnelProtocol == "" {
  952. serverEntry.DisableImpairedProtocols(impairedProtocols)
  953. if len(serverEntry.GetSupportedProtocols()) == 0 {
  954. // Skip this server entry, as it has no supported
  955. // protocols after disabling the impaired ones
  956. // TODO: modify ServerEntryIterator to skip these?
  957. continue
  958. }
  959. }
  960. // adjustedEstablishStartTime is establishStartTime shifted
  961. // to exclude time spent waiting for network connectivity.
  962. candidate := &candidateServerEntry{
  963. serverEntry: serverEntry,
  964. isServerAffinityCandidate: isServerAffinityCandidate,
  965. adjustedEstablishStartTime: establishStartTime.Add(networkWaitDuration),
  966. }
  967. // Note: there must be only one server affinity candidate, as it
  968. // closes the serverAffinityDoneBroadcast channel.
  969. isServerAffinityCandidate = false
  970. // TODO: here we could generate multiple candidates from the
  971. // server entry when there are many MeekFrontingAddresses.
  972. select {
  973. case controller.candidateServerEntries <- candidate:
  974. case <-controller.stopEstablishingBroadcast:
  975. break loop
  976. case <-controller.shutdownBroadcast:
  977. break loop
  978. }
  979. if startTime.Add(ESTABLISH_TUNNEL_WORK_TIME).Before(monotime.Now()) {
  980. // Start over, after a brief pause, with a new shuffle of the server
  981. // entries, and potentially some newly fetched server entries.
  982. break
  983. }
  984. }
  985. // Free up resources now, but don't reset until after the pause.
  986. iterator.Close()
  987. // Trigger a common remote server list fetch, since we may have failed
  988. // to connect with all known servers. Don't block sending signal, since
  989. // this signal may have already been sent.
  990. // Don't wait for fetch remote to succeed, since it may fail and
  991. // enter a retry loop and we're better off trying more known servers.
  992. // TODO: synchronize the fetch response, so it can be incorporated
  993. // into the server entry iterator as soon as available.
  994. select {
  995. case controller.signalFetchCommonRemoteServerList <- *new(struct{}):
  996. default:
  997. }
  998. // Trigger an OSL fetch in parallel. Both fetches are run in parallel
  999. // so that if one out of the common RLS and OSL set is large, it doesn't
  1000. // doesn't entirely block fetching the other.
  1001. select {
  1002. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  1003. default:
  1004. }
  1005. // Trigger an out-of-band upgrade availability check and download.
  1006. // Since we may have failed to connect, we may benefit from upgrading
  1007. // to a new client version with new circumvention capabilities.
  1008. select {
  1009. case controller.signalDownloadUpgrade <- "":
  1010. default:
  1011. }
  1012. // After a complete iteration of candidate servers, pause before iterating again.
  1013. // This helps avoid some busy wait loop conditions, and also allows some time for
  1014. // network conditions to change. Also allows for fetch remote to complete,
  1015. // in typical conditions (it isn't strictly necessary to wait for this, there will
  1016. // be more rounds if required).
  1017. timeout := time.After(
  1018. time.Duration(*controller.config.EstablishTunnelPausePeriodSeconds) * time.Second)
  1019. select {
  1020. case <-timeout:
  1021. // Retry iterating
  1022. case <-controller.stopEstablishingBroadcast:
  1023. break loop
  1024. case <-controller.shutdownBroadcast:
  1025. break loop
  1026. }
  1027. iterator.Reset()
  1028. }
  1029. NoticeInfo("stopped candidate generator")
  1030. }
  1031. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  1032. // a connection to the tunnel server, and delivers the established tunnel to a channel.
  1033. func (controller *Controller) establishTunnelWorker() {
  1034. defer controller.establishWaitGroup.Done()
  1035. loop:
  1036. for candidateServerEntry := range controller.candidateServerEntries {
  1037. // Note: don't receive from candidateServerEntries and stopEstablishingBroadcast
  1038. // in the same select, since we want to prioritize receiving the stop signal
  1039. if controller.isStopEstablishingBroadcast() {
  1040. break loop
  1041. }
  1042. // There may already be a tunnel to this candidate. If so, skip it.
  1043. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  1044. continue
  1045. }
  1046. tunnel, err := EstablishTunnel(
  1047. controller.config,
  1048. controller.untunneledDialConfig,
  1049. controller.sessionId,
  1050. controller.establishPendingConns,
  1051. candidateServerEntry.serverEntry,
  1052. candidateServerEntry.adjustedEstablishStartTime,
  1053. controller) // TunnelOwner
  1054. if err != nil {
  1055. // Unblock other candidates immediately when
  1056. // server affinity candidate fails.
  1057. if candidateServerEntry.isServerAffinityCandidate {
  1058. close(controller.serverAffinityDoneBroadcast)
  1059. }
  1060. // Before emitting error, check if establish interrupted, in which
  1061. // case the error is noise.
  1062. if controller.isStopEstablishingBroadcast() {
  1063. break loop
  1064. }
  1065. NoticeInfo("failed to connect to %s: %s", candidateServerEntry.serverEntry.IpAddress, err)
  1066. continue
  1067. }
  1068. // Block for server affinity grace period before delivering.
  1069. if !candidateServerEntry.isServerAffinityCandidate {
  1070. timer := time.NewTimer(ESTABLISH_TUNNEL_SERVER_AFFINITY_GRACE_PERIOD)
  1071. select {
  1072. case <-timer.C:
  1073. case <-controller.serverAffinityDoneBroadcast:
  1074. case <-controller.stopEstablishingBroadcast:
  1075. }
  1076. }
  1077. // Deliver established tunnel.
  1078. // Don't block. Assumes the receiver has a buffer large enough for
  1079. // the number of desired tunnels. If there's no room, the tunnel must
  1080. // not be required so it's discarded.
  1081. select {
  1082. case controller.establishedTunnels <- tunnel:
  1083. default:
  1084. controller.discardTunnel(tunnel)
  1085. }
  1086. // Unblock other candidates only after delivering when
  1087. // server affinity candidate succeeds.
  1088. if candidateServerEntry.isServerAffinityCandidate {
  1089. close(controller.serverAffinityDoneBroadcast)
  1090. }
  1091. }
  1092. NoticeInfo("stopped establish worker")
  1093. }
  1094. func (controller *Controller) isStopEstablishingBroadcast() bool {
  1095. select {
  1096. case <-controller.stopEstablishingBroadcast:
  1097. return true
  1098. default:
  1099. }
  1100. return false
  1101. }