controller.go 33 KB

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