controller.go 56 KB

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