controller.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. /*
  2. * Copyright (c) 2014, 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. "fmt"
  27. "io"
  28. "net"
  29. "sync"
  30. "time"
  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. failureSignal chan struct{}
  38. shutdownBroadcast chan struct{}
  39. runWaitGroup *sync.WaitGroup
  40. establishedTunnels chan *Tunnel
  41. failedTunnels chan *Tunnel
  42. tunnelMutex sync.Mutex
  43. tunnels []*Tunnel
  44. nextTunnel int
  45. operateWaitGroup *sync.WaitGroup
  46. isEstablishing bool
  47. establishWaitGroup *sync.WaitGroup
  48. stopEstablishingBroadcast chan struct{}
  49. candidateServerEntries chan *ServerEntry
  50. pendingConns *Conns
  51. }
  52. // NewController initializes a new controller.
  53. func NewController(config *Config) (controller *Controller) {
  54. return &Controller{
  55. config: config,
  56. // failureSignal receives a signal from a component (including socks and
  57. // http local proxies) if they unexpectedly fail. Senders should not block.
  58. // A buffer allows at least one stop signal to be sent before there is a receiver.
  59. failureSignal: make(chan struct{}, 1),
  60. shutdownBroadcast: make(chan struct{}),
  61. runWaitGroup: new(sync.WaitGroup),
  62. // establishedTunnels and failedTunnels buffer sizes are large enough to
  63. // receive full pools of tunnels without blocking. Senders should not block.
  64. establishedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  65. failedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  66. tunnels: make([]*Tunnel, 0),
  67. operateWaitGroup: new(sync.WaitGroup),
  68. isEstablishing: false,
  69. pendingConns: new(Conns),
  70. }
  71. }
  72. // Run executes the controller. It launches components and then monitors
  73. // for a shutdown signal; after receiving the signal it shuts down the
  74. // controller.
  75. // The components include:
  76. // - the periodic remote server list fetcher
  77. // - the tunnel manager
  78. // - a local SOCKS proxy that port forwards through the pool of tunnels
  79. // - a local HTTP proxy that port forwards through the pool of tunnels
  80. func (controller *Controller) Run(shutdownBroadcast <-chan struct{}) {
  81. Notice(NOTICE_VERSION, VERSION)
  82. socksProxy, err := NewSocksProxy(controller.config, controller)
  83. if err != nil {
  84. Notice(NOTICE_ALERT, "error initializing local SOCKS proxy: %s", err)
  85. return
  86. }
  87. defer socksProxy.Close()
  88. httpProxy, err := NewHttpProxy(controller.config, controller)
  89. if err != nil {
  90. Notice(NOTICE_ALERT, "error initializing local SOCKS proxy: %s", err)
  91. return
  92. }
  93. defer httpProxy.Close()
  94. controller.runWaitGroup.Add(2)
  95. go controller.remoteServerListFetcher()
  96. go controller.runTunnels()
  97. select {
  98. case <-shutdownBroadcast:
  99. Notice(NOTICE_INFO, "controller shutdown by request")
  100. case <-controller.failureSignal:
  101. Notice(NOTICE_ALERT, "controller shutdown due to failure")
  102. }
  103. // Note: in addition to establish(), this pendingConns will interrupt
  104. // FetchRemoteServerList
  105. controller.pendingConns.CloseAll()
  106. close(controller.shutdownBroadcast)
  107. controller.runWaitGroup.Wait()
  108. Notice(NOTICE_INFO, "exiting controller")
  109. }
  110. // SignalFailure notifies the controller that an associated component has failed.
  111. // This will terminate the controller.
  112. func (controller *Controller) SignalFailure() {
  113. select {
  114. case controller.failureSignal <- *new(struct{}):
  115. default:
  116. }
  117. }
  118. // remoteServerListFetcher fetches an out-of-band list of server entries
  119. // for more tunnel candidates. It fetches immediately, retries after failure
  120. // with a wait period, and refetches after success with a longer wait period.
  121. func (controller *Controller) remoteServerListFetcher() {
  122. defer controller.runWaitGroup.Done()
  123. // Note: unlike existing Psiphon clients, this code
  124. // always makes the fetch remote server list request
  125. loop:
  126. for {
  127. // TODO: FetchRemoteServerList should have its own pendingConns,
  128. // otherwise it may needlessly abort when establish is stopped.
  129. err := FetchRemoteServerList(controller.config, controller.pendingConns)
  130. var duration time.Duration
  131. if err != nil {
  132. Notice(NOTICE_ALERT, "failed to fetch remote server list: %s", err)
  133. duration = FETCH_REMOTE_SERVER_LIST_RETRY_TIMEOUT
  134. } else {
  135. duration = FETCH_REMOTE_SERVER_LIST_STALE_TIMEOUT
  136. }
  137. timeout := time.After(duration)
  138. select {
  139. case <-timeout:
  140. // Fetch again
  141. case <-controller.shutdownBroadcast:
  142. break loop
  143. }
  144. }
  145. Notice(NOTICE_INFO, "exiting remote server list fetcher")
  146. }
  147. // runTunnels is the controller tunnel management main loop. It starts and stops
  148. // establishing tunnels based on the target tunnel pool size and the current size
  149. // of the pool. Tunnels are established asynchronously using worker goroutines.
  150. // When a tunnel is established, it's added to the active pool and a corresponding
  151. // operateTunnel goroutine is launched which starts a session in the tunnel and
  152. // monitors the tunnel for failures.
  153. // When a tunnel fails, it's removed from the pool and the establish process is
  154. // restarted to fill the pool.
  155. func (controller *Controller) runTunnels() {
  156. defer controller.runWaitGroup.Done()
  157. // Don't start establishing until there are some server candidates. The
  158. // typical case is a client with no server entries which will wait for
  159. // the first successful FetchRemoteServerList to populate the data store.
  160. for {
  161. if HasServerEntries(
  162. controller.config.EgressRegion, controller.config.TunnelProtocol) {
  163. break
  164. }
  165. // TODO: replace polling with signal
  166. timeout := time.After(5 * time.Second)
  167. select {
  168. case <-timeout:
  169. case <-controller.shutdownBroadcast:
  170. return
  171. }
  172. }
  173. controller.startEstablishing()
  174. loop:
  175. for {
  176. select {
  177. case failedTunnel := <-controller.failedTunnels:
  178. Notice(NOTICE_ALERT, "tunnel failed: %s", failedTunnel.serverEntry.IpAddress)
  179. controller.terminateTunnel(failedTunnel)
  180. // Note: only this goroutine may call startEstablishing/stopEstablishing and access
  181. // isEstablishing.
  182. if !controller.isEstablishing {
  183. controller.startEstablishing()
  184. }
  185. // !TODO! design issue: might not be enough server entries with region/caps to ever fill tunnel slots
  186. // solution(?) target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  187. case establishedTunnel := <-controller.establishedTunnels:
  188. Notice(NOTICE_INFO, "established tunnel: %s", establishedTunnel.serverEntry.IpAddress)
  189. if controller.registerTunnel(establishedTunnel) {
  190. Notice(NOTICE_INFO, "active tunnel: %s", establishedTunnel.serverEntry.IpAddress)
  191. controller.operateWaitGroup.Add(1)
  192. go controller.operateTunnel(establishedTunnel)
  193. } else {
  194. controller.discardTunnel(establishedTunnel)
  195. }
  196. if controller.isFullyEstablished() {
  197. controller.stopEstablishing()
  198. }
  199. case <-controller.shutdownBroadcast:
  200. break loop
  201. }
  202. }
  203. controller.stopEstablishing()
  204. controller.terminateAllTunnels()
  205. controller.operateWaitGroup.Wait()
  206. // Drain tunnel channels
  207. close(controller.establishedTunnels)
  208. for tunnel := range controller.establishedTunnels {
  209. controller.discardTunnel(tunnel)
  210. }
  211. close(controller.failedTunnels)
  212. for tunnel := range controller.failedTunnels {
  213. controller.discardTunnel(tunnel)
  214. }
  215. Notice(NOTICE_INFO, "exiting run tunnels")
  216. }
  217. // discardTunnel disposes of a successful connection that is no longer required.
  218. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  219. Notice(NOTICE_INFO, "discard tunnel: %s", tunnel.serverEntry.IpAddress)
  220. // TODO: not calling PromoteServerEntry, since that would rank the
  221. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  222. // be promoted (since it connects), but with lower rank than all active
  223. // tunnels?
  224. tunnel.Close()
  225. }
  226. // registerTunnel adds the connected tunnel to the pool of active tunnels
  227. // which are candidates for port forwarding. Returns true if the pool has an
  228. // empty slot and false if the pool is full (caller should discard the tunnel).
  229. func (controller *Controller) registerTunnel(tunnel *Tunnel) bool {
  230. controller.tunnelMutex.Lock()
  231. defer controller.tunnelMutex.Unlock()
  232. if len(controller.tunnels) >= controller.config.TunnelPoolSize {
  233. return false
  234. }
  235. // Perform a final check just in case we've established
  236. // a duplicate connection.
  237. for _, activeTunnel := range controller.tunnels {
  238. if activeTunnel.serverEntry.IpAddress == tunnel.serverEntry.IpAddress {
  239. Notice(NOTICE_ALERT, "duplicate tunnel: %s", tunnel.serverEntry.IpAddress)
  240. return false
  241. }
  242. }
  243. controller.tunnels = append(controller.tunnels, tunnel)
  244. Notice(NOTICE_TUNNELS, "%d", len(controller.tunnels))
  245. return true
  246. }
  247. // isFullyEstablished indicates if the pool of active tunnels is full.
  248. func (controller *Controller) isFullyEstablished() bool {
  249. controller.tunnelMutex.Lock()
  250. defer controller.tunnelMutex.Unlock()
  251. return len(controller.tunnels) >= controller.config.TunnelPoolSize
  252. }
  253. // terminateTunnel removes a tunnel from the pool of active tunnels
  254. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  255. // is adjusted as required.
  256. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  257. controller.tunnelMutex.Lock()
  258. defer controller.tunnelMutex.Unlock()
  259. for index, activeTunnel := range controller.tunnels {
  260. if tunnel == activeTunnel {
  261. controller.tunnels = append(
  262. controller.tunnels[:index], controller.tunnels[index+1:]...)
  263. if controller.nextTunnel > index {
  264. controller.nextTunnel--
  265. }
  266. if controller.nextTunnel >= len(controller.tunnels) {
  267. controller.nextTunnel = 0
  268. }
  269. activeTunnel.Close()
  270. Notice(NOTICE_TUNNELS, "%d", len(controller.tunnels))
  271. break
  272. }
  273. }
  274. }
  275. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  276. // This is used when shutting down the controller.
  277. func (controller *Controller) terminateAllTunnels() {
  278. controller.tunnelMutex.Lock()
  279. defer controller.tunnelMutex.Unlock()
  280. for _, activeTunnel := range controller.tunnels {
  281. activeTunnel.Close()
  282. }
  283. controller.tunnels = make([]*Tunnel, 0)
  284. controller.nextTunnel = 0
  285. Notice(NOTICE_TUNNELS, "%d", len(controller.tunnels))
  286. }
  287. // getNextActiveTunnel returns the next tunnel from the pool of active
  288. // tunnels. Currently, tunnel selection order is simple round-robin.
  289. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  290. controller.tunnelMutex.Lock()
  291. defer controller.tunnelMutex.Unlock()
  292. for i := len(controller.tunnels); i > 0; i-- {
  293. tunnel = controller.tunnels[controller.nextTunnel]
  294. controller.nextTunnel =
  295. (controller.nextTunnel + 1) % len(controller.tunnels)
  296. // A tunnel must[*] have started its session (performed the server
  297. // API handshake sequence) before it may be used for tunneling traffic
  298. // [*]currently not enforced by the server, but may be in the future.
  299. if tunnel.IsSessionStarted() {
  300. return tunnel
  301. }
  302. }
  303. return nil
  304. }
  305. // isActiveTunnelServerEntries is used to check if there's already
  306. // an existing tunnel to a candidate server.
  307. func (controller *Controller) isActiveTunnelServerEntry(serverEntry *ServerEntry) bool {
  308. controller.tunnelMutex.Lock()
  309. defer controller.tunnelMutex.Unlock()
  310. for _, activeTunnel := range controller.tunnels {
  311. if activeTunnel.serverEntry.IpAddress == serverEntry.IpAddress {
  312. return true
  313. }
  314. }
  315. return false
  316. }
  317. // operateTunnel starts a Psiphon session (handshake, etc.) on a newly
  318. // connected tunnel, and then monitors the tunnel for failures:
  319. //
  320. // 1. Overall tunnel failure: the tunnel sends a signal to the ClosedSignal
  321. // channel on keep-alive failure and other transport I/O errors. In case
  322. // of such a failure, the tunnel is marked as failed.
  323. //
  324. // 2. Tunnel port forward failures: the tunnel connection may stay up but
  325. // the client may still fail to establish port forwards due to server load
  326. // and other conditions. After a threshold number of such failures, the
  327. // overall tunnel is marked as failed.
  328. //
  329. // TODO: currently, any connect (dial), read, or write error associated with
  330. // a port forward is counted as a failure. It may be important to differentiate
  331. // between failures due to Psiphon server conditions and failures due to the
  332. // origin/target server (in the latter case, the tunnel is healthy). Here are
  333. // some typical error messages to consider matching against (or ignoring):
  334. //
  335. // - "ssh: rejected: administratively prohibited (open failed)"
  336. // - "ssh: rejected: connect failed (Connection timed out)"
  337. // - "write tcp ... broken pipe"
  338. // - "read tcp ... connection reset by peer"
  339. // - "ssh: unexpected packet in response to channel open: <nil>"
  340. //
  341. func (controller *Controller) operateTunnel(tunnel *Tunnel) {
  342. defer controller.operateWaitGroup.Done()
  343. tunnelClosedSignal := make(chan struct{}, 1)
  344. err := tunnel.conn.SetClosedSignal(tunnelClosedSignal)
  345. if err != nil {
  346. err = fmt.Errorf("failed to set closed signal: %s", err)
  347. }
  348. Notice(NOTICE_INFO, "starting session for %s", tunnel.serverEntry.IpAddress)
  349. // TODO: NewSession server API calls may block shutdown
  350. session, err := NewSession(controller.config, tunnel)
  351. if err != nil {
  352. err = fmt.Errorf("error starting session for %s: %s", tunnel.serverEntry.IpAddress, err)
  353. }
  354. // Tunnel may now be used for port forwarding
  355. tunnel.SetSessionStarted()
  356. // Promote this successful tunnel to first rank so it's one
  357. // of the first candidates next time establish runs.
  358. PromoteServerEntry(tunnel.serverEntry.IpAddress)
  359. statsTimer := time.NewTimer(NextSendPeriod())
  360. for err == nil {
  361. select {
  362. case failures := <-tunnel.portForwardFailures:
  363. tunnel.portForwardFailureTotal += failures
  364. Notice(
  365. NOTICE_INFO, "port forward failures for %s: %d",
  366. tunnel.serverEntry.IpAddress, tunnel.portForwardFailureTotal)
  367. if tunnel.portForwardFailureTotal > controller.config.PortForwardFailureThreshold {
  368. err = errors.New("tunnel exceeded port forward failure threshold")
  369. }
  370. case <-tunnelClosedSignal:
  371. // TODO: this signal can be received during a commanded shutdown due to
  372. // how tunnels are closed; should rework this to avoid log noise.
  373. err = errors.New("tunnel closed unexpectedly")
  374. case <-controller.shutdownBroadcast:
  375. // Send final stats
  376. sendStats(tunnel, session, true)
  377. Notice(NOTICE_INFO, "shutdown operate tunnel")
  378. return
  379. case <-statsTimer.C:
  380. sendStats(tunnel, session, false)
  381. statsTimer.Reset(NextSendPeriod())
  382. }
  383. }
  384. if err != nil {
  385. Notice(NOTICE_ALERT, "operate tunnel error for %s: %s", tunnel.serverEntry.IpAddress, err)
  386. // Don't block. Assumes the receiver has a buffer large enough for
  387. // the typical number of operated tunnels. In case there's no room,
  388. // terminate the tunnel (runTunnels won't get a signal in this case).
  389. select {
  390. case controller.failedTunnels <- tunnel:
  391. default:
  392. controller.terminateTunnel(tunnel)
  393. }
  394. }
  395. }
  396. // sendStats is a helper for sending session stats to the server.
  397. func sendStats(tunnel *Tunnel, session *Session, final bool) {
  398. payload := GetForServer(tunnel.serverEntry.IpAddress)
  399. if payload != nil {
  400. err := session.DoStatusRequest(payload, final)
  401. if err != nil {
  402. Notice(NOTICE_ALERT, "DoStatusRequest failed for %s: %s", tunnel.serverEntry.IpAddress, err)
  403. PutBack(tunnel.serverEntry.IpAddress, payload)
  404. }
  405. }
  406. }
  407. // TunneledConn implements net.Conn and wraps a port foward connection.
  408. // It is used to hook into Read and Write to observe I/O errors and
  409. // report these errors back to the tunnel monitor as port forward failures.
  410. type TunneledConn struct {
  411. net.Conn
  412. tunnel *Tunnel
  413. }
  414. func (conn *TunneledConn) Read(buffer []byte) (n int, err error) {
  415. n, err = conn.Conn.Read(buffer)
  416. if err != nil && err != io.EOF {
  417. // Report 1 new failure. Won't block; assumes the receiver
  418. // has a sufficient buffer for the threshold number of reports.
  419. // TODO: conditional on type of error or error message?
  420. select {
  421. case conn.tunnel.portForwardFailures <- 1:
  422. default:
  423. }
  424. }
  425. return
  426. }
  427. func (conn *TunneledConn) Write(buffer []byte) (n int, err error) {
  428. n, err = conn.Conn.Write(buffer)
  429. if err != nil && err != io.EOF {
  430. // Same as TunneledConn.Read()
  431. select {
  432. case conn.tunnel.portForwardFailures <- 1:
  433. default:
  434. }
  435. }
  436. return
  437. }
  438. // Dial selects an active tunnel and establishes a port forward
  439. // connection through the selected tunnel. Failure to connect is considered
  440. // a port foward failure, for the purpose of monitoring tunnel health.
  441. func (controller *Controller) Dial(remoteAddr string) (conn net.Conn, err error) {
  442. tunnel := controller.getNextActiveTunnel()
  443. if tunnel == nil {
  444. return nil, ContextError(errors.New("no active tunnels"))
  445. }
  446. tunnelConn, err := tunnel.Dial(remoteAddr)
  447. if err != nil {
  448. // TODO: conditional on type of error or error message?
  449. select {
  450. case tunnel.portForwardFailures <- 1:
  451. default:
  452. }
  453. return nil, ContextError(err)
  454. }
  455. statsConn := NewStatsConn(tunnelConn, tunnel.ServerID(), tunnel.StatsRegexps())
  456. conn = &TunneledConn{
  457. Conn: statsConn,
  458. tunnel: tunnel}
  459. return
  460. }
  461. // startEstablishing creates a pool of worker goroutines which will
  462. // attempt to establish tunnels to candidate servers. The candidates
  463. // are generated by another goroutine.
  464. func (controller *Controller) startEstablishing() {
  465. if controller.isEstablishing {
  466. return
  467. }
  468. Notice(NOTICE_INFO, "start establishing")
  469. controller.isEstablishing = true
  470. controller.establishWaitGroup = new(sync.WaitGroup)
  471. controller.stopEstablishingBroadcast = make(chan struct{})
  472. controller.candidateServerEntries = make(chan *ServerEntry)
  473. for i := 0; i < controller.config.ConnectionWorkerPoolSize; i++ {
  474. controller.establishWaitGroup.Add(1)
  475. go controller.establishTunnelWorker()
  476. }
  477. controller.establishWaitGroup.Add(1)
  478. go controller.establishCandidateGenerator()
  479. }
  480. // stopEstablishing signals the establish goroutines to stop and waits
  481. // for the group to halt. pendingConns is used to interrupt any worker
  482. // blocked on a socket connect.
  483. func (controller *Controller) stopEstablishing() {
  484. if !controller.isEstablishing {
  485. return
  486. }
  487. Notice(NOTICE_INFO, "stop establishing")
  488. // Note: on Windows, interruptibleTCPClose doesn't really interrupt socket connects
  489. // and may leave goroutines running for a time after the Wait call.
  490. controller.pendingConns.CloseAll()
  491. close(controller.stopEstablishingBroadcast)
  492. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  493. // (as it may be sending to that channel).
  494. controller.establishWaitGroup.Wait()
  495. controller.isEstablishing = false
  496. controller.establishWaitGroup = nil
  497. controller.stopEstablishingBroadcast = nil
  498. controller.candidateServerEntries = nil
  499. }
  500. // establishCandidateGenerator populates the candidate queue with server entries
  501. // from the data store. Server entries are iterated in rank order, so that promoted
  502. // servers with higher rank are priority candidates.
  503. func (controller *Controller) establishCandidateGenerator() {
  504. defer controller.establishWaitGroup.Done()
  505. iterator, err := NewServerEntryIterator(
  506. controller.config.EgressRegion, controller.config.TunnelProtocol)
  507. if err != nil {
  508. Notice(NOTICE_ALERT, "failed to iterate over candidates: %s", err)
  509. controller.SignalFailure()
  510. return
  511. }
  512. defer iterator.Close()
  513. loop:
  514. for {
  515. for {
  516. serverEntry, err := iterator.Next()
  517. if err != nil {
  518. Notice(NOTICE_ALERT, "failed to get next candidate: %s", err)
  519. controller.SignalFailure()
  520. break loop
  521. }
  522. if serverEntry == nil {
  523. // Completed this iteration
  524. break
  525. }
  526. select {
  527. case controller.candidateServerEntries <- serverEntry:
  528. case <-controller.stopEstablishingBroadcast:
  529. break loop
  530. case <-controller.shutdownBroadcast:
  531. break loop
  532. }
  533. }
  534. iterator.Reset()
  535. // After a complete iteration of candidate servers, pause before iterating again.
  536. // This helps avoid some busy wait loop conditions, and also allows some time for
  537. // network conditions to change.
  538. timeout := time.After(ESTABLISH_TUNNEL_PAUSE_PERIOD)
  539. select {
  540. case <-timeout:
  541. // Retry iterating
  542. case <-controller.stopEstablishingBroadcast:
  543. break loop
  544. case <-controller.shutdownBroadcast:
  545. break loop
  546. }
  547. }
  548. close(controller.candidateServerEntries)
  549. Notice(NOTICE_INFO, "stopped candidate generator")
  550. }
  551. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  552. // a connection to the tunnel server, and delivers the established tunnel to a channel.
  553. func (controller *Controller) establishTunnelWorker() {
  554. defer controller.establishWaitGroup.Done()
  555. for serverEntry := range controller.candidateServerEntries {
  556. // Note: don't receive from candidateQueue and broadcastStopWorkers in the same
  557. // select, since we want to prioritize receiving the stop signal
  558. select {
  559. case <-controller.stopEstablishingBroadcast:
  560. return
  561. default:
  562. }
  563. // There may already be a tunnel to this candidate. If so, skip it.
  564. if controller.isActiveTunnelServerEntry(serverEntry) {
  565. continue
  566. }
  567. tunnel, err := EstablishTunnel(
  568. controller.config, controller.pendingConns, serverEntry)
  569. if err != nil {
  570. // TODO: distingush case where conn is interrupted?
  571. Notice(NOTICE_INFO, "failed to connect to %s: %s", serverEntry.IpAddress, err)
  572. } else {
  573. // Don't block. Assumes the receiver has a buffer large enough for
  574. // the number of desired tunnels. If there's no room, the tunnel must
  575. // not be required so it's discarded.
  576. select {
  577. case controller.establishedTunnels <- tunnel:
  578. default:
  579. controller.discardTunnel(tunnel)
  580. }
  581. }
  582. }
  583. Notice(NOTICE_INFO, "stopped establish worker")
  584. }