controller.go 40 KB

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