controller.go 37 KB

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