controller.go 43 KB

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