controller.go 37 KB

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