controller.go 32 KB

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