controller.go 24 KB

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