controller.go 40 KB

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