controller.go 33 KB

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