controller.go 38 KB

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