controller.go 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  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. "fmt"
  27. "math/rand"
  28. "net"
  29. "sync"
  30. "time"
  31. "github.com/Psiphon-Inc/goarista/monotime"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  35. )
  36. // Controller is a tunnel lifecycle coordinator. It manages lists of servers to
  37. // connect to; establishes and monitors tunnels; and runs local proxies which
  38. // route traffic through the tunnels.
  39. type Controller struct {
  40. config *Config
  41. sessionId string
  42. componentFailureSignal chan struct{}
  43. shutdownBroadcast chan struct{}
  44. runWaitGroup *sync.WaitGroup
  45. establishedTunnels chan *Tunnel
  46. failedTunnels chan *Tunnel
  47. tunnelMutex sync.Mutex
  48. establishedOnce bool
  49. tunnels []*Tunnel
  50. nextTunnel int
  51. startedConnectedReporter bool
  52. isEstablishing bool
  53. concurrentEstablishTunnelsMutex sync.Mutex
  54. concurrentEstablishTunnels int
  55. concurrentMeekEstablishTunnels int
  56. peakConcurrentEstablishTunnels int
  57. peakConcurrentMeekEstablishTunnels int
  58. establishWaitGroup *sync.WaitGroup
  59. stopEstablishingBroadcast chan struct{}
  60. candidateServerEntries chan *candidateServerEntry
  61. establishPendingConns *common.Conns
  62. untunneledPendingConns *common.Conns
  63. untunneledDialConfig *DialConfig
  64. splitTunnelClassifier *SplitTunnelClassifier
  65. signalFetchCommonRemoteServerList chan struct{}
  66. signalFetchObfuscatedServerLists chan struct{}
  67. signalDownloadUpgrade chan string
  68. impairedProtocolClassification map[string]int
  69. signalReportConnected chan struct{}
  70. serverAffinityDoneBroadcast chan struct{}
  71. newClientVerificationPayload chan string
  72. packetTunnelClient *tun.Client
  73. packetTunnelTransport *PacketTunnelTransport
  74. }
  75. type candidateServerEntry struct {
  76. serverEntry *protocol.ServerEntry
  77. isServerAffinityCandidate bool
  78. adjustedEstablishStartTime monotime.Time
  79. }
  80. // NewController initializes a new controller.
  81. func NewController(config *Config) (controller *Controller, err error) {
  82. // Needed by regen, at least
  83. rand.Seed(int64(time.Now().Nanosecond()))
  84. // Generate a session ID for the Psiphon server API. This session ID is
  85. // used across all tunnels established by the controller.
  86. sessionId, err := MakeSessionId()
  87. if err != nil {
  88. return nil, common.ContextError(err)
  89. }
  90. NoticeSessionId(sessionId)
  91. // untunneledPendingConns may be used to interrupt the fetch remote server list
  92. // request and other untunneled connection establishments. BindToDevice may be
  93. // used to exclude these requests and connection from VPN routing.
  94. // TODO: fetch remote server list and untunneled upgrade download should remove
  95. // their completed conns from untunneledPendingConns.
  96. untunneledPendingConns := new(common.Conns)
  97. untunneledDialConfig := &DialConfig{
  98. UpstreamProxyUrl: config.UpstreamProxyUrl,
  99. CustomHeaders: config.CustomHeaders,
  100. PendingConns: untunneledPendingConns,
  101. DeviceBinder: config.DeviceBinder,
  102. DnsServerGetter: config.DnsServerGetter,
  103. IPv6Synthesizer: config.IPv6Synthesizer,
  104. UseIndistinguishableTLS: config.UseIndistinguishableTLS,
  105. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  106. DeviceRegion: config.DeviceRegion,
  107. }
  108. controller = &Controller{
  109. config: config,
  110. sessionId: sessionId,
  111. // componentFailureSignal receives a signal from a component (including socks and
  112. // http local proxies) if they unexpectedly fail. Senders should not block.
  113. // Buffer allows at least one stop signal to be sent before there is a receiver.
  114. componentFailureSignal: make(chan struct{}, 1),
  115. shutdownBroadcast: make(chan struct{}),
  116. runWaitGroup: new(sync.WaitGroup),
  117. // establishedTunnels and failedTunnels buffer sizes are large enough to
  118. // receive full pools of tunnels without blocking. Senders should not block.
  119. establishedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  120. failedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  121. tunnels: make([]*Tunnel, 0),
  122. establishedOnce: false,
  123. startedConnectedReporter: false,
  124. isEstablishing: false,
  125. establishPendingConns: new(common.Conns),
  126. untunneledPendingConns: untunneledPendingConns,
  127. untunneledDialConfig: untunneledDialConfig,
  128. impairedProtocolClassification: make(map[string]int),
  129. // TODO: Add a buffer of 1 so we don't miss a signal while receiver is
  130. // starting? Trade-off is potential back-to-back fetch remotes. As-is,
  131. // establish will eventually signal another fetch remote.
  132. signalFetchCommonRemoteServerList: make(chan struct{}),
  133. signalFetchObfuscatedServerLists: make(chan struct{}),
  134. signalDownloadUpgrade: make(chan string),
  135. signalReportConnected: make(chan struct{}),
  136. // Buffer allows SetClientVerificationPayloadForActiveTunnels to submit one
  137. // new payload without blocking or dropping it.
  138. newClientVerificationPayload: make(chan string, 1),
  139. }
  140. controller.splitTunnelClassifier = NewSplitTunnelClassifier(config, controller)
  141. if config.PacketTunnelTunFileDescriptor > 0 {
  142. // Run a packet tunnel client. The lifetime of the tun.Client is the
  143. // lifetime of the Controller, so it exists across tunnel establishments
  144. // and reestablishments. The PacketTunnelTransport provides a layer
  145. // that presents a continuosuly existing transport to the tun.Client;
  146. // it's set to use new SSH channels after new SSH tunnel establishes.
  147. packetTunnelTransport := NewPacketTunnelTransport()
  148. packetTunnelClient, err := tun.NewClient(&tun.ClientConfig{
  149. Logger: NoticeCommonLogger(),
  150. TunFileDescriptor: config.PacketTunnelTunFileDescriptor,
  151. Transport: packetTunnelTransport,
  152. })
  153. if err != nil {
  154. return nil, common.ContextError(err)
  155. }
  156. controller.packetTunnelClient = packetTunnelClient
  157. controller.packetTunnelTransport = packetTunnelTransport
  158. }
  159. return controller, nil
  160. }
  161. // Run executes the controller. It launches components and then monitors
  162. // for a shutdown signal; after receiving the signal it shuts down the
  163. // controller.
  164. // The components include:
  165. // - the periodic remote server list fetcher
  166. // - the connected reporter
  167. // - the tunnel manager
  168. // - a local SOCKS proxy that port forwards through the pool of tunnels
  169. // - a local HTTP proxy that port forwards through the pool of tunnels
  170. func (controller *Controller) Run(shutdownBroadcast <-chan struct{}) {
  171. ReportAvailableRegions()
  172. // Start components
  173. // TODO: IPv6 support
  174. var listenIP string
  175. if controller.config.ListenInterface == "" {
  176. listenIP = "127.0.0.1"
  177. } else if controller.config.ListenInterface == "any" {
  178. listenIP = "0.0.0.0"
  179. } else {
  180. IPv4Address, _, err := common.GetInterfaceIPAddresses(controller.config.ListenInterface)
  181. if err == nil && IPv4Address == nil {
  182. err = fmt.Errorf("no IPv4 address for interface %s", controller.config.ListenInterface)
  183. }
  184. if err != nil {
  185. NoticeError("error getting listener IP: %s", err)
  186. return
  187. }
  188. listenIP = IPv4Address.String()
  189. }
  190. if !controller.config.DisableLocalSocksProxy {
  191. socksProxy, err := NewSocksProxy(controller.config, controller, listenIP)
  192. if err != nil {
  193. NoticeAlert("error initializing local SOCKS proxy: %s", err)
  194. return
  195. }
  196. defer socksProxy.Close()
  197. }
  198. if !controller.config.DisableLocalHTTPProxy {
  199. httpProxy, err := NewHttpProxy(
  200. controller.config, controller.untunneledDialConfig, controller, listenIP)
  201. if err != nil {
  202. NoticeAlert("error initializing local HTTP proxy: %s", err)
  203. return
  204. }
  205. defer httpProxy.Close()
  206. }
  207. if !controller.config.DisableRemoteServerListFetcher {
  208. retryPeriod := time.Duration(
  209. *controller.config.FetchRemoteServerListRetryPeriodSeconds) * time.Second
  210. if controller.config.RemoteServerListURLs != nil {
  211. controller.runWaitGroup.Add(1)
  212. go controller.remoteServerListFetcher(
  213. "common",
  214. FetchCommonRemoteServerList,
  215. controller.signalFetchCommonRemoteServerList,
  216. retryPeriod,
  217. FETCH_REMOTE_SERVER_LIST_STALE_PERIOD)
  218. }
  219. if controller.config.ObfuscatedServerListRootURLs != nil {
  220. controller.runWaitGroup.Add(1)
  221. go controller.remoteServerListFetcher(
  222. "obfuscated",
  223. FetchObfuscatedServerLists,
  224. controller.signalFetchObfuscatedServerLists,
  225. retryPeriod,
  226. FETCH_REMOTE_SERVER_LIST_STALE_PERIOD)
  227. }
  228. }
  229. if controller.config.UpgradeDownloadURLs != nil {
  230. controller.runWaitGroup.Add(1)
  231. go controller.upgradeDownloader()
  232. }
  233. /// Note: the connected reporter isn't started until a tunnel is
  234. // established
  235. controller.runWaitGroup.Add(1)
  236. go controller.runTunnels()
  237. if *controller.config.EstablishTunnelTimeoutSeconds != 0 {
  238. controller.runWaitGroup.Add(1)
  239. go controller.establishTunnelWatcher()
  240. }
  241. if controller.packetTunnelClient != nil {
  242. controller.packetTunnelClient.Start()
  243. }
  244. // Wait while running
  245. select {
  246. case <-shutdownBroadcast:
  247. NoticeInfo("controller shutdown by request")
  248. case <-controller.componentFailureSignal:
  249. NoticeAlert("controller shutdown due to component failure")
  250. }
  251. close(controller.shutdownBroadcast)
  252. if controller.packetTunnelClient != nil {
  253. controller.packetTunnelClient.Stop()
  254. }
  255. // Interrupts and stops establish workers blocking on
  256. // tunnel establishment network operations.
  257. controller.establishPendingConns.CloseAll()
  258. // Interrupts and stops workers blocking on untunneled
  259. // network operations. This includes fetch remote server
  260. // list and untunneled uprade download.
  261. // Note: this doesn't interrupt the final, untunneled status
  262. // requests started in operateTunnel after shutdownBroadcast.
  263. // This is by design -- we want to give these requests a short
  264. // timer period to succeed and deliver stats. These particular
  265. // requests opt out of untunneledPendingConns and use the
  266. // PSIPHON_API_SHUTDOWN_SERVER_TIMEOUT timeout (see
  267. // doUntunneledStatusRequest).
  268. controller.untunneledPendingConns.CloseAll()
  269. // Now with all workers signaled to stop and with all
  270. // blocking network operations interrupted, wait for
  271. // all workers to terminate.
  272. controller.runWaitGroup.Wait()
  273. controller.splitTunnelClassifier.Shutdown()
  274. NoticeInfo("exiting controller")
  275. NoticeExiting()
  276. }
  277. // SignalComponentFailure notifies the controller that an associated component has failed.
  278. // This will terminate the controller.
  279. func (controller *Controller) SignalComponentFailure() {
  280. select {
  281. case controller.componentFailureSignal <- *new(struct{}):
  282. default:
  283. }
  284. }
  285. // SetClientVerificationPayloadForActiveTunnels sets the client verification
  286. // payload that is to be sent in client verification requests to all established
  287. // tunnels.
  288. //
  289. // Client verification is used to verify that the client is a
  290. // valid Psiphon client, which will determine how the server treats
  291. // the client traffic. The proof-of-validity is platform-specific
  292. // and the payload is opaque to this function but assumed to be JSON.
  293. //
  294. // Since, in some cases, verification payload cannot be determined until
  295. // after tunnel-core starts, the payload cannot be simply specified in
  296. // the Config.
  297. //
  298. // SetClientVerificationPayloadForActiveTunnels will not block enqueuing a new verification
  299. // payload. One new payload can be enqueued, after which additional payloads
  300. // will be dropped if a payload is still enqueued.
  301. func (controller *Controller) SetClientVerificationPayloadForActiveTunnels(clientVerificationPayload string) {
  302. select {
  303. case controller.newClientVerificationPayload <- clientVerificationPayload:
  304. default:
  305. }
  306. }
  307. // remoteServerListFetcher fetches an out-of-band list of server entries
  308. // for more tunnel candidates. It fetches when signalled, with retries
  309. // on failure.
  310. func (controller *Controller) remoteServerListFetcher(
  311. name string,
  312. fetcher RemoteServerListFetcher,
  313. signal <-chan struct{},
  314. retryPeriod, stalePeriod time.Duration) {
  315. defer controller.runWaitGroup.Done()
  316. var lastFetchTime monotime.Time
  317. fetcherLoop:
  318. for {
  319. // Wait for a signal before fetching
  320. select {
  321. case <-signal:
  322. case <-controller.shutdownBroadcast:
  323. break fetcherLoop
  324. }
  325. // Skip fetch entirely (i.e., send no request at all, even when ETag would save
  326. // on response size) when a recent fetch was successful
  327. if lastFetchTime != 0 &&
  328. lastFetchTime.Add(stalePeriod).After(monotime.Now()) {
  329. continue
  330. }
  331. retryLoop:
  332. for attempt := 0; ; attempt++ {
  333. // Don't attempt to fetch while there is no network connectivity,
  334. // to avoid alert notice noise.
  335. if !WaitForNetworkConnectivity(
  336. controller.config.NetworkConnectivityChecker,
  337. controller.shutdownBroadcast) {
  338. break fetcherLoop
  339. }
  340. // Pick any active tunnel and make the next fetch attempt. If there's
  341. // no active tunnel, the untunneledDialConfig will be used.
  342. tunnel := controller.getNextActiveTunnel()
  343. err := fetcher(
  344. controller.config,
  345. attempt,
  346. tunnel,
  347. controller.untunneledDialConfig)
  348. if err == nil {
  349. lastFetchTime = monotime.Now()
  350. break retryLoop
  351. }
  352. NoticeAlert("failed to fetch %s remote server list: %s", name, err)
  353. timeout := time.After(retryPeriod)
  354. select {
  355. case <-timeout:
  356. case <-controller.shutdownBroadcast:
  357. break fetcherLoop
  358. }
  359. }
  360. }
  361. NoticeInfo("exiting %s remote server list fetcher", name)
  362. }
  363. // establishTunnelWatcher terminates the controller if a tunnel
  364. // has not been established in the configured time period. This
  365. // is regardless of how many tunnels are presently active -- meaning
  366. // that if an active tunnel was established and lost the controller
  367. // is left running (to re-establish).
  368. func (controller *Controller) establishTunnelWatcher() {
  369. defer controller.runWaitGroup.Done()
  370. timeout := time.After(
  371. time.Duration(*controller.config.EstablishTunnelTimeoutSeconds) * time.Second)
  372. select {
  373. case <-timeout:
  374. if !controller.hasEstablishedOnce() {
  375. NoticeAlert("failed to establish tunnel before timeout")
  376. controller.SignalComponentFailure()
  377. }
  378. case <-controller.shutdownBroadcast:
  379. }
  380. NoticeInfo("exiting establish tunnel watcher")
  381. }
  382. // connectedReporter sends periodic "connected" requests to the Psiphon API.
  383. // These requests are for server-side unique user stats calculation. See the
  384. // comment in DoConnectedRequest for a description of the request mechanism.
  385. // To ensure we don't over- or under-count unique users, only one connected
  386. // request is made across all simultaneous multi-tunnels; and the connected
  387. // request is repeated periodically for very long-lived tunnels.
  388. // The signalReportConnected mechanism is used to trigger another connected
  389. // request immediately after a reconnect.
  390. func (controller *Controller) connectedReporter() {
  391. defer controller.runWaitGroup.Done()
  392. loop:
  393. for {
  394. // Pick any active tunnel and make the next connected request. No error
  395. // is logged if there's no active tunnel, as that's not an unexpected condition.
  396. reported := false
  397. tunnel := controller.getNextActiveTunnel()
  398. if tunnel != nil {
  399. err := tunnel.serverContext.DoConnectedRequest()
  400. if err == nil {
  401. reported = true
  402. } else {
  403. NoticeAlert("failed to make connected request: %s", err)
  404. }
  405. }
  406. // Schedule the next connected request and wait.
  407. var duration time.Duration
  408. if reported {
  409. duration = PSIPHON_API_CONNECTED_REQUEST_PERIOD
  410. } else {
  411. duration = PSIPHON_API_CONNECTED_REQUEST_RETRY_PERIOD
  412. }
  413. timeout := time.After(duration)
  414. select {
  415. case <-controller.signalReportConnected:
  416. case <-timeout:
  417. // Make another connected request
  418. case <-controller.shutdownBroadcast:
  419. break loop
  420. }
  421. }
  422. NoticeInfo("exiting connected reporter")
  423. }
  424. func (controller *Controller) startOrSignalConnectedReporter() {
  425. // session is nil when DisableApi is set
  426. if controller.config.DisableApi {
  427. return
  428. }
  429. // Start the connected reporter after the first tunnel is established.
  430. // Concurrency note: only the runTunnels goroutine may access startedConnectedReporter.
  431. if !controller.startedConnectedReporter {
  432. controller.startedConnectedReporter = true
  433. controller.runWaitGroup.Add(1)
  434. go controller.connectedReporter()
  435. } else {
  436. select {
  437. case controller.signalReportConnected <- *new(struct{}):
  438. default:
  439. }
  440. }
  441. }
  442. // upgradeDownloader makes periodic attempts to complete a client upgrade
  443. // download. DownloadUpgrade() is resumable, so each attempt has potential for
  444. // getting closer to completion, even in conditions where the download or
  445. // tunnel is repeatedly interrupted.
  446. // An upgrade download is triggered by either a handshake response indicating
  447. // that a new version is available; or after failing to connect, in which case
  448. // it's useful to check, out-of-band, for an upgrade with new circumvention
  449. // capabilities.
  450. // Once the download operation completes successfully, the downloader exits
  451. // and is not run again: either there is not a newer version, or the upgrade
  452. // has been downloaded and is ready to be applied.
  453. // We're assuming that the upgrade will be applied and the entire system
  454. // restarted before another upgrade is to be downloaded.
  455. //
  456. // TODO: refactor upgrade downloader and remote server list fetcher to use
  457. // common code (including the resumable download routines).
  458. //
  459. func (controller *Controller) upgradeDownloader() {
  460. defer controller.runWaitGroup.Done()
  461. var lastDownloadTime monotime.Time
  462. downloadLoop:
  463. for {
  464. // Wait for a signal before downloading
  465. var handshakeVersion string
  466. select {
  467. case handshakeVersion = <-controller.signalDownloadUpgrade:
  468. case <-controller.shutdownBroadcast:
  469. break downloadLoop
  470. }
  471. // Unless handshake is explicitly advertizing a new version, skip
  472. // checking entirely when a recent download was successful.
  473. if handshakeVersion == "" &&
  474. lastDownloadTime != 0 &&
  475. lastDownloadTime.Add(DOWNLOAD_UPGRADE_STALE_PERIOD).After(monotime.Now()) {
  476. continue
  477. }
  478. retryLoop:
  479. for attempt := 0; ; attempt++ {
  480. // Don't attempt to download while there is no network connectivity,
  481. // to avoid alert notice noise.
  482. if !WaitForNetworkConnectivity(
  483. controller.config.NetworkConnectivityChecker,
  484. controller.shutdownBroadcast) {
  485. break downloadLoop
  486. }
  487. // Pick any active tunnel and make the next download attempt. If there's
  488. // no active tunnel, the untunneledDialConfig will be used.
  489. tunnel := controller.getNextActiveTunnel()
  490. err := DownloadUpgrade(
  491. controller.config,
  492. attempt,
  493. handshakeVersion,
  494. tunnel,
  495. controller.untunneledDialConfig)
  496. if err == nil {
  497. lastDownloadTime = monotime.Now()
  498. break retryLoop
  499. }
  500. NoticeAlert("failed to download upgrade: %s", err)
  501. timeout := time.After(
  502. time.Duration(*controller.config.DownloadUpgradeRetryPeriodSeconds) * time.Second)
  503. select {
  504. case <-timeout:
  505. case <-controller.shutdownBroadcast:
  506. break downloadLoop
  507. }
  508. }
  509. }
  510. NoticeInfo("exiting upgrade downloader")
  511. }
  512. // runTunnels is the controller tunnel management main loop. It starts and stops
  513. // establishing tunnels based on the target tunnel pool size and the current size
  514. // of the pool. Tunnels are established asynchronously using worker goroutines.
  515. //
  516. // When there are no server entries for the target region/protocol, the
  517. // establishCandidateGenerator will yield no candidates and wait before
  518. // trying again. In the meantime, a remote server entry fetch may supply
  519. // valid candidates.
  520. //
  521. // When a tunnel is established, it's added to the active pool. The tunnel's
  522. // operateTunnel goroutine monitors the tunnel.
  523. //
  524. // When a tunnel fails, it's removed from the pool and the establish process is
  525. // restarted to fill the pool.
  526. func (controller *Controller) runTunnels() {
  527. defer controller.runWaitGroup.Done()
  528. var clientVerificationPayload string
  529. // Start running
  530. controller.startEstablishing()
  531. loop:
  532. for {
  533. select {
  534. case failedTunnel := <-controller.failedTunnels:
  535. NoticeAlert("tunnel failed: %s", failedTunnel.serverEntry.IpAddress)
  536. controller.terminateTunnel(failedTunnel)
  537. // Note: we make this extra check to ensure the shutdown signal takes priority
  538. // and that we do not start establishing. Critically, startEstablishing() calls
  539. // establishPendingConns.Reset() which clears the closed flag in
  540. // establishPendingConns; this causes the pendingConns.Add() within
  541. // interruptibleTCPDial to succeed instead of aborting, and the result
  542. // is that it's possible for establish goroutines to run all the way through
  543. // NewServerContext before being discarded... delaying shutdown.
  544. select {
  545. case <-controller.shutdownBroadcast:
  546. break loop
  547. default:
  548. }
  549. controller.classifyImpairedProtocol(failedTunnel)
  550. // Clear the reference to this tunnel before calling startEstablishing,
  551. // which will invoke a garbage collection.
  552. failedTunnel = nil
  553. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing
  554. // and access isEstablishing.
  555. if !controller.isEstablishing {
  556. controller.startEstablishing()
  557. }
  558. case establishedTunnel := <-controller.establishedTunnels:
  559. if controller.isImpairedProtocol(establishedTunnel.protocol) {
  560. // Protocol was classified as impaired while this tunnel established.
  561. // This is most likely to occur with TunnelPoolSize > 0. We log the
  562. // event but take no action. Discarding the tunnel would break the
  563. // impaired logic unless we did that (a) only if there are other
  564. // unimpaired protocols; (b) only during the first interation of the
  565. // ESTABLISH_TUNNEL_WORK_TIME loop. By not discarding here, a true
  566. // impaired protocol may require an extra reconnect.
  567. NoticeAlert("established tunnel with impaired protocol: %s", establishedTunnel.protocol)
  568. }
  569. tunnelCount, registered := controller.registerTunnel(establishedTunnel)
  570. if !registered {
  571. // Already fully established, so discard.
  572. controller.discardTunnel(establishedTunnel)
  573. // Clear the reference to this discarded tunnel and immediately run
  574. // a garbage collection to reclaim its memory.
  575. establishedTunnel = nil
  576. aggressiveGarbageCollection()
  577. break
  578. }
  579. NoticeActiveTunnel(establishedTunnel.serverEntry.IpAddress, establishedTunnel.protocol, establishedTunnel.serverEntry.SupportsSSHAPIRequests())
  580. if tunnelCount == 1 {
  581. // The split tunnel classifier is started once the first tunnel is
  582. // established. This first tunnel is passed in to be used to make
  583. // the routes data request.
  584. // A long-running controller may run while the host device is present
  585. // in different regions. In this case, we want the split tunnel logic
  586. // to switch to routes for new regions and not classify traffic based
  587. // on routes installed for older regions.
  588. // We assume that when regions change, the host network will also
  589. // change, and so all tunnels will fail and be re-established. Under
  590. // that assumption, the classifier will be re-Start()-ed here when
  591. // the region has changed.
  592. controller.splitTunnelClassifier.Start(establishedTunnel)
  593. // Signal a connected request on each 1st tunnel establishment. For
  594. // multi-tunnels, the session is connected as long as at least one
  595. // tunnel is established.
  596. controller.startOrSignalConnectedReporter()
  597. // If the handshake indicated that a new client version is available,
  598. // trigger an upgrade download.
  599. // Note: serverContext is nil when DisableApi is set
  600. if establishedTunnel.serverContext != nil &&
  601. establishedTunnel.serverContext.clientUpgradeVersion != "" {
  602. handshakeVersion := establishedTunnel.serverContext.clientUpgradeVersion
  603. select {
  604. case controller.signalDownloadUpgrade <- handshakeVersion:
  605. default:
  606. }
  607. }
  608. }
  609. // Set the new tunnel as the transport for the packet tunnel. The packet tunnel
  610. // client remains up when reestablishing, but no packets are relayed while there
  611. // is no connected tunnel. UseTunnel will establish a new packet tunnel SSH
  612. // channel over the new SSH tunnel and configure the packet tunnel client to use
  613. // the new SSH channel as its transport.
  614. //
  615. // Note: as is, this logic is suboptimal for TunnelPoolSize > 1, as this would
  616. // continuously initialize new packet tunnel sessions for each established
  617. // server. For now, config validation requires TunnelPoolSize == 1 when
  618. // the packet tunnel is used.
  619. if controller.packetTunnelTransport != nil {
  620. controller.packetTunnelTransport.UseTunnel(establishedTunnel)
  621. }
  622. // TODO: design issue -- might not be enough server entries with region/caps to ever fill tunnel slots;
  623. // possible solution is establish target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  624. if controller.isFullyEstablished() {
  625. controller.stopEstablishing()
  626. }
  627. case clientVerificationPayload = <-controller.newClientVerificationPayload:
  628. controller.setClientVerificationPayloadForActiveTunnels(clientVerificationPayload)
  629. case <-controller.shutdownBroadcast:
  630. break loop
  631. }
  632. }
  633. // Stop running
  634. controller.stopEstablishing()
  635. controller.terminateAllTunnels()
  636. // Drain tunnel channels
  637. close(controller.establishedTunnels)
  638. for tunnel := range controller.establishedTunnels {
  639. controller.discardTunnel(tunnel)
  640. }
  641. close(controller.failedTunnels)
  642. for tunnel := range controller.failedTunnels {
  643. controller.discardTunnel(tunnel)
  644. }
  645. NoticeInfo("exiting run tunnels")
  646. }
  647. // classifyImpairedProtocol tracks "impaired" protocol classifications for failed
  648. // tunnels. A protocol is classified as impaired if a tunnel using that protocol
  649. // fails, repeatedly, shortly after the start of the connection. During tunnel
  650. // establishment, impaired protocols are briefly skipped.
  651. //
  652. // One purpose of this measure is to defend against an attack where the adversary,
  653. // for example, tags an OSSH TCP connection as an "unidentified" protocol; allows
  654. // it to connect; but then kills the underlying TCP connection after a short time.
  655. // Since OSSH has less latency than other protocols that may bypass an "unidentified"
  656. // filter, these other protocols might never be selected for use.
  657. //
  658. // Concurrency note: only the runTunnels() goroutine may call classifyImpairedProtocol
  659. func (controller *Controller) classifyImpairedProtocol(failedTunnel *Tunnel) {
  660. if failedTunnel.establishedTime.Add(IMPAIRED_PROTOCOL_CLASSIFICATION_DURATION).After(monotime.Now()) {
  661. controller.impairedProtocolClassification[failedTunnel.protocol] += 1
  662. } else {
  663. controller.impairedProtocolClassification[failedTunnel.protocol] = 0
  664. }
  665. // Reset classification once all known protocols are classified as impaired, as
  666. // there is now no way to proceed with only unimpaired protocols. The network
  667. // situation (or attack) resulting in classification may not be protocol-specific.
  668. //
  669. // Note: with controller.config.TunnelProtocol set, this will always reset once
  670. // that protocol has reached IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD.
  671. if CountNonImpairedProtocols(
  672. controller.config.EgressRegion,
  673. controller.config.TunnelProtocol,
  674. controller.getImpairedProtocols()) == 0 {
  675. controller.impairedProtocolClassification = make(map[string]int)
  676. }
  677. }
  678. // getImpairedProtocols returns a list of protocols that have sufficient
  679. // classifications to be considered impaired protocols.
  680. //
  681. // Concurrency note: only the runTunnels() goroutine may call getImpairedProtocols
  682. func (controller *Controller) getImpairedProtocols() []string {
  683. NoticeImpairedProtocolClassification(controller.impairedProtocolClassification)
  684. impairedProtocols := make([]string, 0)
  685. for protocol, count := range controller.impairedProtocolClassification {
  686. if count >= IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD {
  687. impairedProtocols = append(impairedProtocols, protocol)
  688. }
  689. }
  690. return impairedProtocols
  691. }
  692. // isImpairedProtocol checks if the specified protocol is classified as impaired.
  693. //
  694. // Concurrency note: only the runTunnels() goroutine may call isImpairedProtocol
  695. func (controller *Controller) isImpairedProtocol(protocol string) bool {
  696. count, ok := controller.impairedProtocolClassification[protocol]
  697. return ok && count >= IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD
  698. }
  699. // SignalSeededNewSLOK implements the TunnelOwner interface. This function
  700. // is called by Tunnel.operateTunnel when the tunnel has received a new,
  701. // previously unknown SLOK from the server. The Controller triggers an OSL
  702. // fetch, as the new SLOK may be sufficient to access new OSLs.
  703. func (controller *Controller) SignalSeededNewSLOK() {
  704. select {
  705. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  706. default:
  707. }
  708. }
  709. // SignalTunnelFailure implements the TunnelOwner interface. This function
  710. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  711. // has failed. The Controller will signal runTunnels to create a new
  712. // tunnel and/or remove the tunnel from the list of active tunnels.
  713. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  714. // Don't block. Assumes the receiver has a buffer large enough for
  715. // the typical number of operated tunnels. In case there's no room,
  716. // terminate the tunnel (runTunnels won't get a signal in this case,
  717. // but the tunnel will be removed from the list of active tunnels).
  718. select {
  719. case controller.failedTunnels <- tunnel:
  720. default:
  721. controller.terminateTunnel(tunnel)
  722. }
  723. }
  724. // discardTunnel disposes of a successful connection that is no longer required.
  725. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  726. NoticeInfo("discard tunnel: %s", tunnel.serverEntry.IpAddress)
  727. // TODO: not calling PromoteServerEntry, since that would rank the
  728. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  729. // be promoted (since it connects), but with lower rank than all active
  730. // tunnels?
  731. tunnel.Close(true)
  732. }
  733. // registerTunnel adds the connected tunnel to the pool of active tunnels
  734. // which are candidates for port forwarding. Returns true if the pool has an
  735. // empty slot and false if the pool is full (caller should discard the tunnel).
  736. func (controller *Controller) registerTunnel(tunnel *Tunnel) (int, bool) {
  737. controller.tunnelMutex.Lock()
  738. defer controller.tunnelMutex.Unlock()
  739. if len(controller.tunnels) >= controller.config.TunnelPoolSize {
  740. return len(controller.tunnels), false
  741. }
  742. // Perform a final check just in case we've established
  743. // a duplicate connection.
  744. for _, activeTunnel := range controller.tunnels {
  745. if activeTunnel.serverEntry.IpAddress == tunnel.serverEntry.IpAddress {
  746. NoticeAlert("duplicate tunnel: %s", tunnel.serverEntry.IpAddress)
  747. return len(controller.tunnels), false
  748. }
  749. }
  750. controller.establishedOnce = true
  751. controller.tunnels = append(controller.tunnels, tunnel)
  752. NoticeTunnels(len(controller.tunnels))
  753. // Promote this successful tunnel to first rank so it's one
  754. // of the first candidates next time establish runs.
  755. // Connecting to a TargetServerEntry does not change the
  756. // ranking.
  757. if controller.config.TargetServerEntry == "" {
  758. PromoteServerEntry(tunnel.serverEntry.IpAddress)
  759. }
  760. return len(controller.tunnels), true
  761. }
  762. // hasEstablishedOnce indicates if at least one active tunnel has
  763. // been established up to this point. This is regardeless of how many
  764. // tunnels are presently active.
  765. func (controller *Controller) hasEstablishedOnce() bool {
  766. controller.tunnelMutex.Lock()
  767. defer controller.tunnelMutex.Unlock()
  768. return controller.establishedOnce
  769. }
  770. // isFullyEstablished indicates if the pool of active tunnels is full.
  771. func (controller *Controller) isFullyEstablished() bool {
  772. controller.tunnelMutex.Lock()
  773. defer controller.tunnelMutex.Unlock()
  774. return len(controller.tunnels) >= controller.config.TunnelPoolSize
  775. }
  776. // terminateTunnel removes a tunnel from the pool of active tunnels
  777. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  778. // is adjusted as required.
  779. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  780. controller.tunnelMutex.Lock()
  781. defer controller.tunnelMutex.Unlock()
  782. for index, activeTunnel := range controller.tunnels {
  783. if tunnel == activeTunnel {
  784. controller.tunnels = append(
  785. controller.tunnels[:index], controller.tunnels[index+1:]...)
  786. if controller.nextTunnel > index {
  787. controller.nextTunnel--
  788. }
  789. if controller.nextTunnel >= len(controller.tunnels) {
  790. controller.nextTunnel = 0
  791. }
  792. activeTunnel.Close(false)
  793. NoticeTunnels(len(controller.tunnels))
  794. break
  795. }
  796. }
  797. }
  798. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  799. // This is used when shutting down the controller.
  800. func (controller *Controller) terminateAllTunnels() {
  801. controller.tunnelMutex.Lock()
  802. defer controller.tunnelMutex.Unlock()
  803. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  804. // may take a few seconds to send a final status request. We only want
  805. // to wait as long as the single slowest tunnel.
  806. closeWaitGroup := new(sync.WaitGroup)
  807. closeWaitGroup.Add(len(controller.tunnels))
  808. for _, activeTunnel := range controller.tunnels {
  809. tunnel := activeTunnel
  810. go func() {
  811. defer closeWaitGroup.Done()
  812. tunnel.Close(false)
  813. }()
  814. }
  815. closeWaitGroup.Wait()
  816. controller.tunnels = make([]*Tunnel, 0)
  817. controller.nextTunnel = 0
  818. NoticeTunnels(len(controller.tunnels))
  819. }
  820. // getNextActiveTunnel returns the next tunnel from the pool of active
  821. // tunnels. Currently, tunnel selection order is simple round-robin.
  822. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  823. controller.tunnelMutex.Lock()
  824. defer controller.tunnelMutex.Unlock()
  825. for i := len(controller.tunnels); i > 0; i-- {
  826. tunnel = controller.tunnels[controller.nextTunnel]
  827. controller.nextTunnel =
  828. (controller.nextTunnel + 1) % len(controller.tunnels)
  829. return tunnel
  830. }
  831. return nil
  832. }
  833. // isActiveTunnelServerEntry is used to check if there's already
  834. // an existing tunnel to a candidate server.
  835. func (controller *Controller) isActiveTunnelServerEntry(
  836. serverEntry *protocol.ServerEntry) bool {
  837. controller.tunnelMutex.Lock()
  838. defer controller.tunnelMutex.Unlock()
  839. for _, activeTunnel := range controller.tunnels {
  840. if activeTunnel.serverEntry.IpAddress == serverEntry.IpAddress {
  841. return true
  842. }
  843. }
  844. return false
  845. }
  846. // setClientVerificationPayloadForActiveTunnels triggers the client verification
  847. // request for all active tunnels.
  848. func (controller *Controller) setClientVerificationPayloadForActiveTunnels(
  849. clientVerificationPayload string) {
  850. controller.tunnelMutex.Lock()
  851. defer controller.tunnelMutex.Unlock()
  852. for _, activeTunnel := range controller.tunnels {
  853. activeTunnel.SetClientVerificationPayload(clientVerificationPayload)
  854. }
  855. }
  856. // Dial selects an active tunnel and establishes a port forward
  857. // connection through the selected tunnel. Failure to connect is considered
  858. // a port forward failure, for the purpose of monitoring tunnel health.
  859. func (controller *Controller) Dial(
  860. remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error) {
  861. tunnel := controller.getNextActiveTunnel()
  862. if tunnel == nil {
  863. return nil, common.ContextError(errors.New("no active tunnels"))
  864. }
  865. // Perform split tunnel classification when feature is enabled, and if the remote
  866. // address is classified as untunneled, dial directly.
  867. if !alwaysTunnel && controller.config.SplitTunnelDnsServer != "" {
  868. host, _, err := net.SplitHostPort(remoteAddr)
  869. if err != nil {
  870. return nil, common.ContextError(err)
  871. }
  872. // Note: a possible optimization, when split tunnel is active and IsUntunneled performs
  873. // a DNS resolution in order to make its classification, is to reuse that IP address in
  874. // the following Dials so they do not need to make their own resolutions. However, the
  875. // way this is currently implemented ensures that, e.g., DNS geo load balancing occurs
  876. // relative to the outbound network.
  877. if controller.splitTunnelClassifier.IsUntunneled(host) {
  878. // TODO: track downstreamConn and close it when the DialTCP conn closes, as with tunnel.Dial conns?
  879. return DialTCP(remoteAddr, controller.untunneledDialConfig)
  880. }
  881. }
  882. tunneledConn, err := tunnel.Dial(remoteAddr, alwaysTunnel, downstreamConn)
  883. if err != nil {
  884. return nil, common.ContextError(err)
  885. }
  886. return tunneledConn, nil
  887. }
  888. // startEstablishing creates a pool of worker goroutines which will
  889. // attempt to establish tunnels to candidate servers. The candidates
  890. // are generated by another goroutine.
  891. func (controller *Controller) startEstablishing() {
  892. if controller.isEstablishing {
  893. return
  894. }
  895. NoticeInfo("start establishing")
  896. controller.concurrentEstablishTunnelsMutex.Lock()
  897. controller.concurrentEstablishTunnels = 0
  898. controller.concurrentMeekEstablishTunnels = 0
  899. controller.peakConcurrentEstablishTunnels = 0
  900. controller.peakConcurrentMeekEstablishTunnels = 0
  901. controller.concurrentEstablishTunnelsMutex.Unlock()
  902. aggressiveGarbageCollection()
  903. emitMemoryMetrics()
  904. controller.isEstablishing = true
  905. controller.establishWaitGroup = new(sync.WaitGroup)
  906. controller.stopEstablishingBroadcast = make(chan struct{})
  907. controller.candidateServerEntries = make(chan *candidateServerEntry)
  908. controller.establishPendingConns.Reset()
  909. // The server affinity mechanism attempts to favor the previously
  910. // used server when reconnecting. This is beneficial for user
  911. // applications which expect consistency in user IP address (for
  912. // example, a web site which prompts for additional user
  913. // authentication when the IP address changes).
  914. //
  915. // Only the very first server, as determined by
  916. // datastore.PromoteServerEntry(), is the server affinity candidate.
  917. // Concurrent connections attempts to many servers are launched
  918. // without delay, in case the affinity server connection fails.
  919. // While the affinity server connection is outstanding, when any
  920. // other connection is established, there is a short grace period
  921. // delay before delivering the established tunnel; this allows some
  922. // time for the affinity server connection to succeed first.
  923. // When the affinity server connection fails, any other established
  924. // tunnel is registered without delay.
  925. //
  926. // Note: the establishTunnelWorker that receives the affinity
  927. // candidate is solely resonsible for closing
  928. // controller.serverAffinityDoneBroadcast.
  929. //
  930. // Note: if config.EgressRegion or config.TunnelProtocol has changed
  931. // since the top server was promoted, the first server may not actually
  932. // be the last connected server.
  933. // TODO: should not favor the first server in this case
  934. controller.serverAffinityDoneBroadcast = make(chan struct{})
  935. for i := 0; i < controller.config.ConnectionWorkerPoolSize; i++ {
  936. controller.establishWaitGroup.Add(1)
  937. go controller.establishTunnelWorker()
  938. }
  939. controller.establishWaitGroup.Add(1)
  940. go controller.establishCandidateGenerator(
  941. controller.getImpairedProtocols())
  942. }
  943. // stopEstablishing signals the establish goroutines to stop and waits
  944. // for the group to halt. pendingConns is used to interrupt any worker
  945. // blocked on a socket connect.
  946. func (controller *Controller) stopEstablishing() {
  947. if !controller.isEstablishing {
  948. return
  949. }
  950. NoticeInfo("stop establishing")
  951. close(controller.stopEstablishingBroadcast)
  952. // Note: interruptibleTCPClose doesn't really interrupt socket connects
  953. // and may leave goroutines running for a time after the Wait call.
  954. controller.establishPendingConns.CloseAll()
  955. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  956. // (as it may be sending to that channel).
  957. controller.establishWaitGroup.Wait()
  958. controller.isEstablishing = false
  959. controller.establishWaitGroup = nil
  960. controller.stopEstablishingBroadcast = nil
  961. controller.candidateServerEntries = nil
  962. controller.serverAffinityDoneBroadcast = nil
  963. controller.concurrentEstablishTunnelsMutex.Lock()
  964. peakConcurrent := controller.peakConcurrentEstablishTunnels
  965. peakConcurrentMeek := controller.peakConcurrentMeekEstablishTunnels
  966. controller.concurrentEstablishTunnels = 0
  967. controller.concurrentMeekEstablishTunnels = 0
  968. controller.peakConcurrentEstablishTunnels = 0
  969. controller.peakConcurrentMeekEstablishTunnels = 0
  970. controller.concurrentEstablishTunnelsMutex.Unlock()
  971. NoticeInfo("peak concurrent establish tunnels: %d", peakConcurrent)
  972. NoticeInfo("peak concurrent meek establish tunnels: %d", peakConcurrentMeek)
  973. emitMemoryMetrics()
  974. standardGarbageCollection()
  975. }
  976. // establishCandidateGenerator populates the candidate queue with server entries
  977. // from the data store. Server entries are iterated in rank order, so that promoted
  978. // servers with higher rank are priority candidates.
  979. func (controller *Controller) establishCandidateGenerator(impairedProtocols []string) {
  980. defer controller.establishWaitGroup.Done()
  981. defer close(controller.candidateServerEntries)
  982. // establishStartTime is used to calculate and report the
  983. // client's tunnel establishment duration.
  984. //
  985. // networkWaitDuration is the elapsed time spent waiting
  986. // for network connectivity. This duration will be excluded
  987. // from reported tunnel establishment duration.
  988. establishStartTime := monotime.Now()
  989. var networkWaitDuration time.Duration
  990. iterator, err := NewServerEntryIterator(controller.config)
  991. if err != nil {
  992. NoticeAlert("failed to iterate over candidates: %s", err)
  993. controller.SignalComponentFailure()
  994. return
  995. }
  996. defer iterator.Close()
  997. isServerAffinityCandidate := true
  998. // TODO: reconcile server affinity scheme with multi-tunnel mode
  999. if controller.config.TunnelPoolSize > 1 {
  1000. isServerAffinityCandidate = false
  1001. close(controller.serverAffinityDoneBroadcast)
  1002. }
  1003. loop:
  1004. // Repeat until stopped
  1005. for i := 0; ; i++ {
  1006. networkWaitStartTime := monotime.Now()
  1007. if !WaitForNetworkConnectivity(
  1008. controller.config.NetworkConnectivityChecker,
  1009. controller.stopEstablishingBroadcast,
  1010. controller.shutdownBroadcast) {
  1011. break loop
  1012. }
  1013. networkWaitDuration += monotime.Since(networkWaitStartTime)
  1014. // Send each iterator server entry to the establish workers
  1015. startTime := monotime.Now()
  1016. for {
  1017. serverEntry, err := iterator.Next()
  1018. if err != nil {
  1019. NoticeAlert("failed to get next candidate: %s", err)
  1020. controller.SignalComponentFailure()
  1021. break loop
  1022. }
  1023. if serverEntry == nil {
  1024. // Completed this iteration
  1025. break
  1026. }
  1027. if controller.config.TargetApiProtocol == protocol.PSIPHON_SSH_API_PROTOCOL &&
  1028. !serverEntry.SupportsSSHAPIRequests() {
  1029. continue
  1030. }
  1031. // Disable impaired protocols. This is only done for the
  1032. // first iteration of the ESTABLISH_TUNNEL_WORK_TIME
  1033. // loop since (a) one iteration should be sufficient to
  1034. // evade the attack; (b) there's a good chance of false
  1035. // positives (such as short tunnel durations due to network
  1036. // hopping on a mobile device).
  1037. // The edited serverEntry is temporary copy which is not
  1038. // stored or reused.
  1039. if i == 0 {
  1040. serverEntry.DisableImpairedProtocols(impairedProtocols)
  1041. if len(serverEntry.GetSupportedProtocols(false)) == 0 {
  1042. // Skip this server entry, as it has no supported
  1043. // protocols after disabling the impaired ones
  1044. // TODO: modify ServerEntryIterator to skip these?
  1045. continue
  1046. }
  1047. }
  1048. // adjustedEstablishStartTime is establishStartTime shifted
  1049. // to exclude time spent waiting for network connectivity.
  1050. candidate := &candidateServerEntry{
  1051. serverEntry: serverEntry,
  1052. isServerAffinityCandidate: isServerAffinityCandidate,
  1053. adjustedEstablishStartTime: establishStartTime.Add(networkWaitDuration),
  1054. }
  1055. wasServerAffinityCandidate := isServerAffinityCandidate
  1056. // Note: there must be only one server affinity candidate, as it
  1057. // closes the serverAffinityDoneBroadcast channel.
  1058. isServerAffinityCandidate = false
  1059. // TODO: here we could generate multiple candidates from the
  1060. // server entry when there are many MeekFrontingAddresses.
  1061. select {
  1062. case controller.candidateServerEntries <- candidate:
  1063. case <-controller.stopEstablishingBroadcast:
  1064. break loop
  1065. case <-controller.shutdownBroadcast:
  1066. break loop
  1067. }
  1068. if startTime.Add(ESTABLISH_TUNNEL_WORK_TIME).Before(monotime.Now()) {
  1069. // Start over, after a brief pause, with a new shuffle of the server
  1070. // entries, and potentially some newly fetched server entries.
  1071. break
  1072. }
  1073. if wasServerAffinityCandidate {
  1074. // Don't start the next candidate until either the server affinity
  1075. // candidate has completed (success or failure) or is still working
  1076. // and the grace period has elapsed.
  1077. timer := time.NewTimer(ESTABLISH_TUNNEL_SERVER_AFFINITY_GRACE_PERIOD)
  1078. select {
  1079. case <-timer.C:
  1080. case <-controller.serverAffinityDoneBroadcast:
  1081. case <-controller.stopEstablishingBroadcast:
  1082. break loop
  1083. case <-controller.shutdownBroadcast:
  1084. break loop
  1085. }
  1086. } else if controller.config.StaggerConnectionWorkersMilliseconds != 0 {
  1087. // Stagger concurrent connection workers.
  1088. timer := time.NewTimer(time.Millisecond * time.Duration(
  1089. controller.config.StaggerConnectionWorkersMilliseconds))
  1090. select {
  1091. case <-timer.C:
  1092. case <-controller.stopEstablishingBroadcast:
  1093. break loop
  1094. case <-controller.shutdownBroadcast:
  1095. break loop
  1096. }
  1097. }
  1098. }
  1099. // Free up resources now, but don't reset until after the pause.
  1100. iterator.Close()
  1101. // Trigger a common remote server list fetch, since we may have failed
  1102. // to connect with all known servers. Don't block sending signal, since
  1103. // this signal may have already been sent.
  1104. // Don't wait for fetch remote to succeed, since it may fail and
  1105. // enter a retry loop and we're better off trying more known servers.
  1106. // TODO: synchronize the fetch response, so it can be incorporated
  1107. // into the server entry iterator as soon as available.
  1108. select {
  1109. case controller.signalFetchCommonRemoteServerList <- *new(struct{}):
  1110. default:
  1111. }
  1112. // Trigger an OSL fetch in parallel. Both fetches are run in parallel
  1113. // so that if one out of the common RLS and OSL set is large, it doesn't
  1114. // doesn't entirely block fetching the other.
  1115. select {
  1116. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  1117. default:
  1118. }
  1119. // Trigger an out-of-band upgrade availability check and download.
  1120. // Since we may have failed to connect, we may benefit from upgrading
  1121. // to a new client version with new circumvention capabilities.
  1122. select {
  1123. case controller.signalDownloadUpgrade <- "":
  1124. default:
  1125. }
  1126. // After a complete iteration of candidate servers, pause before iterating again.
  1127. // This helps avoid some busy wait loop conditions, and also allows some time for
  1128. // network conditions to change. Also allows for fetch remote to complete,
  1129. // in typical conditions (it isn't strictly necessary to wait for this, there will
  1130. // be more rounds if required).
  1131. timeout := time.After(
  1132. time.Duration(*controller.config.EstablishTunnelPausePeriodSeconds) * time.Second)
  1133. select {
  1134. case <-timeout:
  1135. // Retry iterating
  1136. case <-controller.stopEstablishingBroadcast:
  1137. break loop
  1138. case <-controller.shutdownBroadcast:
  1139. break loop
  1140. }
  1141. iterator.Reset()
  1142. }
  1143. NoticeInfo("stopped candidate generator")
  1144. }
  1145. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  1146. // a connection to the tunnel server, and delivers the established tunnel to a channel.
  1147. func (controller *Controller) establishTunnelWorker() {
  1148. defer controller.establishWaitGroup.Done()
  1149. loop:
  1150. for candidateServerEntry := range controller.candidateServerEntries {
  1151. // Note: don't receive from candidateServerEntries and stopEstablishingBroadcast
  1152. // in the same select, since we want to prioritize receiving the stop signal
  1153. if controller.isStopEstablishingBroadcast() {
  1154. break loop
  1155. }
  1156. // There may already be a tunnel to this candidate. If so, skip it.
  1157. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  1158. continue
  1159. }
  1160. // EstablishTunnel will allocate significant memory, so first attempt to
  1161. // reclaim as much as possible.
  1162. aggressiveGarbageCollection()
  1163. // Select the tunnel protocol. Unless config.TunnelProtocol is set, the
  1164. // selection will be made at random from protocols supported by the
  1165. // server entry.
  1166. //
  1167. // When limiting concurrent meek connection workers, and at the limit,
  1168. // do not select meek since otherwise the candidate must be skipped.
  1169. //
  1170. // If at the limit and unabled to select a non-meek protocol, skip the
  1171. // candidate entirely and move on to the next. Since candidates are shuffled
  1172. // it's probable that the next candidate is not meek. In this case, a
  1173. // StaggerConnectionWorkersMilliseconds delay may still be incurred.
  1174. excludeMeek := false
  1175. controller.concurrentEstablishTunnelsMutex.Lock()
  1176. if controller.config.LimitMeekConnectionWorkers > 0 &&
  1177. controller.concurrentMeekEstablishTunnels >=
  1178. controller.config.LimitMeekConnectionWorkers {
  1179. excludeMeek = true
  1180. }
  1181. controller.concurrentEstablishTunnelsMutex.Unlock()
  1182. selectedProtocol, err := selectProtocol(
  1183. controller.config, candidateServerEntry.serverEntry, excludeMeek)
  1184. if err == errProtocolNotSupported {
  1185. // selectProtocol returns errProtocolNotSupported when excludeMeek
  1186. // is set and the server entry only supports meek protocols.
  1187. // Skip this candidate.
  1188. continue
  1189. }
  1190. var tunnel *Tunnel
  1191. if err == nil {
  1192. isMeek := protocol.TunnelProtocolUsesMeek(selectedProtocol) ||
  1193. protocol.TunnelProtocolUsesMeek(selectedProtocol)
  1194. controller.concurrentEstablishTunnelsMutex.Lock()
  1195. if isMeek {
  1196. // Recheck the limit now that we know we're selecting meek and
  1197. // adjusting concurrentMeekEstablishTunnels.
  1198. if controller.config.LimitMeekConnectionWorkers > 0 &&
  1199. controller.concurrentMeekEstablishTunnels >=
  1200. controller.config.LimitMeekConnectionWorkers {
  1201. // Skip this candidate.
  1202. controller.concurrentEstablishTunnelsMutex.Unlock()
  1203. continue
  1204. }
  1205. controller.concurrentMeekEstablishTunnels += 1
  1206. if controller.concurrentMeekEstablishTunnels > controller.peakConcurrentMeekEstablishTunnels {
  1207. controller.peakConcurrentMeekEstablishTunnels = controller.concurrentMeekEstablishTunnels
  1208. }
  1209. }
  1210. controller.concurrentEstablishTunnels += 1
  1211. if controller.concurrentEstablishTunnels > controller.peakConcurrentEstablishTunnels {
  1212. controller.peakConcurrentEstablishTunnels = controller.concurrentEstablishTunnels
  1213. }
  1214. controller.concurrentEstablishTunnelsMutex.Unlock()
  1215. tunnel, err = EstablishTunnel(
  1216. controller.config,
  1217. controller.untunneledDialConfig,
  1218. controller.sessionId,
  1219. controller.establishPendingConns,
  1220. candidateServerEntry.serverEntry,
  1221. selectedProtocol,
  1222. candidateServerEntry.adjustedEstablishStartTime,
  1223. controller) // TunnelOwner
  1224. controller.concurrentEstablishTunnelsMutex.Lock()
  1225. if isMeek {
  1226. controller.concurrentMeekEstablishTunnels -= 1
  1227. }
  1228. controller.concurrentEstablishTunnels -= 1
  1229. controller.concurrentEstablishTunnelsMutex.Unlock()
  1230. }
  1231. // Periodically emit memory metrics during the establishment cycle.
  1232. if !controller.isStopEstablishingBroadcast() {
  1233. emitMemoryMetrics()
  1234. }
  1235. // Immediately reclaim memory allocated by the establishment. In the case
  1236. // of failure, first clear the reference to the tunnel. In the case of
  1237. // success, the garbage collection may still be effective as the initial
  1238. // phases of some protocols involve significant memory allocation that
  1239. // could now be reclaimed.
  1240. if err != nil {
  1241. tunnel = nil
  1242. }
  1243. aggressiveGarbageCollection()
  1244. if err != nil {
  1245. // Unblock other candidates immediately when
  1246. // server affinity candidate fails.
  1247. if candidateServerEntry.isServerAffinityCandidate {
  1248. close(controller.serverAffinityDoneBroadcast)
  1249. }
  1250. // Before emitting error, check if establish interrupted, in which
  1251. // case the error is noise.
  1252. if controller.isStopEstablishingBroadcast() {
  1253. break loop
  1254. }
  1255. NoticeInfo("failed to connect to %s: %s", candidateServerEntry.serverEntry.IpAddress, err)
  1256. continue
  1257. }
  1258. // Deliver established tunnel.
  1259. // Don't block. Assumes the receiver has a buffer large enough for
  1260. // the number of desired tunnels. If there's no room, the tunnel must
  1261. // not be required so it's discarded.
  1262. select {
  1263. case controller.establishedTunnels <- tunnel:
  1264. default:
  1265. controller.discardTunnel(tunnel)
  1266. // Clear the reference to this discarded tunnel and immediately run
  1267. // a garbage collection to reclaim its memory.
  1268. tunnel = nil
  1269. aggressiveGarbageCollection()
  1270. }
  1271. // Unblock other candidates only after delivering when
  1272. // server affinity candidate succeeds.
  1273. if candidateServerEntry.isServerAffinityCandidate {
  1274. close(controller.serverAffinityDoneBroadcast)
  1275. }
  1276. }
  1277. NoticeInfo("stopped establish worker")
  1278. }
  1279. func (controller *Controller) isStopEstablishingBroadcast() bool {
  1280. select {
  1281. case <-controller.stopEstablishingBroadcast:
  1282. return true
  1283. default:
  1284. }
  1285. return false
  1286. }