controller.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  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. // session is nil when DisableApi is set
  275. if controller.config.DisableApi {
  276. return
  277. }
  278. // Start the connected reporter after the first tunnel is established.
  279. // Concurrency note: only the runTunnels goroutine may access startedConnectedReporter.
  280. if !controller.startedConnectedReporter {
  281. controller.startedConnectedReporter = true
  282. controller.runWaitGroup.Add(1)
  283. go controller.connectedReporter()
  284. }
  285. }
  286. // upgradeDownloader makes periodic attemps to complete a client upgrade
  287. // download. DownloadUpgrade() is resumable, so each attempt has potential for
  288. // getting closer to completion, even in conditions where the download or
  289. // tunnel is repeatedly interrupted.
  290. // Once the download is complete, the downloader exits and is not run again:
  291. // We're assuming that the upgrade will be applied and the entire system
  292. // restarted before another upgrade is to be downloaded.
  293. func (controller *Controller) upgradeDownloader(clientUpgradeVersion string) {
  294. defer controller.runWaitGroup.Done()
  295. loop:
  296. for {
  297. // Pick any active tunnel and make the next download attempt. No error
  298. // is logged if there's no active tunnel, as that's not an unexpected condition.
  299. tunnel := controller.getNextActiveTunnel()
  300. if tunnel != nil {
  301. err := DownloadUpgrade(controller.config, clientUpgradeVersion, tunnel)
  302. if err == nil {
  303. break loop
  304. }
  305. NoticeAlert("upgrade download failed: ", err)
  306. }
  307. timeout := time.After(DOWNLOAD_UPGRADE_RETRY_PAUSE_PERIOD)
  308. select {
  309. case <-timeout:
  310. // Make another download attempt
  311. case <-controller.shutdownBroadcast:
  312. break loop
  313. }
  314. }
  315. NoticeInfo("exiting upgrade downloader")
  316. }
  317. func (controller *Controller) startClientUpgradeDownloader(session *Session) {
  318. // session is nil when DisableApi is set
  319. if controller.config.DisableApi {
  320. return
  321. }
  322. if controller.config.UpgradeDownloadUrl == "" ||
  323. controller.config.UpgradeDownloadFilename == "" {
  324. // No upgrade is desired
  325. return
  326. }
  327. if session.clientUpgradeVersion == "" {
  328. // No upgrade is offered
  329. return
  330. }
  331. // Start the client upgrade downloaded after the first tunnel is established.
  332. // Concurrency note: only the runTunnels goroutine may access startClientUpgradeDownloader.
  333. if !controller.startedUpgradeDownloader {
  334. controller.startedUpgradeDownloader = true
  335. controller.runWaitGroup.Add(1)
  336. go controller.upgradeDownloader(session.clientUpgradeVersion)
  337. }
  338. }
  339. // runTunnels is the controller tunnel management main loop. It starts and stops
  340. // establishing tunnels based on the target tunnel pool size and the current size
  341. // of the pool. Tunnels are established asynchronously using worker goroutines.
  342. //
  343. // When there are no server entries for the target region/protocol, the
  344. // establishCandidateGenerator will yield no candidates and wait before
  345. // trying again. In the meantime, a remote server entry fetch may supply
  346. // valid candidates.
  347. //
  348. // When a tunnel is established, it's added to the active pool. The tunnel's
  349. // operateTunnel goroutine monitors the tunnel.
  350. //
  351. // When a tunnel fails, it's removed from the pool and the establish process is
  352. // restarted to fill the pool.
  353. func (controller *Controller) runTunnels() {
  354. defer controller.runWaitGroup.Done()
  355. // Start running
  356. controller.startEstablishing()
  357. loop:
  358. for {
  359. select {
  360. case failedTunnel := <-controller.failedTunnels:
  361. NoticeAlert("tunnel failed: %s", failedTunnel.serverEntry.IpAddress)
  362. controller.terminateTunnel(failedTunnel)
  363. // Note: we make this extra check to ensure the shutdown signal takes priority
  364. // and that we do not start establishing. Critically, startEstablishing() calls
  365. // establishPendingConns.Reset() which clears the closed flag in
  366. // establishPendingConns; this causes the pendingConns.Add() within
  367. // interruptibleTCPDial to succeed instead of aborting, and the result
  368. // is that it's possible for establish goroutines to run all the way through
  369. // NewSession before being discarded... delaying shutdown.
  370. select {
  371. case <-controller.shutdownBroadcast:
  372. break loop
  373. default:
  374. }
  375. controller.classifyImpairedProtocol(failedTunnel)
  376. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing
  377. // and access isEstablishing.
  378. if !controller.isEstablishing {
  379. controller.startEstablishing()
  380. }
  381. // !TODO! design issue: might not be enough server entries with region/caps to ever fill tunnel slots
  382. // solution(?) target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  383. case establishedTunnel := <-controller.establishedTunnels:
  384. if controller.registerTunnel(establishedTunnel) {
  385. NoticeActiveTunnel(establishedTunnel.serverEntry.IpAddress, establishedTunnel.protocol)
  386. } else {
  387. controller.discardTunnel(establishedTunnel)
  388. }
  389. if controller.isFullyEstablished() {
  390. controller.stopEstablishing()
  391. }
  392. controller.startConnectedReporter()
  393. controller.startClientUpgradeDownloader(establishedTunnel.session)
  394. case <-controller.shutdownBroadcast:
  395. break loop
  396. }
  397. }
  398. // Stop running
  399. controller.stopEstablishing()
  400. controller.terminateAllTunnels()
  401. // Drain tunnel channels
  402. close(controller.establishedTunnels)
  403. for tunnel := range controller.establishedTunnels {
  404. controller.discardTunnel(tunnel)
  405. }
  406. close(controller.failedTunnels)
  407. for tunnel := range controller.failedTunnels {
  408. controller.discardTunnel(tunnel)
  409. }
  410. NoticeInfo("exiting run tunnels")
  411. }
  412. // classifyImpairedProtocol tracks "impaired" protocol classifications for failed
  413. // tunnels. A protocol is classified as impaired if a tunnel using that protocol
  414. // fails, repeatedly, shortly after the start of the session. During tunnel
  415. // establishment, impaired protocols are briefly skipped.
  416. //
  417. // One purpose of this measure is to defend against an attack where the adversary,
  418. // for example, tags an OSSH TCP connection as an "unidentified" protocol; allows
  419. // it to connect; but then kills the underlying TCP connection after a short time.
  420. // Since OSSH has less latency than other protocols that may bypass an "unidentified"
  421. // filter, these other protocols might never be selected for use.
  422. //
  423. // Concurrency note: only the runTunnels() goroutine may call classifyImpairedProtocol
  424. func (controller *Controller) classifyImpairedProtocol(failedTunnel *Tunnel) {
  425. if failedTunnel.sessionStartTime.Add(IMPAIRED_PROTOCOL_CLASSIFICATION_DURATION).After(time.Now()) {
  426. controller.impairedProtocolClassification[failedTunnel.protocol] += 1
  427. } else {
  428. controller.impairedProtocolClassification[failedTunnel.protocol] = 0
  429. }
  430. if len(controller.getImpairedProtocols()) == len(SupportedTunnelProtocols) {
  431. // Reset classification if all protocols are classified as impaired as
  432. // the network situation (or attack) may not be protocol-specific.
  433. // TODO: compare against count of distinct supported protocols for
  434. // current known server entries.
  435. controller.impairedProtocolClassification = make(map[string]int)
  436. }
  437. }
  438. // getImpairedProtocols returns a list of protocols that have sufficient
  439. // classifications to be considered impaired protocols.
  440. //
  441. // Concurrency note: only the runTunnels() goroutine may call getImpairedProtocols
  442. func (controller *Controller) getImpairedProtocols() []string {
  443. if len(controller.impairedProtocolClassification) > 0 {
  444. NoticeInfo("impaired protocols: %+v", controller.impairedProtocolClassification)
  445. }
  446. impairedProtocols := make([]string, 0)
  447. for protocol, count := range controller.impairedProtocolClassification {
  448. if count >= IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD {
  449. impairedProtocols = append(impairedProtocols, protocol)
  450. }
  451. }
  452. return impairedProtocols
  453. }
  454. // SignalTunnelFailure implements the TunnelOwner interface. This function
  455. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  456. // has failed. The Controller will signal runTunnels to create a new
  457. // tunnel and/or remove the tunnel from the list of active tunnels.
  458. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  459. // Don't block. Assumes the receiver has a buffer large enough for
  460. // the typical number of operated tunnels. In case there's no room,
  461. // terminate the tunnel (runTunnels won't get a signal in this case,
  462. // but the tunnel will be removed from the list of active tunnels).
  463. select {
  464. case controller.failedTunnels <- tunnel:
  465. default:
  466. controller.terminateTunnel(tunnel)
  467. }
  468. }
  469. // discardTunnel disposes of a successful connection that is no longer required.
  470. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  471. NoticeInfo("discard tunnel: %s", tunnel.serverEntry.IpAddress)
  472. // TODO: not calling PromoteServerEntry, since that would rank the
  473. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  474. // be promoted (since it connects), but with lower rank than all active
  475. // tunnels?
  476. tunnel.Close()
  477. }
  478. // registerTunnel adds the connected tunnel to the pool of active tunnels
  479. // which are candidates for port forwarding. Returns true if the pool has an
  480. // empty slot and false if the pool is full (caller should discard the tunnel).
  481. func (controller *Controller) registerTunnel(tunnel *Tunnel) bool {
  482. controller.tunnelMutex.Lock()
  483. defer controller.tunnelMutex.Unlock()
  484. if len(controller.tunnels) >= controller.config.TunnelPoolSize {
  485. return false
  486. }
  487. // Perform a final check just in case we've established
  488. // a duplicate connection.
  489. for _, activeTunnel := range controller.tunnels {
  490. if activeTunnel.serverEntry.IpAddress == tunnel.serverEntry.IpAddress {
  491. NoticeAlert("duplicate tunnel: %s", tunnel.serverEntry.IpAddress)
  492. return false
  493. }
  494. }
  495. controller.establishedOnce = true
  496. controller.tunnels = append(controller.tunnels, tunnel)
  497. NoticeTunnels(len(controller.tunnels))
  498. // The split tunnel classifier is started once the first tunnel is
  499. // established. This first tunnel is passed in to be used to make
  500. // the routes data request.
  501. // A long-running controller may run while the host device is present
  502. // in different regions. In this case, we want the split tunnel logic
  503. // to switch to routes for new regions and not classify traffic based
  504. // on routes installed for older regions.
  505. // We assume that when regions change, the host network will also
  506. // change, and so all tunnels will fail and be re-established. Under
  507. // that assumption, the classifier will be re-Start()-ed here when
  508. // the region has changed.
  509. if len(controller.tunnels) == 1 {
  510. controller.splitTunnelClassifier.Start(tunnel)
  511. }
  512. return true
  513. }
  514. // hasEstablishedOnce indicates if at least one active tunnel has
  515. // been established up to this point. This is regardeless of how many
  516. // tunnels are presently active.
  517. func (controller *Controller) hasEstablishedOnce() bool {
  518. controller.tunnelMutex.Lock()
  519. defer controller.tunnelMutex.Unlock()
  520. return controller.establishedOnce
  521. }
  522. // isFullyEstablished indicates if the pool of active tunnels is full.
  523. func (controller *Controller) isFullyEstablished() bool {
  524. controller.tunnelMutex.Lock()
  525. defer controller.tunnelMutex.Unlock()
  526. return len(controller.tunnels) >= controller.config.TunnelPoolSize
  527. }
  528. // terminateTunnel removes a tunnel from the pool of active tunnels
  529. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  530. // is adjusted as required.
  531. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  532. controller.tunnelMutex.Lock()
  533. defer controller.tunnelMutex.Unlock()
  534. for index, activeTunnel := range controller.tunnels {
  535. if tunnel == activeTunnel {
  536. controller.tunnels = append(
  537. controller.tunnels[:index], controller.tunnels[index+1:]...)
  538. if controller.nextTunnel > index {
  539. controller.nextTunnel--
  540. }
  541. if controller.nextTunnel >= len(controller.tunnels) {
  542. controller.nextTunnel = 0
  543. }
  544. activeTunnel.Close()
  545. NoticeTunnels(len(controller.tunnels))
  546. break
  547. }
  548. }
  549. }
  550. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  551. // This is used when shutting down the controller.
  552. func (controller *Controller) terminateAllTunnels() {
  553. controller.tunnelMutex.Lock()
  554. defer controller.tunnelMutex.Unlock()
  555. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  556. // may take a few seconds to send a final status request. We only want
  557. // to wait as long as the single slowest tunnel.
  558. closeWaitGroup := new(sync.WaitGroup)
  559. closeWaitGroup.Add(len(controller.tunnels))
  560. for _, activeTunnel := range controller.tunnels {
  561. tunnel := activeTunnel
  562. go func() {
  563. defer closeWaitGroup.Done()
  564. tunnel.Close()
  565. }()
  566. }
  567. closeWaitGroup.Wait()
  568. controller.tunnels = make([]*Tunnel, 0)
  569. controller.nextTunnel = 0
  570. NoticeTunnels(len(controller.tunnels))
  571. }
  572. // getNextActiveTunnel returns the next tunnel from the pool of active
  573. // tunnels. Currently, tunnel selection order is simple round-robin.
  574. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  575. controller.tunnelMutex.Lock()
  576. defer controller.tunnelMutex.Unlock()
  577. for i := len(controller.tunnels); i > 0; i-- {
  578. tunnel = controller.tunnels[controller.nextTunnel]
  579. controller.nextTunnel =
  580. (controller.nextTunnel + 1) % len(controller.tunnels)
  581. return tunnel
  582. }
  583. return nil
  584. }
  585. // isActiveTunnelServerEntry is used to check if there's already
  586. // an existing tunnel to a candidate server.
  587. func (controller *Controller) isActiveTunnelServerEntry(serverEntry *ServerEntry) bool {
  588. controller.tunnelMutex.Lock()
  589. defer controller.tunnelMutex.Unlock()
  590. for _, activeTunnel := range controller.tunnels {
  591. if activeTunnel.serverEntry.IpAddress == serverEntry.IpAddress {
  592. return true
  593. }
  594. }
  595. return false
  596. }
  597. // Dial selects an active tunnel and establishes a port forward
  598. // connection through the selected tunnel. Failure to connect is considered
  599. // a port foward failure, for the purpose of monitoring tunnel health.
  600. func (controller *Controller) Dial(
  601. remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error) {
  602. tunnel := controller.getNextActiveTunnel()
  603. if tunnel == nil {
  604. return nil, ContextError(errors.New("no active tunnels"))
  605. }
  606. // Perform split tunnel classification when feature is enabled, and if the remote
  607. // address is classified as untunneled, dial directly.
  608. if !alwaysTunnel && controller.config.SplitTunnelDnsServer != "" {
  609. host, _, err := net.SplitHostPort(remoteAddr)
  610. if err != nil {
  611. return nil, ContextError(err)
  612. }
  613. // Note: a possible optimization, when split tunnel is active and IsUntunneled performs
  614. // a DNS resolution in order to make its classification, is to reuse that IP address in
  615. // the following Dials so they do not need to make their own resolutions. However, the
  616. // way this is currently implemented ensures that, e.g., DNS geo load balancing occurs
  617. // relative to the outbound network.
  618. if controller.splitTunnelClassifier.IsUntunneled(host) {
  619. // !TODO! track downstreamConn and close it when the DialTCP conn closes, as with tunnel.Dial conns?
  620. return DialTCP(remoteAddr, controller.untunneledDialConfig)
  621. }
  622. }
  623. tunneledConn, err := tunnel.Dial(remoteAddr, alwaysTunnel, downstreamConn)
  624. if err != nil {
  625. return nil, ContextError(err)
  626. }
  627. return tunneledConn, nil
  628. }
  629. // startEstablishing creates a pool of worker goroutines which will
  630. // attempt to establish tunnels to candidate servers. The candidates
  631. // are generated by another goroutine.
  632. func (controller *Controller) startEstablishing() {
  633. if controller.isEstablishing {
  634. return
  635. }
  636. NoticeInfo("start establishing")
  637. controller.isEstablishing = true
  638. controller.establishWaitGroup = new(sync.WaitGroup)
  639. controller.stopEstablishingBroadcast = make(chan struct{})
  640. controller.candidateServerEntries = make(chan *ServerEntry)
  641. controller.establishPendingConns.Reset()
  642. for i := 0; i < controller.config.ConnectionWorkerPoolSize; i++ {
  643. controller.establishWaitGroup.Add(1)
  644. go controller.establishTunnelWorker()
  645. }
  646. controller.establishWaitGroup.Add(1)
  647. go controller.establishCandidateGenerator(
  648. controller.getImpairedProtocols())
  649. }
  650. // stopEstablishing signals the establish goroutines to stop and waits
  651. // for the group to halt. pendingConns is used to interrupt any worker
  652. // blocked on a socket connect.
  653. func (controller *Controller) stopEstablishing() {
  654. if !controller.isEstablishing {
  655. return
  656. }
  657. NoticeInfo("stop establishing")
  658. close(controller.stopEstablishingBroadcast)
  659. // Note: interruptibleTCPClose doesn't really interrupt socket connects
  660. // and may leave goroutines running for a time after the Wait call.
  661. controller.establishPendingConns.CloseAll()
  662. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  663. // (as it may be sending to that channel).
  664. controller.establishWaitGroup.Wait()
  665. controller.isEstablishing = false
  666. controller.establishWaitGroup = nil
  667. controller.stopEstablishingBroadcast = nil
  668. controller.candidateServerEntries = nil
  669. }
  670. // establishCandidateGenerator populates the candidate queue with server entries
  671. // from the data store. Server entries are iterated in rank order, so that promoted
  672. // servers with higher rank are priority candidates.
  673. func (controller *Controller) establishCandidateGenerator(impairedProtocols []string) {
  674. defer controller.establishWaitGroup.Done()
  675. defer close(controller.candidateServerEntries)
  676. iterator, err := NewServerEntryIterator(controller.config)
  677. if err != nil {
  678. NoticeAlert("failed to iterate over candidates: %s", err)
  679. controller.SignalComponentFailure()
  680. return
  681. }
  682. defer iterator.Close()
  683. loop:
  684. // Repeat until stopped
  685. for i := 0; ; i++ {
  686. if !WaitForNetworkConnectivity(
  687. controller.config.NetworkConnectivityChecker,
  688. controller.stopEstablishingBroadcast,
  689. controller.shutdownBroadcast) {
  690. break loop
  691. }
  692. // Send each iterator server entry to the establish workers
  693. startTime := time.Now()
  694. for {
  695. serverEntry, err := iterator.Next()
  696. if err != nil {
  697. NoticeAlert("failed to get next candidate: %s", err)
  698. controller.SignalComponentFailure()
  699. break loop
  700. }
  701. if serverEntry == nil {
  702. // Completed this iteration
  703. break
  704. }
  705. // Disable impaired protocols. This is only done for the
  706. // first iteration of the ESTABLISH_TUNNEL_WORK_TIME
  707. // loop since (a) one iteration should be sufficient to
  708. // evade the attack; (b) there's a good chance of false
  709. // positives (such as short session durations due to network
  710. // hopping on a mobile device).
  711. // Impaired protocols logic is not applied when
  712. // config.TunnelProtocol is specified.
  713. // The edited serverEntry is temporary copy which is not
  714. // stored or reused.
  715. if i == 0 && controller.config.TunnelProtocol == "" {
  716. serverEntry.DisableImpairedProtocols(impairedProtocols)
  717. if len(serverEntry.GetSupportedProtocols()) == 0 {
  718. // Skip this server entry, as it has no supported
  719. // protocols after disabling the impaired ones
  720. // TODO: modify ServerEntryIterator to skip these?
  721. continue
  722. }
  723. }
  724. // TODO: here we could generate multiple candidates from the
  725. // server entry when there are many MeekFrontingAddresses.
  726. select {
  727. case controller.candidateServerEntries <- serverEntry:
  728. case <-controller.stopEstablishingBroadcast:
  729. break loop
  730. case <-controller.shutdownBroadcast:
  731. break loop
  732. }
  733. if time.Now().After(startTime.Add(ESTABLISH_TUNNEL_WORK_TIME)) {
  734. // Start over, after a brief pause, with a new shuffle of the server
  735. // entries, and potentially some newly fetched server entries.
  736. break
  737. }
  738. }
  739. // Free up resources now, but don't reset until after the pause.
  740. iterator.Close()
  741. // Trigger a fetch remote server list, since we may have failed to
  742. // connect with all known servers. Don't block sending signal, since
  743. // this signal may have already been sent.
  744. // Don't wait for fetch remote to succeed, since it may fail and
  745. // enter a retry loop and we're better off trying more known servers.
  746. // TODO: synchronize the fetch response, so it can be incorporated
  747. // into the server entry iterator as soon as available.
  748. select {
  749. case controller.signalFetchRemoteServerList <- *new(struct{}):
  750. default:
  751. }
  752. // After a complete iteration of candidate servers, pause before iterating again.
  753. // This helps avoid some busy wait loop conditions, and also allows some time for
  754. // network conditions to change. Also allows for fetch remote to complete,
  755. // in typical conditions (it isn't strictly necessary to wait for this, there will
  756. // be more rounds if required).
  757. timeout := time.After(ESTABLISH_TUNNEL_PAUSE_PERIOD)
  758. select {
  759. case <-timeout:
  760. // Retry iterating
  761. case <-controller.stopEstablishingBroadcast:
  762. break loop
  763. case <-controller.shutdownBroadcast:
  764. break loop
  765. }
  766. iterator.Reset()
  767. }
  768. NoticeInfo("stopped candidate generator")
  769. }
  770. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  771. // a connection to the tunnel server, and delivers the established tunnel to a channel.
  772. func (controller *Controller) establishTunnelWorker() {
  773. defer controller.establishWaitGroup.Done()
  774. loop:
  775. for serverEntry := range controller.candidateServerEntries {
  776. // Note: don't receive from candidateServerEntries and stopEstablishingBroadcast
  777. // in the same select, since we want to prioritize receiving the stop signal
  778. if controller.isStopEstablishingBroadcast() {
  779. break loop
  780. }
  781. // There may already be a tunnel to this candidate. If so, skip it.
  782. if controller.isActiveTunnelServerEntry(serverEntry) {
  783. continue
  784. }
  785. tunnel, err := EstablishTunnel(
  786. controller.config,
  787. controller.sessionId,
  788. controller.establishPendingConns,
  789. serverEntry,
  790. controller) // TunnelOwner
  791. if err != nil {
  792. // Before emitting error, check if establish interrupted, in which
  793. // case the error is noise.
  794. if controller.isStopEstablishingBroadcast() {
  795. break loop
  796. }
  797. NoticeInfo("failed to connect to %s: %s", serverEntry.IpAddress, err)
  798. continue
  799. }
  800. // Deliver established tunnel.
  801. // Don't block. Assumes the receiver has a buffer large enough for
  802. // the number of desired tunnels. If there's no room, the tunnel must
  803. // not be required so it's discarded.
  804. select {
  805. case controller.establishedTunnels <- tunnel:
  806. default:
  807. controller.discardTunnel(tunnel)
  808. }
  809. }
  810. NoticeInfo("stopped establish worker")
  811. }
  812. func (controller *Controller) isStopEstablishingBroadcast() bool {
  813. select {
  814. case <-controller.stopEstablishingBroadcast:
  815. return true
  816. default:
  817. }
  818. return false
  819. }