controller.go 37 KB

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