controller.go 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  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. if clientVerificationPayload != "" {
  511. establishedTunnel.SetClientVerificationPayload(clientVerificationPayload)
  512. }
  513. NoticeActiveTunnel(establishedTunnel.serverEntry.IpAddress, establishedTunnel.protocol)
  514. if tunnelCount == 1 {
  515. // The split tunnel classifier is started once the first tunnel is
  516. // established. This first tunnel is passed in to be used to make
  517. // the routes data request.
  518. // A long-running controller may run while the host device is present
  519. // in different regions. In this case, we want the split tunnel logic
  520. // to switch to routes for new regions and not classify traffic based
  521. // on routes installed for older regions.
  522. // We assume that when regions change, the host network will also
  523. // change, and so all tunnels will fail and be re-established. Under
  524. // that assumption, the classifier will be re-Start()-ed here when
  525. // the region has changed.
  526. controller.splitTunnelClassifier.Start(establishedTunnel)
  527. // Signal a connected request on each 1st tunnel establishment. For
  528. // multi-tunnels, the session is connected as long as at least one
  529. // tunnel is established.
  530. controller.startOrSignalConnectedReporter()
  531. // If the handshake indicated that a new client version is available,
  532. // trigger an upgrade download.
  533. // Note: serverContext is nil when DisableApi is set
  534. if establishedTunnel.serverContext != nil &&
  535. establishedTunnel.serverContext.clientUpgradeVersion != "" {
  536. handshakeVersion := establishedTunnel.serverContext.clientUpgradeVersion
  537. select {
  538. case controller.signalDownloadUpgrade <- handshakeVersion:
  539. default:
  540. }
  541. }
  542. }
  543. // TODO: design issue -- might not be enough server entries with region/caps to ever fill tunnel slots;
  544. // possible solution is establish target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  545. if controller.isFullyEstablished() {
  546. controller.stopEstablishing()
  547. }
  548. case clientVerificationPayload = <-controller.newClientVerificationPayload:
  549. controller.setClientVerificationPayloadForActiveTunnels(clientVerificationPayload)
  550. case <-controller.shutdownBroadcast:
  551. break loop
  552. }
  553. }
  554. // Stop running
  555. controller.stopEstablishing()
  556. controller.terminateAllTunnels()
  557. // Drain tunnel channels
  558. close(controller.establishedTunnels)
  559. for tunnel := range controller.establishedTunnels {
  560. controller.discardTunnel(tunnel)
  561. }
  562. close(controller.failedTunnels)
  563. for tunnel := range controller.failedTunnels {
  564. controller.discardTunnel(tunnel)
  565. }
  566. NoticeInfo("exiting run tunnels")
  567. }
  568. // classifyImpairedProtocol tracks "impaired" protocol classifications for failed
  569. // tunnels. A protocol is classified as impaired if a tunnel using that protocol
  570. // fails, repeatedly, shortly after the start of the connection. During tunnel
  571. // establishment, impaired protocols are briefly skipped.
  572. //
  573. // One purpose of this measure is to defend against an attack where the adversary,
  574. // for example, tags an OSSH TCP connection as an "unidentified" protocol; allows
  575. // it to connect; but then kills the underlying TCP connection after a short time.
  576. // Since OSSH has less latency than other protocols that may bypass an "unidentified"
  577. // filter, these other protocols might never be selected for use.
  578. //
  579. // Concurrency note: only the runTunnels() goroutine may call classifyImpairedProtocol
  580. func (controller *Controller) classifyImpairedProtocol(failedTunnel *Tunnel) {
  581. if failedTunnel.startTime.Add(IMPAIRED_PROTOCOL_CLASSIFICATION_DURATION).After(time.Now()) {
  582. controller.impairedProtocolClassification[failedTunnel.protocol] += 1
  583. } else {
  584. controller.impairedProtocolClassification[failedTunnel.protocol] = 0
  585. }
  586. if len(controller.getImpairedProtocols()) == len(common.SupportedTunnelProtocols) {
  587. // Reset classification if all protocols are classified as impaired as
  588. // the network situation (or attack) may not be protocol-specific.
  589. // TODO: compare against count of distinct supported protocols for
  590. // current known server entries.
  591. controller.impairedProtocolClassification = make(map[string]int)
  592. }
  593. }
  594. // getImpairedProtocols returns a list of protocols that have sufficient
  595. // classifications to be considered impaired protocols.
  596. //
  597. // Concurrency note: only the runTunnels() goroutine may call getImpairedProtocols
  598. func (controller *Controller) getImpairedProtocols() []string {
  599. NoticeImpairedProtocolClassification(controller.impairedProtocolClassification)
  600. impairedProtocols := make([]string, 0)
  601. for protocol, count := range controller.impairedProtocolClassification {
  602. if count >= IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD {
  603. impairedProtocols = append(impairedProtocols, protocol)
  604. }
  605. }
  606. return impairedProtocols
  607. }
  608. // isImpairedProtocol checks if the specified protocol is classified as impaired.
  609. //
  610. // Concurrency note: only the runTunnels() goroutine may call isImpairedProtocol
  611. func (controller *Controller) isImpairedProtocol(protocol string) bool {
  612. count, ok := controller.impairedProtocolClassification[protocol]
  613. return ok && count >= IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD
  614. }
  615. // SignalTunnelFailure implements the TunnelOwner interface. This function
  616. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  617. // has failed. The Controller will signal runTunnels to create a new
  618. // tunnel and/or remove the tunnel from the list of active tunnels.
  619. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  620. // Don't block. Assumes the receiver has a buffer large enough for
  621. // the typical number of operated tunnels. In case there's no room,
  622. // terminate the tunnel (runTunnels won't get a signal in this case,
  623. // but the tunnel will be removed from the list of active tunnels).
  624. select {
  625. case controller.failedTunnels <- tunnel:
  626. default:
  627. controller.terminateTunnel(tunnel)
  628. }
  629. }
  630. // discardTunnel disposes of a successful connection that is no longer required.
  631. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  632. NoticeInfo("discard tunnel: %s", tunnel.serverEntry.IpAddress)
  633. // TODO: not calling PromoteServerEntry, since that would rank the
  634. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  635. // be promoted (since it connects), but with lower rank than all active
  636. // tunnels?
  637. tunnel.Close(true)
  638. }
  639. // registerTunnel adds the connected tunnel to the pool of active tunnels
  640. // which are candidates for port forwarding. Returns true if the pool has an
  641. // empty slot and false if the pool is full (caller should discard the tunnel).
  642. func (controller *Controller) registerTunnel(tunnel *Tunnel) (int, bool) {
  643. controller.tunnelMutex.Lock()
  644. defer controller.tunnelMutex.Unlock()
  645. if len(controller.tunnels) >= controller.config.TunnelPoolSize {
  646. return len(controller.tunnels), false
  647. }
  648. // Perform a final check just in case we've established
  649. // a duplicate connection.
  650. for _, activeTunnel := range controller.tunnels {
  651. if activeTunnel.serverEntry.IpAddress == tunnel.serverEntry.IpAddress {
  652. NoticeAlert("duplicate tunnel: %s", tunnel.serverEntry.IpAddress)
  653. return len(controller.tunnels), false
  654. }
  655. }
  656. controller.establishedOnce = true
  657. controller.tunnels = append(controller.tunnels, tunnel)
  658. NoticeTunnels(len(controller.tunnels))
  659. // Promote this successful tunnel to first rank so it's one
  660. // of the first candidates next time establish runs.
  661. // Connecting to a TargetServerEntry does not change the
  662. // ranking.
  663. if controller.config.TargetServerEntry == "" {
  664. PromoteServerEntry(tunnel.serverEntry.IpAddress)
  665. }
  666. return len(controller.tunnels), true
  667. }
  668. // hasEstablishedOnce indicates if at least one active tunnel has
  669. // been established up to this point. This is regardeless of how many
  670. // tunnels are presently active.
  671. func (controller *Controller) hasEstablishedOnce() bool {
  672. controller.tunnelMutex.Lock()
  673. defer controller.tunnelMutex.Unlock()
  674. return controller.establishedOnce
  675. }
  676. // isFullyEstablished indicates if the pool of active tunnels is full.
  677. func (controller *Controller) isFullyEstablished() bool {
  678. controller.tunnelMutex.Lock()
  679. defer controller.tunnelMutex.Unlock()
  680. return len(controller.tunnels) >= controller.config.TunnelPoolSize
  681. }
  682. // terminateTunnel removes a tunnel from the pool of active tunnels
  683. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  684. // is adjusted as required.
  685. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  686. controller.tunnelMutex.Lock()
  687. defer controller.tunnelMutex.Unlock()
  688. for index, activeTunnel := range controller.tunnels {
  689. if tunnel == activeTunnel {
  690. controller.tunnels = append(
  691. controller.tunnels[:index], controller.tunnels[index+1:]...)
  692. if controller.nextTunnel > index {
  693. controller.nextTunnel--
  694. }
  695. if controller.nextTunnel >= len(controller.tunnels) {
  696. controller.nextTunnel = 0
  697. }
  698. activeTunnel.Close(false)
  699. NoticeTunnels(len(controller.tunnels))
  700. break
  701. }
  702. }
  703. }
  704. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  705. // This is used when shutting down the controller.
  706. func (controller *Controller) terminateAllTunnels() {
  707. controller.tunnelMutex.Lock()
  708. defer controller.tunnelMutex.Unlock()
  709. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  710. // may take a few seconds to send a final status request. We only want
  711. // to wait as long as the single slowest tunnel.
  712. closeWaitGroup := new(sync.WaitGroup)
  713. closeWaitGroup.Add(len(controller.tunnels))
  714. for _, activeTunnel := range controller.tunnels {
  715. tunnel := activeTunnel
  716. go func() {
  717. defer closeWaitGroup.Done()
  718. tunnel.Close(false)
  719. }()
  720. }
  721. closeWaitGroup.Wait()
  722. controller.tunnels = make([]*Tunnel, 0)
  723. controller.nextTunnel = 0
  724. NoticeTunnels(len(controller.tunnels))
  725. }
  726. // getNextActiveTunnel returns the next tunnel from the pool of active
  727. // tunnels. Currently, tunnel selection order is simple round-robin.
  728. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  729. controller.tunnelMutex.Lock()
  730. defer controller.tunnelMutex.Unlock()
  731. for i := len(controller.tunnels); i > 0; i-- {
  732. tunnel = controller.tunnels[controller.nextTunnel]
  733. controller.nextTunnel =
  734. (controller.nextTunnel + 1) % len(controller.tunnels)
  735. return tunnel
  736. }
  737. return nil
  738. }
  739. // isActiveTunnelServerEntry is used to check if there's already
  740. // an existing tunnel to a candidate server.
  741. func (controller *Controller) isActiveTunnelServerEntry(serverEntry *ServerEntry) bool {
  742. controller.tunnelMutex.Lock()
  743. defer controller.tunnelMutex.Unlock()
  744. for _, activeTunnel := range controller.tunnels {
  745. if activeTunnel.serverEntry.IpAddress == serverEntry.IpAddress {
  746. return true
  747. }
  748. }
  749. return false
  750. }
  751. // setClientVerificationPayloadForActiveTunnels triggers the client verification
  752. // request for all active tunnels.
  753. func (controller *Controller) setClientVerificationPayloadForActiveTunnels(
  754. clientVerificationPayload string) {
  755. controller.tunnelMutex.Lock()
  756. defer controller.tunnelMutex.Unlock()
  757. for _, activeTunnel := range controller.tunnels {
  758. activeTunnel.SetClientVerificationPayload(clientVerificationPayload)
  759. }
  760. }
  761. // Dial selects an active tunnel and establishes a port forward
  762. // connection through the selected tunnel. Failure to connect is considered
  763. // a port foward failure, for the purpose of monitoring tunnel health.
  764. func (controller *Controller) Dial(
  765. remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error) {
  766. tunnel := controller.getNextActiveTunnel()
  767. if tunnel == nil {
  768. return nil, common.ContextError(errors.New("no active tunnels"))
  769. }
  770. // Perform split tunnel classification when feature is enabled, and if the remote
  771. // address is classified as untunneled, dial directly.
  772. if !alwaysTunnel && controller.config.SplitTunnelDnsServer != "" {
  773. host, _, err := net.SplitHostPort(remoteAddr)
  774. if err != nil {
  775. return nil, common.ContextError(err)
  776. }
  777. // Note: a possible optimization, when split tunnel is active and IsUntunneled performs
  778. // a DNS resolution in order to make its classification, is to reuse that IP address in
  779. // the following Dials so they do not need to make their own resolutions. However, the
  780. // way this is currently implemented ensures that, e.g., DNS geo load balancing occurs
  781. // relative to the outbound network.
  782. if controller.splitTunnelClassifier.IsUntunneled(host) {
  783. // TODO: track downstreamConn and close it when the DialTCP conn closes, as with tunnel.Dial conns?
  784. return DialTCP(remoteAddr, controller.untunneledDialConfig)
  785. }
  786. }
  787. tunneledConn, err := tunnel.Dial(remoteAddr, alwaysTunnel, downstreamConn)
  788. if err != nil {
  789. return nil, common.ContextError(err)
  790. }
  791. return tunneledConn, nil
  792. }
  793. // startEstablishing creates a pool of worker goroutines which will
  794. // attempt to establish tunnels to candidate servers. The candidates
  795. // are generated by another goroutine.
  796. func (controller *Controller) startEstablishing() {
  797. if controller.isEstablishing {
  798. return
  799. }
  800. NoticeInfo("start establishing")
  801. controller.isEstablishing = true
  802. controller.establishWaitGroup = new(sync.WaitGroup)
  803. controller.stopEstablishingBroadcast = make(chan struct{})
  804. controller.candidateServerEntries = make(chan *candidateServerEntry)
  805. controller.establishPendingConns.Reset()
  806. // The server affinity mechanism attempts to favor the previously
  807. // used server when reconnecting. This is beneficial for user
  808. // applications which expect consistency in user IP address (for
  809. // example, a web site which prompts for additional user
  810. // authentication when the IP address changes).
  811. //
  812. // Only the very first server, as determined by
  813. // datastore.PromoteServerEntry(), is the server affinity candidate.
  814. // Concurrent connections attempts to many servers are launched
  815. // without delay, in case the affinity server connection fails.
  816. // While the affinity server connection is outstanding, when any
  817. // other connection is established, there is a short grace period
  818. // delay before delivering the established tunnel; this allows some
  819. // time for the affinity server connection to succeed first.
  820. // When the affinity server connection fails, any other established
  821. // tunnel is registered without delay.
  822. //
  823. // Note: the establishTunnelWorker that receives the affinity
  824. // candidate is solely resonsible for closing
  825. // controller.serverAffinityDoneBroadcast.
  826. //
  827. // Note: if config.EgressRegion or config.TunnelProtocol has changed
  828. // since the top server was promoted, the first server may not actually
  829. // be the last connected server.
  830. // TODO: should not favor the first server in this case
  831. controller.serverAffinityDoneBroadcast = make(chan struct{})
  832. for i := 0; i < controller.config.ConnectionWorkerPoolSize; i++ {
  833. controller.establishWaitGroup.Add(1)
  834. go controller.establishTunnelWorker()
  835. }
  836. controller.establishWaitGroup.Add(1)
  837. go controller.establishCandidateGenerator(
  838. controller.getImpairedProtocols())
  839. }
  840. // stopEstablishing signals the establish goroutines to stop and waits
  841. // for the group to halt. pendingConns is used to interrupt any worker
  842. // blocked on a socket connect.
  843. func (controller *Controller) stopEstablishing() {
  844. if !controller.isEstablishing {
  845. return
  846. }
  847. NoticeInfo("stop establishing")
  848. close(controller.stopEstablishingBroadcast)
  849. // Note: interruptibleTCPClose doesn't really interrupt socket connects
  850. // and may leave goroutines running for a time after the Wait call.
  851. controller.establishPendingConns.CloseAll()
  852. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  853. // (as it may be sending to that channel).
  854. controller.establishWaitGroup.Wait()
  855. controller.isEstablishing = false
  856. controller.establishWaitGroup = nil
  857. controller.stopEstablishingBroadcast = nil
  858. controller.candidateServerEntries = nil
  859. controller.serverAffinityDoneBroadcast = nil
  860. }
  861. // establishCandidateGenerator populates the candidate queue with server entries
  862. // from the data store. Server entries are iterated in rank order, so that promoted
  863. // servers with higher rank are priority candidates.
  864. func (controller *Controller) establishCandidateGenerator(impairedProtocols []string) {
  865. defer controller.establishWaitGroup.Done()
  866. defer close(controller.candidateServerEntries)
  867. iterator, err := NewServerEntryIterator(controller.config)
  868. if err != nil {
  869. NoticeAlert("failed to iterate over candidates: %s", err)
  870. controller.SignalComponentFailure()
  871. return
  872. }
  873. defer iterator.Close()
  874. isServerAffinityCandidate := true
  875. // TODO: reconcile server affinity scheme with multi-tunnel mode
  876. if controller.config.TunnelPoolSize > 1 {
  877. isServerAffinityCandidate = false
  878. close(controller.serverAffinityDoneBroadcast)
  879. }
  880. loop:
  881. // Repeat until stopped
  882. for i := 0; ; i++ {
  883. if !WaitForNetworkConnectivity(
  884. controller.config.NetworkConnectivityChecker,
  885. controller.stopEstablishingBroadcast,
  886. controller.shutdownBroadcast) {
  887. break loop
  888. }
  889. // Send each iterator server entry to the establish workers
  890. startTime := time.Now()
  891. for {
  892. serverEntry, err := iterator.Next()
  893. if err != nil {
  894. NoticeAlert("failed to get next candidate: %s", err)
  895. controller.SignalComponentFailure()
  896. break loop
  897. }
  898. if serverEntry == nil {
  899. // Completed this iteration
  900. break
  901. }
  902. // Disable impaired protocols. This is only done for the
  903. // first iteration of the ESTABLISH_TUNNEL_WORK_TIME
  904. // loop since (a) one iteration should be sufficient to
  905. // evade the attack; (b) there's a good chance of false
  906. // positives (such as short tunnel durations due to network
  907. // hopping on a mobile device).
  908. // Impaired protocols logic is not applied when
  909. // config.TunnelProtocol is specified.
  910. // The edited serverEntry is temporary copy which is not
  911. // stored or reused.
  912. if i == 0 && controller.config.TunnelProtocol == "" {
  913. serverEntry.DisableImpairedProtocols(impairedProtocols)
  914. if len(serverEntry.GetSupportedProtocols()) == 0 {
  915. // Skip this server entry, as it has no supported
  916. // protocols after disabling the impaired ones
  917. // TODO: modify ServerEntryIterator to skip these?
  918. continue
  919. }
  920. }
  921. // Note: there must be only one server affinity candidate, as it
  922. // closes the serverAffinityDoneBroadcast channel.
  923. candidate := &candidateServerEntry{serverEntry, isServerAffinityCandidate}
  924. isServerAffinityCandidate = false
  925. // TODO: here we could generate multiple candidates from the
  926. // server entry when there are many MeekFrontingAddresses.
  927. select {
  928. case controller.candidateServerEntries <- candidate:
  929. case <-controller.stopEstablishingBroadcast:
  930. break loop
  931. case <-controller.shutdownBroadcast:
  932. break loop
  933. }
  934. if time.Now().After(startTime.Add(ESTABLISH_TUNNEL_WORK_TIME)) {
  935. // Start over, after a brief pause, with a new shuffle of the server
  936. // entries, and potentially some newly fetched server entries.
  937. break
  938. }
  939. }
  940. // Free up resources now, but don't reset until after the pause.
  941. iterator.Close()
  942. // Trigger a fetch remote server list, since we may have failed to
  943. // connect with all known servers. Don't block sending signal, since
  944. // this signal may have already been sent.
  945. // Don't wait for fetch remote to succeed, since it may fail and
  946. // enter a retry loop and we're better off trying more known servers.
  947. // TODO: synchronize the fetch response, so it can be incorporated
  948. // into the server entry iterator as soon as available.
  949. select {
  950. case controller.signalFetchRemoteServerList <- *new(struct{}):
  951. default:
  952. }
  953. // Trigger an out-of-band upgrade availability check and download.
  954. // Since we may have failed to connect, we may benefit from upgrading
  955. // to a new client version with new circumvention capabilities.
  956. select {
  957. case controller.signalDownloadUpgrade <- "":
  958. default:
  959. }
  960. // After a complete iteration of candidate servers, pause before iterating again.
  961. // This helps avoid some busy wait loop conditions, and also allows some time for
  962. // network conditions to change. Also allows for fetch remote to complete,
  963. // in typical conditions (it isn't strictly necessary to wait for this, there will
  964. // be more rounds if required).
  965. timeout := time.After(
  966. time.Duration(*controller.config.EstablishTunnelPausePeriodSeconds) * time.Second)
  967. select {
  968. case <-timeout:
  969. // Retry iterating
  970. case <-controller.stopEstablishingBroadcast:
  971. break loop
  972. case <-controller.shutdownBroadcast:
  973. break loop
  974. }
  975. iterator.Reset()
  976. }
  977. NoticeInfo("stopped candidate generator")
  978. }
  979. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  980. // a connection to the tunnel server, and delivers the established tunnel to a channel.
  981. func (controller *Controller) establishTunnelWorker() {
  982. defer controller.establishWaitGroup.Done()
  983. loop:
  984. for candidateServerEntry := range controller.candidateServerEntries {
  985. // Note: don't receive from candidateServerEntries and stopEstablishingBroadcast
  986. // in the same select, since we want to prioritize receiving the stop signal
  987. if controller.isStopEstablishingBroadcast() {
  988. break loop
  989. }
  990. // There may already be a tunnel to this candidate. If so, skip it.
  991. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  992. continue
  993. }
  994. tunnel, err := EstablishTunnel(
  995. controller.config,
  996. controller.untunneledDialConfig,
  997. controller.sessionId,
  998. controller.establishPendingConns,
  999. candidateServerEntry.serverEntry,
  1000. controller) // TunnelOwner
  1001. if err != nil {
  1002. // Unblock other candidates immediately when
  1003. // server affinity candidate fails.
  1004. if candidateServerEntry.isServerAffinityCandidate {
  1005. close(controller.serverAffinityDoneBroadcast)
  1006. }
  1007. // Before emitting error, check if establish interrupted, in which
  1008. // case the error is noise.
  1009. if controller.isStopEstablishingBroadcast() {
  1010. break loop
  1011. }
  1012. NoticeInfo("failed to connect to %s: %s", candidateServerEntry.serverEntry.IpAddress, err)
  1013. continue
  1014. }
  1015. // Block for server affinity grace period before delivering.
  1016. if !candidateServerEntry.isServerAffinityCandidate {
  1017. timer := time.NewTimer(ESTABLISH_TUNNEL_SERVER_AFFINITY_GRACE_PERIOD)
  1018. select {
  1019. case <-timer.C:
  1020. case <-controller.serverAffinityDoneBroadcast:
  1021. case <-controller.stopEstablishingBroadcast:
  1022. }
  1023. }
  1024. // Deliver established tunnel.
  1025. // Don't block. Assumes the receiver has a buffer large enough for
  1026. // the number of desired tunnels. If there's no room, the tunnel must
  1027. // not be required so it's discarded.
  1028. select {
  1029. case controller.establishedTunnels <- tunnel:
  1030. default:
  1031. controller.discardTunnel(tunnel)
  1032. }
  1033. // Unblock other candidates only after delivering when
  1034. // server affinity candidate succeeds.
  1035. if candidateServerEntry.isServerAffinityCandidate {
  1036. close(controller.serverAffinityDoneBroadcast)
  1037. }
  1038. }
  1039. NoticeInfo("stopped establish worker")
  1040. }
  1041. func (controller *Controller) isStopEstablishingBroadcast() bool {
  1042. select {
  1043. case <-controller.stopEstablishingBroadcast:
  1044. return true
  1045. default:
  1046. }
  1047. return false
  1048. }