controller.go 42 KB

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