controller.go 24 KB

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