controller.go 40 KB

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