controller.go 33 KB

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