controller.go 38 KB

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