controller.go 24 KB

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