controller.go 26 KB

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