controller.go 45 KB

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