controller.go 32 KB

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