controller.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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.NetworkConnectivityChecker,
  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. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  388. // may take a few seconds to send a final status request. We only want
  389. // to wait as long as the single slowest tunnel.
  390. closeWaitGroup := new(sync.WaitGroup)
  391. closeWaitGroup.Add(len(controller.tunnels))
  392. for _, activeTunnel := range controller.tunnels {
  393. tunnel := activeTunnel
  394. go func() {
  395. defer closeWaitGroup.Done()
  396. tunnel.Close()
  397. }()
  398. }
  399. closeWaitGroup.Wait()
  400. controller.tunnels = make([]*Tunnel, 0)
  401. controller.nextTunnel = 0
  402. NoticeTunnels(len(controller.tunnels))
  403. }
  404. // getNextActiveTunnel returns the next tunnel from the pool of active
  405. // tunnels. Currently, tunnel selection order is simple round-robin.
  406. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  407. controller.tunnelMutex.Lock()
  408. defer controller.tunnelMutex.Unlock()
  409. for i := len(controller.tunnels); i > 0; i-- {
  410. tunnel = controller.tunnels[controller.nextTunnel]
  411. controller.nextTunnel =
  412. (controller.nextTunnel + 1) % len(controller.tunnels)
  413. return tunnel
  414. }
  415. return nil
  416. }
  417. // isActiveTunnelServerEntries is used to check if there's already
  418. // an existing tunnel to a candidate server.
  419. func (controller *Controller) isActiveTunnelServerEntry(serverEntry *ServerEntry) bool {
  420. controller.tunnelMutex.Lock()
  421. defer controller.tunnelMutex.Unlock()
  422. for _, activeTunnel := range controller.tunnels {
  423. if activeTunnel.serverEntry.IpAddress == serverEntry.IpAddress {
  424. return true
  425. }
  426. }
  427. return false
  428. }
  429. // Dial selects an active tunnel and establishes a port forward
  430. // connection through the selected tunnel. Failure to connect is considered
  431. // a port foward failure, for the purpose of monitoring tunnel health.
  432. func (controller *Controller) Dial(remoteAddr string, downstreamConn net.Conn) (conn net.Conn, err error) {
  433. tunnel := controller.getNextActiveTunnel()
  434. if tunnel == nil {
  435. return nil, ContextError(errors.New("no active tunnels"))
  436. }
  437. tunneledConn, err := tunnel.Dial(remoteAddr, downstreamConn)
  438. if err != nil {
  439. return nil, ContextError(err)
  440. }
  441. return tunneledConn, nil
  442. }
  443. // startEstablishing creates a pool of worker goroutines which will
  444. // attempt to establish tunnels to candidate servers. The candidates
  445. // are generated by another goroutine.
  446. func (controller *Controller) startEstablishing() {
  447. if controller.isEstablishing {
  448. return
  449. }
  450. NoticeInfo("start establishing")
  451. controller.isEstablishing = true
  452. controller.establishWaitGroup = new(sync.WaitGroup)
  453. controller.stopEstablishingBroadcast = make(chan struct{})
  454. controller.candidateServerEntries = make(chan *ServerEntry)
  455. controller.establishPendingConns.Reset()
  456. for i := 0; i < controller.config.ConnectionWorkerPoolSize; i++ {
  457. controller.establishWaitGroup.Add(1)
  458. go controller.establishTunnelWorker()
  459. }
  460. controller.establishWaitGroup.Add(1)
  461. go controller.establishCandidateGenerator()
  462. }
  463. // stopEstablishing signals the establish goroutines to stop and waits
  464. // for the group to halt. pendingConns is used to interrupt any worker
  465. // blocked on a socket connect.
  466. func (controller *Controller) stopEstablishing() {
  467. if !controller.isEstablishing {
  468. return
  469. }
  470. NoticeInfo("stop establishing")
  471. close(controller.stopEstablishingBroadcast)
  472. // Note: on Windows, interruptibleTCPClose doesn't really interrupt socket connects
  473. // and may leave goroutines running for a time after the Wait call.
  474. controller.establishPendingConns.CloseAll()
  475. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  476. // (as it may be sending to that channel).
  477. controller.establishWaitGroup.Wait()
  478. controller.isEstablishing = false
  479. controller.establishWaitGroup = nil
  480. controller.stopEstablishingBroadcast = nil
  481. controller.candidateServerEntries = nil
  482. }
  483. // establishCandidateGenerator populates the candidate queue with server entries
  484. // from the data store. Server entries are iterated in rank order, so that promoted
  485. // servers with higher rank are priority candidates.
  486. func (controller *Controller) establishCandidateGenerator() {
  487. defer controller.establishWaitGroup.Done()
  488. defer close(controller.candidateServerEntries)
  489. iterator, err := NewServerEntryIterator(controller.config)
  490. if err != nil {
  491. NoticeAlert("failed to iterate over candidates: %s", err)
  492. controller.SignalComponentFailure()
  493. return
  494. }
  495. defer iterator.Close()
  496. loop:
  497. // Repeat until stopped
  498. for {
  499. // Yield each server entry returned by the iterator
  500. for {
  501. serverEntry, err := iterator.Next()
  502. if err != nil {
  503. NoticeAlert("failed to get next candidate: %s", err)
  504. controller.SignalComponentFailure()
  505. break loop
  506. }
  507. if serverEntry == nil {
  508. // Completed this iteration
  509. break
  510. }
  511. select {
  512. case controller.candidateServerEntries <- serverEntry:
  513. case <-controller.stopEstablishingBroadcast:
  514. break loop
  515. case <-controller.shutdownBroadcast:
  516. break loop
  517. }
  518. }
  519. iterator.Reset()
  520. // After a complete iteration of candidate servers, pause before iterating again.
  521. // This helps avoid some busy wait loop conditions, and also allows some time for
  522. // network conditions to change.
  523. timeout := time.After(ESTABLISH_TUNNEL_PAUSE_PERIOD)
  524. select {
  525. case <-timeout:
  526. // Retry iterating
  527. case <-controller.stopEstablishingBroadcast:
  528. break loop
  529. case <-controller.shutdownBroadcast:
  530. break loop
  531. }
  532. }
  533. NoticeInfo("stopped candidate generator")
  534. }
  535. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  536. // a connection to the tunnel server, and delivers the established tunnel to a channel.
  537. func (controller *Controller) establishTunnelWorker() {
  538. defer controller.establishWaitGroup.Done()
  539. loop:
  540. for serverEntry := range controller.candidateServerEntries {
  541. // Note: don't receive from candidateServerEntries and stopEstablishingBroadcast
  542. // in the same select, since we want to prioritize receiving the stop signal
  543. if controller.isStopEstablishingBroadcast() {
  544. break loop
  545. }
  546. // There may already be a tunnel to this candidate. If so, skip it.
  547. if controller.isActiveTunnelServerEntry(serverEntry) {
  548. continue
  549. }
  550. if !WaitForNetworkConnectivity(
  551. controller.config.NetworkConnectivityChecker,
  552. controller.stopEstablishingBroadcast) {
  553. break loop
  554. }
  555. tunnel, err := EstablishTunnel(
  556. controller.config,
  557. controller.sessionId,
  558. controller.establishPendingConns,
  559. serverEntry,
  560. controller) // TunnelOwner
  561. if err != nil {
  562. // Before emitting error, check if establish interrupted, in which
  563. // case the error is noise.
  564. if controller.isStopEstablishingBroadcast() {
  565. break loop
  566. }
  567. NoticeInfo("failed to connect to %s: %s", serverEntry.IpAddress, err)
  568. continue
  569. }
  570. // Deliver established tunnel.
  571. // Don't block. Assumes the receiver has a buffer large enough for
  572. // the number of desired tunnels. If there's no room, the tunnel must
  573. // not be required so it's discarded.
  574. select {
  575. case controller.establishedTunnels <- tunnel:
  576. default:
  577. controller.discardTunnel(tunnel)
  578. }
  579. }
  580. NoticeInfo("stopped establish worker")
  581. }
  582. func (controller *Controller) isStopEstablishingBroadcast() bool {
  583. select {
  584. case <-controller.stopEstablishingBroadcast:
  585. return true
  586. default:
  587. }
  588. return false
  589. }