controller.go 32 KB

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