controller.go 21 KB

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