controller.go 37 KB

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