controller.go 45 KB

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