controller.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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. "net"
  27. "sync"
  28. "time"
  29. )
  30. // Controller is a tunnel lifecycle coordinator. It manages lists of servers to
  31. // connect to; establishes and monitors tunnels; and runs local proxies which
  32. // route traffic through the tunnels.
  33. type Controller struct {
  34. config *Config
  35. sessionId string
  36. componentFailureSignal chan struct{}
  37. shutdownBroadcast chan struct{}
  38. runWaitGroup *sync.WaitGroup
  39. establishedTunnels chan *Tunnel
  40. failedTunnels chan *Tunnel
  41. tunnelMutex sync.Mutex
  42. establishedOnce bool
  43. tunnels []*Tunnel
  44. nextTunnel int
  45. startedConnectedReporter bool
  46. isEstablishing bool
  47. establishWaitGroup *sync.WaitGroup
  48. stopEstablishingBroadcast chan struct{}
  49. candidateServerEntries chan *ServerEntry
  50. establishPendingConns *Conns
  51. fetchRemotePendingConns *Conns
  52. }
  53. // NewController initializes a new controller.
  54. func NewController(config *Config) (controller *Controller, err error) {
  55. // Generate a session ID for the Psiphon server API. This session ID is
  56. // used across all tunnels established by the controller.
  57. sessionId, err := MakeSessionId()
  58. if err != nil {
  59. return nil, ContextError(err)
  60. }
  61. return &Controller{
  62. config: config,
  63. sessionId: sessionId,
  64. // componentFailureSignal receives a signal from a component (including socks and
  65. // http local proxies) if they unexpectedly fail. Senders should not block.
  66. // A buffer allows at least one stop signal to be sent before there is a receiver.
  67. componentFailureSignal: make(chan struct{}, 1),
  68. shutdownBroadcast: make(chan struct{}),
  69. runWaitGroup: new(sync.WaitGroup),
  70. // establishedTunnels and failedTunnels buffer sizes are large enough to
  71. // receive full pools of tunnels without blocking. Senders should not block.
  72. establishedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  73. failedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  74. tunnels: make([]*Tunnel, 0),
  75. establishedOnce: false,
  76. startedConnectedReporter: false,
  77. isEstablishing: false,
  78. establishPendingConns: new(Conns),
  79. fetchRemotePendingConns: new(Conns),
  80. }, nil
  81. }
  82. // Run executes the controller. It launches components and then monitors
  83. // for a shutdown signal; after receiving the signal it shuts down the
  84. // controller.
  85. // The components include:
  86. // - the periodic remote server list fetcher
  87. // - the connected reporter
  88. // - the tunnel manager
  89. // - a local SOCKS proxy that port forwards through the pool of tunnels
  90. // - a local HTTP proxy that port forwards through the pool of tunnels
  91. func (controller *Controller) Run(shutdownBroadcast <-chan struct{}) {
  92. NoticeBuildInfo()
  93. NoticeCoreVersion(VERSION)
  94. // Start components
  95. socksProxy, err := NewSocksProxy(controller.config, controller)
  96. if err != nil {
  97. NoticeAlert("error initializing local SOCKS proxy: %s", err)
  98. return
  99. }
  100. defer socksProxy.Close()
  101. httpProxy, err := NewHttpProxy(controller.config, controller)
  102. if err != nil {
  103. NoticeAlert("error initializing local HTTP proxy: %s", err)
  104. return
  105. }
  106. defer httpProxy.Close()
  107. if !controller.config.DisableRemoteServerListFetcher {
  108. controller.runWaitGroup.Add(1)
  109. go controller.remoteServerListFetcher()
  110. }
  111. /// Note: the connected reporter isn't started until a tunnel is
  112. // established
  113. controller.runWaitGroup.Add(1)
  114. go controller.runTunnels()
  115. if *controller.config.EstablishTunnelTimeoutSeconds != 0 {
  116. controller.runWaitGroup.Add(1)
  117. go controller.establishTunnelWatcher()
  118. }
  119. // Wait while running
  120. select {
  121. case <-shutdownBroadcast:
  122. NoticeInfo("controller shutdown by request")
  123. case <-controller.componentFailureSignal:
  124. NoticeAlert("controller shutdown due to component failure")
  125. }
  126. close(controller.shutdownBroadcast)
  127. controller.establishPendingConns.CloseAll()
  128. controller.fetchRemotePendingConns.CloseAll()
  129. controller.runWaitGroup.Wait()
  130. NoticeInfo("exiting controller")
  131. }
  132. // SignalComponentFailure notifies the controller that an associated component has failed.
  133. // This will terminate the controller.
  134. func (controller *Controller) SignalComponentFailure() {
  135. select {
  136. case controller.componentFailureSignal <- *new(struct{}):
  137. default:
  138. }
  139. }
  140. // remoteServerListFetcher fetches an out-of-band list of server entries
  141. // for more tunnel candidates. It fetches immediately, retries after failure
  142. // with a wait period, and refetches after success with a longer wait period.
  143. func (controller *Controller) remoteServerListFetcher() {
  144. defer controller.runWaitGroup.Done()
  145. loop:
  146. for {
  147. err := FetchRemoteServerList(
  148. controller.config, controller.fetchRemotePendingConns)
  149. var duration time.Duration
  150. if err != nil {
  151. NoticeAlert("failed to fetch remote server list: %s", err)
  152. duration = FETCH_REMOTE_SERVER_LIST_RETRY_PERIOD
  153. } else {
  154. duration = FETCH_REMOTE_SERVER_LIST_STALE_PERIOD
  155. }
  156. timeout := time.After(duration)
  157. select {
  158. case <-timeout:
  159. // Fetch again
  160. case <-controller.shutdownBroadcast:
  161. break loop
  162. }
  163. }
  164. NoticeInfo("exiting remote server list fetcher")
  165. }
  166. // establishTunnelWatcher terminates the controller if a tunnel
  167. // has not been established in the configured time period. This
  168. // is regardless of how many tunnels are presently active -- meaning
  169. // that if an active tunnel was established and lost the controller
  170. // is left running (to re-establish).
  171. func (controller *Controller) establishTunnelWatcher() {
  172. defer controller.runWaitGroup.Done()
  173. timeout := time.After(
  174. time.Duration(*controller.config.EstablishTunnelTimeoutSeconds) * time.Second)
  175. select {
  176. case <-timeout:
  177. if !controller.hasEstablishedOnce() {
  178. NoticeAlert("failed to establish tunnel before timeout")
  179. controller.SignalComponentFailure()
  180. }
  181. case <-controller.shutdownBroadcast:
  182. }
  183. NoticeInfo("exiting establish tunnel watcher")
  184. }
  185. // connectedReporter sends periodic "connected" requests to the Psiphon API.
  186. // These requests are for server-side unique user stats calculation. See the
  187. // comment in DoConnectedRequest for a description of the request mechanism.
  188. // To ensure we don't over- or under-count unique users, only one connected
  189. // request is made across all simultaneous multi-tunnels; and the connected
  190. // request is repeated periodically.
  191. func (controller *Controller) connectedReporter() {
  192. defer controller.runWaitGroup.Done()
  193. loop:
  194. for {
  195. // Pick any active tunnel and make the next connected request. No error
  196. // is logged if there's no active tunnel, as that's not an unexpected condition.
  197. reported := false
  198. tunnel := controller.getNextActiveTunnel()
  199. if tunnel != nil {
  200. err := tunnel.session.DoConnectedRequest()
  201. if err == nil {
  202. reported = true
  203. } else {
  204. NoticeAlert("failed to make connected request: %s", err)
  205. }
  206. }
  207. // Schedule the next connected request and wait.
  208. var duration time.Duration
  209. if reported {
  210. duration = PSIPHON_API_CONNECTED_REQUEST_PERIOD
  211. } else {
  212. duration = PSIPHON_API_CONNECTED_REQUEST_RETRY_PERIOD
  213. }
  214. timeout := time.After(duration)
  215. select {
  216. case <-timeout:
  217. // Make another connected request
  218. case <-controller.shutdownBroadcast:
  219. break loop
  220. }
  221. }
  222. NoticeInfo("exiting connected reporter")
  223. }
  224. func (controller *Controller) startConnectedReporter() {
  225. if controller.config.DisableApi {
  226. return
  227. }
  228. // Start the connected reporter after the first tunnel is established.
  229. // Concurrency note: only the runTunnels goroutine may access startedConnectedReporter.
  230. if !controller.startedConnectedReporter {
  231. controller.startedConnectedReporter = true
  232. controller.runWaitGroup.Add(1)
  233. go controller.connectedReporter()
  234. }
  235. }
  236. // runTunnels is the controller tunnel management main loop. It starts and stops
  237. // establishing tunnels based on the target tunnel pool size and the current size
  238. // of the pool. Tunnels are established asynchronously using worker goroutines.
  239. //
  240. // When there are no server entries for the target region/protocol, the
  241. // establishCandidateGenerator will yield no candidates and wait before
  242. // trying again. In the meantime, a remote server entry fetch may supply
  243. // valid candidates.
  244. //
  245. // When a tunnel is established, it's added to the active pool. The tunnel's
  246. // operateTunnel goroutine monitors the tunnel.
  247. //
  248. // When a tunnel fails, it's removed from the pool and the establish process is
  249. // restarted to fill the pool.
  250. func (controller *Controller) runTunnels() {
  251. defer controller.runWaitGroup.Done()
  252. // Start running
  253. controller.startEstablishing()
  254. loop:
  255. for {
  256. select {
  257. case failedTunnel := <-controller.failedTunnels:
  258. NoticeAlert("tunnel failed: %s", failedTunnel.serverEntry.IpAddress)
  259. controller.terminateTunnel(failedTunnel)
  260. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing
  261. // and access isEstablishing.
  262. if !controller.isEstablishing {
  263. controller.startEstablishing()
  264. }
  265. // !TODO! design issue: might not be enough server entries with region/caps to ever fill tunnel slots
  266. // solution(?) target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  267. case establishedTunnel := <-controller.establishedTunnels:
  268. if controller.registerTunnel(establishedTunnel) {
  269. NoticeActiveTunnel(establishedTunnel.serverEntry.IpAddress)
  270. } else {
  271. controller.discardTunnel(establishedTunnel)
  272. }
  273. if controller.isFullyEstablished() {
  274. controller.stopEstablishing()
  275. }
  276. controller.startConnectedReporter()
  277. case <-controller.shutdownBroadcast:
  278. break loop
  279. }
  280. }
  281. // Stop running
  282. controller.stopEstablishing()
  283. controller.terminateAllTunnels()
  284. // Drain tunnel channels
  285. close(controller.establishedTunnels)
  286. for tunnel := range controller.establishedTunnels {
  287. controller.discardTunnel(tunnel)
  288. }
  289. close(controller.failedTunnels)
  290. for tunnel := range controller.failedTunnels {
  291. controller.discardTunnel(tunnel)
  292. }
  293. NoticeInfo("exiting run tunnels")
  294. }
  295. // SignalTunnelFailure implements the TunnelOwner interface. This function
  296. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  297. // has failed. The Controller will signal runTunnels to create a new
  298. // tunnel and/or remove the tunnel from the list of active tunnels.
  299. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  300. // Don't block. Assumes the receiver has a buffer large enough for
  301. // the typical number of operated tunnels. In case there's no room,
  302. // terminate the tunnel (runTunnels won't get a signal in this case,
  303. // but the tunnel will be removed from the list of active tunnels).
  304. select {
  305. case controller.failedTunnels <- tunnel:
  306. default:
  307. controller.terminateTunnel(tunnel)
  308. }
  309. }
  310. // discardTunnel disposes of a successful connection that is no longer required.
  311. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  312. NoticeInfo("discard tunnel: %s", tunnel.serverEntry.IpAddress)
  313. // TODO: not calling PromoteServerEntry, since that would rank the
  314. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  315. // be promoted (since it connects), but with lower rank than all active
  316. // tunnels?
  317. tunnel.Close()
  318. }
  319. // registerTunnel adds the connected tunnel to the pool of active tunnels
  320. // which are candidates for port forwarding. Returns true if the pool has an
  321. // empty slot and false if the pool is full (caller should discard the tunnel).
  322. func (controller *Controller) registerTunnel(tunnel *Tunnel) bool {
  323. controller.tunnelMutex.Lock()
  324. defer controller.tunnelMutex.Unlock()
  325. if len(controller.tunnels) >= controller.config.TunnelPoolSize {
  326. return false
  327. }
  328. // Perform a final check just in case we've established
  329. // a duplicate connection.
  330. for _, activeTunnel := range controller.tunnels {
  331. if activeTunnel.serverEntry.IpAddress == tunnel.serverEntry.IpAddress {
  332. NoticeAlert("duplicate tunnel: %s", tunnel.serverEntry.IpAddress)
  333. return false
  334. }
  335. }
  336. controller.establishedOnce = true
  337. controller.tunnels = append(controller.tunnels, tunnel)
  338. NoticeTunnels(len(controller.tunnels))
  339. return true
  340. }
  341. // hasEstablishedOnce indicates if at least one active tunnel has
  342. // been established up to this point. This is regardeless of how many
  343. // tunnels are presently active.
  344. func (controller *Controller) hasEstablishedOnce() bool {
  345. controller.tunnelMutex.Lock()
  346. defer controller.tunnelMutex.Unlock()
  347. return controller.establishedOnce
  348. }
  349. // isFullyEstablished indicates if the pool of active tunnels is full.
  350. func (controller *Controller) isFullyEstablished() bool {
  351. controller.tunnelMutex.Lock()
  352. defer controller.tunnelMutex.Unlock()
  353. return len(controller.tunnels) >= controller.config.TunnelPoolSize
  354. }
  355. // terminateTunnel removes a tunnel from the pool of active tunnels
  356. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  357. // is adjusted as required.
  358. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  359. controller.tunnelMutex.Lock()
  360. defer controller.tunnelMutex.Unlock()
  361. for index, activeTunnel := range controller.tunnels {
  362. if tunnel == activeTunnel {
  363. controller.tunnels = append(
  364. controller.tunnels[:index], controller.tunnels[index+1:]...)
  365. if controller.nextTunnel > index {
  366. controller.nextTunnel--
  367. }
  368. if controller.nextTunnel >= len(controller.tunnels) {
  369. controller.nextTunnel = 0
  370. }
  371. activeTunnel.Close()
  372. NoticeTunnels(len(controller.tunnels))
  373. break
  374. }
  375. }
  376. }
  377. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  378. // This is used when shutting down the controller.
  379. func (controller *Controller) terminateAllTunnels() {
  380. controller.tunnelMutex.Lock()
  381. defer controller.tunnelMutex.Unlock()
  382. for _, activeTunnel := range controller.tunnels {
  383. activeTunnel.Close()
  384. }
  385. controller.tunnels = make([]*Tunnel, 0)
  386. controller.nextTunnel = 0
  387. NoticeTunnels(len(controller.tunnels))
  388. }
  389. // getNextActiveTunnel returns the next tunnel from the pool of active
  390. // tunnels. Currently, tunnel selection order is simple round-robin.
  391. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  392. controller.tunnelMutex.Lock()
  393. defer controller.tunnelMutex.Unlock()
  394. for i := len(controller.tunnels); i > 0; i-- {
  395. tunnel = controller.tunnels[controller.nextTunnel]
  396. controller.nextTunnel =
  397. (controller.nextTunnel + 1) % len(controller.tunnels)
  398. return tunnel
  399. }
  400. return nil
  401. }
  402. // isActiveTunnelServerEntries is used to check if there's already
  403. // an existing tunnel to a candidate server.
  404. func (controller *Controller) isActiveTunnelServerEntry(serverEntry *ServerEntry) bool {
  405. controller.tunnelMutex.Lock()
  406. defer controller.tunnelMutex.Unlock()
  407. for _, activeTunnel := range controller.tunnels {
  408. if activeTunnel.serverEntry.IpAddress == serverEntry.IpAddress {
  409. return true
  410. }
  411. }
  412. return false
  413. }
  414. // Dial selects an active tunnel and establishes a port forward
  415. // connection through the selected tunnel. Failure to connect is considered
  416. // a port foward failure, for the purpose of monitoring tunnel health.
  417. func (controller *Controller) Dial(remoteAddr string) (conn net.Conn, err error) {
  418. tunnel := controller.getNextActiveTunnel()
  419. if tunnel == nil {
  420. return nil, ContextError(errors.New("no active tunnels"))
  421. }
  422. tunneledConn, err := tunnel.Dial(remoteAddr)
  423. if err != nil {
  424. return nil, ContextError(err)
  425. }
  426. return tunneledConn, nil
  427. }
  428. // startEstablishing creates a pool of worker goroutines which will
  429. // attempt to establish tunnels to candidate servers. The candidates
  430. // are generated by another goroutine.
  431. func (controller *Controller) startEstablishing() {
  432. if controller.isEstablishing {
  433. return
  434. }
  435. NoticeInfo("start establishing")
  436. controller.isEstablishing = true
  437. controller.establishWaitGroup = new(sync.WaitGroup)
  438. controller.stopEstablishingBroadcast = make(chan struct{})
  439. controller.candidateServerEntries = make(chan *ServerEntry)
  440. controller.establishPendingConns.Reset()
  441. for i := 0; i < controller.config.ConnectionWorkerPoolSize; i++ {
  442. controller.establishWaitGroup.Add(1)
  443. go controller.establishTunnelWorker()
  444. }
  445. controller.establishWaitGroup.Add(1)
  446. go controller.establishCandidateGenerator()
  447. }
  448. // stopEstablishing signals the establish goroutines to stop and waits
  449. // for the group to halt. pendingConns is used to interrupt any worker
  450. // blocked on a socket connect.
  451. func (controller *Controller) stopEstablishing() {
  452. if !controller.isEstablishing {
  453. return
  454. }
  455. NoticeInfo("stop establishing")
  456. close(controller.stopEstablishingBroadcast)
  457. // Note: on Windows, interruptibleTCPClose doesn't really interrupt socket connects
  458. // and may leave goroutines running for a time after the Wait call.
  459. controller.establishPendingConns.CloseAll()
  460. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  461. // (as it may be sending to that channel).
  462. controller.establishWaitGroup.Wait()
  463. controller.isEstablishing = false
  464. controller.establishWaitGroup = nil
  465. controller.stopEstablishingBroadcast = nil
  466. controller.candidateServerEntries = nil
  467. }
  468. // establishCandidateGenerator populates the candidate queue with server entries
  469. // from the data store. Server entries are iterated in rank order, so that promoted
  470. // servers with higher rank are priority candidates.
  471. func (controller *Controller) establishCandidateGenerator() {
  472. defer controller.establishWaitGroup.Done()
  473. defer close(controller.candidateServerEntries)
  474. iterator, err := NewServerEntryIterator(controller.config)
  475. if err != nil {
  476. NoticeAlert("failed to iterate over candidates: %s", err)
  477. controller.SignalComponentFailure()
  478. return
  479. }
  480. defer iterator.Close()
  481. loop:
  482. // Repeat until stopped
  483. for {
  484. // Yield each server entry returned by the iterator
  485. for {
  486. serverEntry, err := iterator.Next()
  487. if err != nil {
  488. NoticeAlert("failed to get next candidate: %s", err)
  489. controller.SignalComponentFailure()
  490. break loop
  491. }
  492. if serverEntry == nil {
  493. // Completed this iteration
  494. break
  495. }
  496. select {
  497. case controller.candidateServerEntries <- serverEntry:
  498. case <-controller.stopEstablishingBroadcast:
  499. break loop
  500. case <-controller.shutdownBroadcast:
  501. break loop
  502. }
  503. }
  504. iterator.Reset()
  505. // After a complete iteration of candidate servers, pause before iterating again.
  506. // This helps avoid some busy wait loop conditions, and also allows some time for
  507. // network conditions to change.
  508. timeout := time.After(ESTABLISH_TUNNEL_PAUSE_PERIOD)
  509. select {
  510. case <-timeout:
  511. // Retry iterating
  512. case <-controller.stopEstablishingBroadcast:
  513. break loop
  514. case <-controller.shutdownBroadcast:
  515. break loop
  516. }
  517. }
  518. NoticeInfo("stopped candidate generator")
  519. }
  520. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  521. // a connection to the tunnel server, and delivers the established tunnel to a channel.
  522. func (controller *Controller) establishTunnelWorker() {
  523. defer controller.establishWaitGroup.Done()
  524. loop:
  525. for serverEntry := range controller.candidateServerEntries {
  526. // Note: don't receive from candidateServerEntries and stopEstablishingBroadcast
  527. // in the same select, since we want to prioritize receiving the stop signal
  528. if controller.isStopEstablishingBroadcast() {
  529. break loop
  530. }
  531. // There may already be a tunnel to this candidate. If so, skip it.
  532. if controller.isActiveTunnelServerEntry(serverEntry) {
  533. continue
  534. }
  535. tunnel, err := EstablishTunnel(
  536. controller.config,
  537. controller.sessionId,
  538. controller.establishPendingConns,
  539. serverEntry,
  540. controller) // TunnelOwner
  541. if err != nil {
  542. // Before emitting error, check if establish interrupted, in which
  543. // case the error is noise.
  544. if controller.isStopEstablishingBroadcast() {
  545. break loop
  546. }
  547. NoticeInfo("failed to connect to %s: %s", serverEntry.IpAddress, err)
  548. continue
  549. }
  550. // Deliver established tunnel.
  551. // Don't block. Assumes the receiver has a buffer large enough for
  552. // the number of desired tunnels. If there's no room, the tunnel must
  553. // not be required so it's discarded.
  554. select {
  555. case controller.establishedTunnels <- tunnel:
  556. default:
  557. controller.discardTunnel(tunnel)
  558. }
  559. }
  560. NoticeInfo("stopped establish worker")
  561. }
  562. func (controller *Controller) isStopEstablishingBroadcast() bool {
  563. select {
  564. case <-controller.stopEstablishingBroadcast:
  565. return true
  566. default:
  567. }
  568. return false
  569. }