controller.go 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901
  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. "context"
  26. "errors"
  27. "fmt"
  28. "math/rand"
  29. "net"
  30. "sync"
  31. "time"
  32. "github.com/Psiphon-Labs/goarista/monotime"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  38. )
  39. // Controller is a tunnel lifecycle coordinator. It manages lists of servers to
  40. // connect to; establishes and monitors tunnels; and runs local proxies which
  41. // route traffic through the tunnels.
  42. type Controller struct {
  43. config *Config
  44. sessionId string
  45. runCtx context.Context
  46. stopRunning context.CancelFunc
  47. runWaitGroup *sync.WaitGroup
  48. connectedTunnels chan *Tunnel
  49. failedTunnels chan *Tunnel
  50. tunnelMutex sync.Mutex
  51. establishedOnce bool
  52. tunnels []*Tunnel
  53. nextTunnel int
  54. startedConnectedReporter bool
  55. isEstablishing bool
  56. establishLimitTunnelProtocolsState *limitTunnelProtocolsState
  57. concurrentEstablishTunnelsMutex sync.Mutex
  58. establishConnectTunnelCount int
  59. concurrentEstablishTunnels int
  60. concurrentIntensiveEstablishTunnels int
  61. peakConcurrentEstablishTunnels int
  62. peakConcurrentIntensiveEstablishTunnels int
  63. establishCtx context.Context
  64. stopEstablish context.CancelFunc
  65. establishWaitGroup *sync.WaitGroup
  66. candidateServerEntries chan *candidateServerEntry
  67. untunneledDialConfig *DialConfig
  68. splitTunnelClassifier *SplitTunnelClassifier
  69. signalFetchCommonRemoteServerList chan struct{}
  70. signalFetchObfuscatedServerLists chan struct{}
  71. signalDownloadUpgrade chan string
  72. signalReportConnected chan struct{}
  73. serverAffinityDoneBroadcast chan struct{}
  74. packetTunnelClient *tun.Client
  75. packetTunnelTransport *PacketTunnelTransport
  76. }
  77. // NewController initializes a new controller.
  78. func NewController(config *Config) (controller *Controller, err error) {
  79. if !config.IsCommitted() {
  80. return nil, common.ContextError(errors.New("uncommitted config"))
  81. }
  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. untunneledDialConfig := &DialConfig{
  88. UpstreamProxyURL: config.UpstreamProxyURL,
  89. CustomHeaders: config.CustomHeaders,
  90. DeviceBinder: config.deviceBinder,
  91. DnsServerGetter: config.DnsServerGetter,
  92. IPv6Synthesizer: config.IPv6Synthesizer,
  93. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  94. }
  95. controller = &Controller{
  96. config: config,
  97. sessionId: config.SessionID,
  98. runWaitGroup: new(sync.WaitGroup),
  99. // connectedTunnels and failedTunnels buffer sizes are large enough to
  100. // receive full pools of tunnels without blocking. Senders should not block.
  101. connectedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  102. failedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  103. tunnels: make([]*Tunnel, 0),
  104. establishedOnce: false,
  105. startedConnectedReporter: false,
  106. isEstablishing: false,
  107. untunneledDialConfig: untunneledDialConfig,
  108. // TODO: Add a buffer of 1 so we don't miss a signal while receiver is
  109. // starting? Trade-off is potential back-to-back fetch remotes. As-is,
  110. // establish will eventually signal another fetch remote.
  111. signalFetchCommonRemoteServerList: make(chan struct{}),
  112. signalFetchObfuscatedServerLists: make(chan struct{}),
  113. signalDownloadUpgrade: make(chan string),
  114. signalReportConnected: make(chan struct{}),
  115. }
  116. controller.splitTunnelClassifier = NewSplitTunnelClassifier(config, controller)
  117. if config.PacketTunnelTunFileDescriptor > 0 {
  118. // Run a packet tunnel client. The lifetime of the tun.Client is the
  119. // lifetime of the Controller, so it exists across tunnel establishments
  120. // and reestablishments. The PacketTunnelTransport provides a layer
  121. // that presents a continuosuly existing transport to the tun.Client;
  122. // it's set to use new SSH channels after new SSH tunnel establishes.
  123. packetTunnelTransport := NewPacketTunnelTransport()
  124. packetTunnelClient, err := tun.NewClient(&tun.ClientConfig{
  125. Logger: NoticeCommonLogger(),
  126. TunFileDescriptor: config.PacketTunnelTunFileDescriptor,
  127. Transport: packetTunnelTransport,
  128. })
  129. if err != nil {
  130. return nil, common.ContextError(err)
  131. }
  132. controller.packetTunnelClient = packetTunnelClient
  133. controller.packetTunnelTransport = packetTunnelTransport
  134. }
  135. return controller, nil
  136. }
  137. // Run executes the controller. Run exits if a controller
  138. // component fails or the parent context is canceled.
  139. func (controller *Controller) Run(ctx context.Context) {
  140. pprofRun()
  141. // Ensure fresh repetitive notice state for each run, so the
  142. // client will always get an AvailableEgressRegions notice,
  143. // an initial instance of any repetitive error notice, etc.
  144. ResetRepetitiveNotices()
  145. runCtx, stopRunning := context.WithCancel(ctx)
  146. defer stopRunning()
  147. controller.runCtx = runCtx
  148. controller.stopRunning = stopRunning
  149. // Start components
  150. // TODO: IPv6 support
  151. var listenIP string
  152. if controller.config.ListenInterface == "" {
  153. listenIP = "127.0.0.1"
  154. } else if controller.config.ListenInterface == "any" {
  155. listenIP = "0.0.0.0"
  156. } else {
  157. IPv4Address, _, err := common.GetInterfaceIPAddresses(controller.config.ListenInterface)
  158. if err == nil && IPv4Address == nil {
  159. err = fmt.Errorf("no IPv4 address for interface %s", controller.config.ListenInterface)
  160. }
  161. if err != nil {
  162. NoticeError("error getting listener IP: %s", err)
  163. return
  164. }
  165. listenIP = IPv4Address.String()
  166. }
  167. if !controller.config.DisableLocalSocksProxy {
  168. socksProxy, err := NewSocksProxy(controller.config, controller, listenIP)
  169. if err != nil {
  170. NoticeAlert("error initializing local SOCKS proxy: %s", err)
  171. return
  172. }
  173. defer socksProxy.Close()
  174. }
  175. if !controller.config.DisableLocalHTTPProxy {
  176. httpProxy, err := NewHttpProxy(controller.config, controller, listenIP)
  177. if err != nil {
  178. NoticeAlert("error initializing local HTTP proxy: %s", err)
  179. return
  180. }
  181. defer httpProxy.Close()
  182. }
  183. if !controller.config.DisableRemoteServerListFetcher {
  184. if controller.config.RemoteServerListURLs != nil {
  185. controller.runWaitGroup.Add(1)
  186. go controller.remoteServerListFetcher(
  187. "common",
  188. FetchCommonRemoteServerList,
  189. controller.signalFetchCommonRemoteServerList)
  190. }
  191. if controller.config.ObfuscatedServerListRootURLs != nil {
  192. controller.runWaitGroup.Add(1)
  193. go controller.remoteServerListFetcher(
  194. "obfuscated",
  195. FetchObfuscatedServerLists,
  196. controller.signalFetchObfuscatedServerLists)
  197. }
  198. }
  199. if controller.config.UpgradeDownloadURLs != nil {
  200. controller.runWaitGroup.Add(1)
  201. go controller.upgradeDownloader()
  202. }
  203. /// Note: the connected reporter isn't started until a tunnel is
  204. // established
  205. controller.runWaitGroup.Add(1)
  206. go controller.runTunnels()
  207. controller.runWaitGroup.Add(1)
  208. go controller.establishTunnelWatcher()
  209. if controller.packetTunnelClient != nil {
  210. controller.packetTunnelClient.Start()
  211. }
  212. // Wait while running
  213. <-controller.runCtx.Done()
  214. NoticeInfo("controller stopped")
  215. if controller.packetTunnelClient != nil {
  216. controller.packetTunnelClient.Stop()
  217. }
  218. // All workers -- runTunnels, establishment workers, and auxilliary
  219. // workers such as fetch remote server list and untunneled uprade
  220. // download -- operate with the controller run context and will all
  221. // be interrupted when the run context is done.
  222. controller.runWaitGroup.Wait()
  223. controller.splitTunnelClassifier.Shutdown()
  224. NoticeInfo("exiting controller")
  225. NoticeExiting()
  226. }
  227. // SignalComponentFailure notifies the controller that an associated component has failed.
  228. // This will terminate the controller.
  229. func (controller *Controller) SignalComponentFailure() {
  230. NoticeAlert("controller shutdown due to component failure")
  231. controller.stopRunning()
  232. }
  233. // SetDynamicConfig overrides the sponsor ID and authorizations fields of the
  234. // Controller config with the input values. The new values will be used in the
  235. // next tunnel connection.
  236. func (controller *Controller) SetDynamicConfig(sponsorID string, authorizations []string) {
  237. controller.config.SetDynamicConfig(sponsorID, authorizations)
  238. }
  239. // TerminateNextActiveTunnel terminates the active tunnel, which will initiate
  240. // establishment of a new tunnel.
  241. func (controller *Controller) TerminateNextActiveTunnel() {
  242. tunnel := controller.getNextActiveTunnel()
  243. if tunnel != nil {
  244. controller.SignalTunnelFailure(tunnel)
  245. NoticeInfo("terminated tunnel: %s", tunnel.serverEntry.IpAddress)
  246. }
  247. }
  248. // remoteServerListFetcher fetches an out-of-band list of server entries
  249. // for more tunnel candidates. It fetches when signalled, with retries
  250. // on failure.
  251. func (controller *Controller) remoteServerListFetcher(
  252. name string,
  253. fetcher RemoteServerListFetcher,
  254. signal <-chan struct{}) {
  255. defer controller.runWaitGroup.Done()
  256. var lastFetchTime monotime.Time
  257. fetcherLoop:
  258. for {
  259. // Wait for a signal before fetching
  260. select {
  261. case <-signal:
  262. case <-controller.runCtx.Done():
  263. break fetcherLoop
  264. }
  265. // Skip fetch entirely (i.e., send no request at all, even when ETag would save
  266. // on response size) when a recent fetch was successful
  267. stalePeriod := controller.config.clientParameters.Get().Duration(
  268. parameters.FetchRemoteServerListStalePeriod)
  269. if lastFetchTime != 0 &&
  270. lastFetchTime.Add(stalePeriod).After(monotime.Now()) {
  271. continue
  272. }
  273. retryLoop:
  274. for attempt := 0; ; attempt++ {
  275. // Don't attempt to fetch while there is no network connectivity,
  276. // to avoid alert notice noise.
  277. if !WaitForNetworkConnectivity(
  278. controller.runCtx,
  279. controller.config.NetworkConnectivityChecker) {
  280. break fetcherLoop
  281. }
  282. // Pick any active tunnel and make the next fetch attempt. If there's
  283. // no active tunnel, the untunneledDialConfig will be used.
  284. tunnel := controller.getNextActiveTunnel()
  285. err := fetcher(
  286. controller.runCtx,
  287. controller.config,
  288. attempt,
  289. tunnel,
  290. controller.untunneledDialConfig)
  291. if err == nil {
  292. lastFetchTime = monotime.Now()
  293. break retryLoop
  294. }
  295. NoticeAlert("failed to fetch %s remote server list: %s", name, err)
  296. retryPeriod := controller.config.clientParameters.Get().Duration(
  297. parameters.FetchRemoteServerListRetryPeriod)
  298. timer := time.NewTimer(retryPeriod)
  299. select {
  300. case <-timer.C:
  301. case <-controller.runCtx.Done():
  302. timer.Stop()
  303. break fetcherLoop
  304. }
  305. }
  306. }
  307. NoticeInfo("exiting %s remote server list fetcher", name)
  308. }
  309. // establishTunnelWatcher terminates the controller if a tunnel
  310. // has not been established in the configured time period. This
  311. // is regardless of how many tunnels are presently active -- meaning
  312. // that if an active tunnel was established and lost the controller
  313. // is left running (to re-establish).
  314. func (controller *Controller) establishTunnelWatcher() {
  315. defer controller.runWaitGroup.Done()
  316. timeout := controller.config.clientParameters.Get().Duration(
  317. parameters.EstablishTunnelTimeout)
  318. if timeout > 0 {
  319. timer := time.NewTimer(timeout)
  320. defer timer.Stop()
  321. select {
  322. case <-timer.C:
  323. if !controller.hasEstablishedOnce() {
  324. NoticeAlert("failed to establish tunnel before timeout")
  325. controller.SignalComponentFailure()
  326. }
  327. case <-controller.runCtx.Done():
  328. }
  329. }
  330. NoticeInfo("exiting establish tunnel watcher")
  331. }
  332. // connectedReporter sends periodic "connected" requests to the Psiphon API.
  333. // These requests are for server-side unique user stats calculation. See the
  334. // comment in DoConnectedRequest for a description of the request mechanism.
  335. // To ensure we don't over- or under-count unique users, only one connected
  336. // request is made across all simultaneous multi-tunnels; and the connected
  337. // request is repeated periodically for very long-lived tunnels.
  338. // The signalReportConnected mechanism is used to trigger another connected
  339. // request immediately after a reconnect.
  340. func (controller *Controller) connectedReporter() {
  341. defer controller.runWaitGroup.Done()
  342. loop:
  343. for {
  344. // Pick any active tunnel and make the next connected request. No error
  345. // is logged if there's no active tunnel, as that's not an unexpected condition.
  346. reported := false
  347. tunnel := controller.getNextActiveTunnel()
  348. if tunnel != nil {
  349. err := tunnel.serverContext.DoConnectedRequest()
  350. if err == nil {
  351. reported = true
  352. } else {
  353. NoticeAlert("failed to make connected request: %s", err)
  354. }
  355. }
  356. // Schedule the next connected request and wait.
  357. // Note: this duration is not a dynamic ClientParameter as
  358. // the daily unique user stats logic specifically requires
  359. // a "connected" request no more or less often than every
  360. // 24 hours.
  361. var duration time.Duration
  362. if reported {
  363. duration = 24 * time.Hour
  364. } else {
  365. duration = controller.config.clientParameters.Get().Duration(
  366. parameters.PsiphonAPIConnectedRequestRetryPeriod)
  367. }
  368. timer := time.NewTimer(duration)
  369. doBreak := false
  370. select {
  371. case <-controller.signalReportConnected:
  372. case <-timer.C:
  373. // Make another connected request
  374. case <-controller.runCtx.Done():
  375. doBreak = true
  376. }
  377. timer.Stop()
  378. if doBreak {
  379. break loop
  380. }
  381. }
  382. NoticeInfo("exiting connected reporter")
  383. }
  384. func (controller *Controller) startOrSignalConnectedReporter() {
  385. // session is nil when DisableApi is set
  386. if controller.config.DisableApi {
  387. return
  388. }
  389. // Start the connected reporter after the first tunnel is established.
  390. // Concurrency note: only the runTunnels goroutine may access startedConnectedReporter.
  391. if !controller.startedConnectedReporter {
  392. controller.startedConnectedReporter = true
  393. controller.runWaitGroup.Add(1)
  394. go controller.connectedReporter()
  395. } else {
  396. select {
  397. case controller.signalReportConnected <- *new(struct{}):
  398. default:
  399. }
  400. }
  401. }
  402. // upgradeDownloader makes periodic attempts to complete a client upgrade
  403. // download. DownloadUpgrade() is resumable, so each attempt has potential for
  404. // getting closer to completion, even in conditions where the download or
  405. // tunnel is repeatedly interrupted.
  406. // An upgrade download is triggered by either a handshake response indicating
  407. // that a new version is available; or after failing to connect, in which case
  408. // it's useful to check, out-of-band, for an upgrade with new circumvention
  409. // capabilities.
  410. // Once the download operation completes successfully, the downloader exits
  411. // and is not run again: either there is not a newer version, or the upgrade
  412. // has been downloaded and is ready to be applied.
  413. // We're assuming that the upgrade will be applied and the entire system
  414. // restarted before another upgrade is to be downloaded.
  415. //
  416. // TODO: refactor upgrade downloader and remote server list fetcher to use
  417. // common code (including the resumable download routines).
  418. //
  419. func (controller *Controller) upgradeDownloader() {
  420. defer controller.runWaitGroup.Done()
  421. var lastDownloadTime monotime.Time
  422. downloadLoop:
  423. for {
  424. // Wait for a signal before downloading
  425. var handshakeVersion string
  426. select {
  427. case handshakeVersion = <-controller.signalDownloadUpgrade:
  428. case <-controller.runCtx.Done():
  429. break downloadLoop
  430. }
  431. stalePeriod := controller.config.clientParameters.Get().Duration(
  432. parameters.FetchUpgradeStalePeriod)
  433. // Unless handshake is explicitly advertizing a new version, skip
  434. // checking entirely when a recent download was successful.
  435. if handshakeVersion == "" &&
  436. lastDownloadTime != 0 &&
  437. lastDownloadTime.Add(stalePeriod).After(monotime.Now()) {
  438. continue
  439. }
  440. retryLoop:
  441. for attempt := 0; ; attempt++ {
  442. // Don't attempt to download while there is no network connectivity,
  443. // to avoid alert notice noise.
  444. if !WaitForNetworkConnectivity(
  445. controller.runCtx,
  446. controller.config.NetworkConnectivityChecker) {
  447. break downloadLoop
  448. }
  449. // Pick any active tunnel and make the next download attempt. If there's
  450. // no active tunnel, the untunneledDialConfig will be used.
  451. tunnel := controller.getNextActiveTunnel()
  452. err := DownloadUpgrade(
  453. controller.runCtx,
  454. controller.config,
  455. attempt,
  456. handshakeVersion,
  457. tunnel,
  458. controller.untunneledDialConfig)
  459. if err == nil {
  460. lastDownloadTime = monotime.Now()
  461. break retryLoop
  462. }
  463. NoticeAlert("failed to download upgrade: %s", err)
  464. timeout := controller.config.clientParameters.Get().Duration(
  465. parameters.FetchUpgradeRetryPeriod)
  466. timer := time.NewTimer(timeout)
  467. select {
  468. case <-timer.C:
  469. case <-controller.runCtx.Done():
  470. timer.Stop()
  471. break downloadLoop
  472. }
  473. }
  474. }
  475. NoticeInfo("exiting upgrade downloader")
  476. }
  477. // runTunnels is the controller tunnel management main loop. It starts and stops
  478. // establishing tunnels based on the target tunnel pool size and the current size
  479. // of the pool. Tunnels are established asynchronously using worker goroutines.
  480. //
  481. // When there are no server entries for the target region/protocol, the
  482. // establishCandidateGenerator will yield no candidates and wait before
  483. // trying again. In the meantime, a remote server entry fetch may supply
  484. // valid candidates.
  485. //
  486. // When a tunnel is established, it's added to the active pool. The tunnel's
  487. // operateTunnel goroutine monitors the tunnel.
  488. //
  489. // When a tunnel fails, it's removed from the pool and the establish process is
  490. // restarted to fill the pool.
  491. func (controller *Controller) runTunnels() {
  492. defer controller.runWaitGroup.Done()
  493. // Start running
  494. controller.startEstablishing()
  495. loop:
  496. for {
  497. select {
  498. case failedTunnel := <-controller.failedTunnels:
  499. NoticeAlert("tunnel failed: %s", failedTunnel.serverEntry.IpAddress)
  500. controller.terminateTunnel(failedTunnel)
  501. // Clear the reference to this tunnel before calling startEstablishing,
  502. // which will invoke a garbage collection.
  503. failedTunnel = nil
  504. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing,
  505. // which reference controller.isEstablishing.
  506. controller.startEstablishing()
  507. case connectedTunnel := <-controller.connectedTunnels:
  508. // Tunnel establishment has two phases: connection and activation.
  509. //
  510. // Connection is run concurrently by the establishTunnelWorkers, to minimize
  511. // delay when it's not yet known which server and protocol will be available
  512. // and unblocked.
  513. //
  514. // Activation is run serially, here, to minimize the overhead of making a
  515. // handshake request and starting the operateTunnel management worker for a
  516. // tunnel which may be discarded.
  517. //
  518. // When the active tunnel will complete establishment, establishment is
  519. // stopped before activation. This interrupts all connecting tunnels and
  520. // garbage collects their memory. The purpose is to minimize memory
  521. // pressure when the handshake request is made. In the unlikely case that the
  522. // handshake fails, establishment is restarted.
  523. //
  524. // Any delays in stopEstablishing will delay the handshake for the last
  525. // active tunnel.
  526. //
  527. // In the typical case of TunnelPoolSize of 1, only a single handshake is
  528. // performed and the homepages notices file, when used, will not be modifed
  529. // after the NoticeTunnels(1) [i.e., connected] until NoticeTunnels(0) [i.e.,
  530. // disconnected]. For TunnelPoolSize > 1, serial handshakes only ensures that
  531. // each set of emitted NoticeHomepages is contiguous.
  532. active, outstanding := controller.numTunnels()
  533. // discardTunnel will be true here when already fully established.
  534. discardTunnel := (outstanding <= 0)
  535. isFirstTunnel := (active == 0)
  536. isLastTunnel := (outstanding == 1)
  537. if !discardTunnel {
  538. if isLastTunnel {
  539. controller.stopEstablishing()
  540. }
  541. err := connectedTunnel.Activate(controller.runCtx, controller)
  542. if err != nil {
  543. NoticeAlert("failed to activate %s: %s", connectedTunnel.serverEntry.IpAddress, err)
  544. discardTunnel = true
  545. } else {
  546. // It's unlikely that registerTunnel will fail, since only this goroutine
  547. // calls registerTunnel -- and after checking numTunnels; so failure is not
  548. // expected.
  549. if !controller.registerTunnel(connectedTunnel) {
  550. NoticeAlert("failed to register %s: %s", connectedTunnel.serverEntry.IpAddress, err)
  551. discardTunnel = true
  552. }
  553. }
  554. // May need to replace this tunnel
  555. if isLastTunnel && discardTunnel {
  556. controller.startEstablishing()
  557. }
  558. }
  559. if discardTunnel {
  560. controller.discardTunnel(connectedTunnel)
  561. // Clear the reference to this discarded tunnel and immediately run
  562. // a garbage collection to reclaim its memory.
  563. connectedTunnel = nil
  564. DoGarbageCollection()
  565. // Skip the rest of this case
  566. break
  567. }
  568. NoticeActiveTunnel(
  569. connectedTunnel.serverEntry.IpAddress,
  570. connectedTunnel.protocol,
  571. connectedTunnel.serverEntry.SupportsSSHAPIRequests())
  572. if isFirstTunnel {
  573. // The split tunnel classifier is started once the first tunnel is
  574. // established. This first tunnel is passed in to be used to make
  575. // the routes data request.
  576. // A long-running controller may run while the host device is present
  577. // in different regions. In this case, we want the split tunnel logic
  578. // to switch to routes for new regions and not classify traffic based
  579. // on routes installed for older regions.
  580. // We assume that when regions change, the host network will also
  581. // change, and so all tunnels will fail and be re-established. Under
  582. // that assumption, the classifier will be re-Start()-ed here when
  583. // the region has changed.
  584. controller.splitTunnelClassifier.Start(connectedTunnel)
  585. // Signal a connected request on each 1st tunnel establishment. For
  586. // multi-tunnels, the session is connected as long as at least one
  587. // tunnel is established.
  588. controller.startOrSignalConnectedReporter()
  589. // If the handshake indicated that a new client version is available,
  590. // trigger an upgrade download.
  591. // Note: serverContext is nil when DisableApi is set
  592. if connectedTunnel.serverContext != nil &&
  593. connectedTunnel.serverContext.clientUpgradeVersion != "" {
  594. handshakeVersion := connectedTunnel.serverContext.clientUpgradeVersion
  595. select {
  596. case controller.signalDownloadUpgrade <- handshakeVersion:
  597. default:
  598. }
  599. }
  600. }
  601. // Set the new tunnel as the transport for the packet tunnel. The packet tunnel
  602. // client remains up when reestablishing, but no packets are relayed while there
  603. // is no connected tunnel. UseTunnel will establish a new packet tunnel SSH
  604. // channel over the new SSH tunnel and configure the packet tunnel client to use
  605. // the new SSH channel as its transport.
  606. //
  607. // Note: as is, this logic is suboptimal for TunnelPoolSize > 1, as this would
  608. // continuously initialize new packet tunnel sessions for each established
  609. // server. For now, config validation requires TunnelPoolSize == 1 when
  610. // the packet tunnel is used.
  611. if controller.packetTunnelTransport != nil {
  612. controller.packetTunnelTransport.UseTunnel(connectedTunnel)
  613. }
  614. // TODO: design issue -- might not be enough server entries with region/caps to ever fill tunnel slots;
  615. // possible solution is establish target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  616. if controller.isFullyEstablished() {
  617. controller.stopEstablishing()
  618. }
  619. case <-controller.runCtx.Done():
  620. break loop
  621. }
  622. }
  623. // Stop running
  624. controller.stopEstablishing()
  625. controller.terminateAllTunnels()
  626. // Drain tunnel channels
  627. close(controller.connectedTunnels)
  628. for tunnel := range controller.connectedTunnels {
  629. controller.discardTunnel(tunnel)
  630. }
  631. close(controller.failedTunnels)
  632. for tunnel := range controller.failedTunnels {
  633. controller.discardTunnel(tunnel)
  634. }
  635. NoticeInfo("exiting run tunnels")
  636. }
  637. // SignalSeededNewSLOK implements the TunnelOwner interface. This function
  638. // is called by Tunnel.operateTunnel when the tunnel has received a new,
  639. // previously unknown SLOK from the server. The Controller triggers an OSL
  640. // fetch, as the new SLOK may be sufficient to access new OSLs.
  641. func (controller *Controller) SignalSeededNewSLOK() {
  642. select {
  643. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  644. default:
  645. }
  646. }
  647. // SignalTunnelFailure implements the TunnelOwner interface. This function
  648. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  649. // has failed. The Controller will signal runTunnels to create a new
  650. // tunnel and/or remove the tunnel from the list of active tunnels.
  651. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  652. // Don't block. Assumes the receiver has a buffer large enough for
  653. // the typical number of operated tunnels. In case there's no room,
  654. // terminate the tunnel (runTunnels won't get a signal in this case,
  655. // but the tunnel will be removed from the list of active tunnels).
  656. select {
  657. case controller.failedTunnels <- tunnel:
  658. default:
  659. controller.terminateTunnel(tunnel)
  660. }
  661. }
  662. // discardTunnel disposes of a successful connection that is no longer required.
  663. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  664. NoticeInfo("discard tunnel: %s", tunnel.serverEntry.IpAddress)
  665. // TODO: not calling PromoteServerEntry, since that would rank the
  666. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  667. // be promoted (since it connects), but with lower rank than all active
  668. // tunnels?
  669. tunnel.Close(true)
  670. }
  671. // registerTunnel adds the connected tunnel to the pool of active tunnels
  672. // which are candidates for port forwarding. Returns true if the pool has an
  673. // empty slot and false if the pool is full (caller should discard the tunnel).
  674. func (controller *Controller) registerTunnel(tunnel *Tunnel) bool {
  675. controller.tunnelMutex.Lock()
  676. defer controller.tunnelMutex.Unlock()
  677. if len(controller.tunnels) >= controller.config.TunnelPoolSize {
  678. return false
  679. }
  680. // Perform a final check just in case we've established
  681. // a duplicate connection.
  682. for _, activeTunnel := range controller.tunnels {
  683. if activeTunnel.serverEntry.IpAddress == tunnel.serverEntry.IpAddress {
  684. NoticeAlert("duplicate tunnel: %s", tunnel.serverEntry.IpAddress)
  685. return false
  686. }
  687. }
  688. controller.establishedOnce = true
  689. controller.tunnels = append(controller.tunnels, tunnel)
  690. NoticeTunnels(len(controller.tunnels))
  691. // Promote this successful tunnel to first rank so it's one
  692. // of the first candidates next time establish runs.
  693. // Connecting to a TargetServerEntry does not change the
  694. // ranking.
  695. if controller.config.TargetServerEntry == "" {
  696. PromoteServerEntry(controller.config, tunnel.serverEntry.IpAddress)
  697. }
  698. return true
  699. }
  700. // hasEstablishedOnce indicates if at least one active tunnel has
  701. // been established up to this point. This is regardeless of how many
  702. // tunnels are presently active.
  703. func (controller *Controller) hasEstablishedOnce() bool {
  704. controller.tunnelMutex.Lock()
  705. defer controller.tunnelMutex.Unlock()
  706. return controller.establishedOnce
  707. }
  708. // isFullyEstablished indicates if the pool of active tunnels is full.
  709. func (controller *Controller) isFullyEstablished() bool {
  710. controller.tunnelMutex.Lock()
  711. defer controller.tunnelMutex.Unlock()
  712. return len(controller.tunnels) >= controller.config.TunnelPoolSize
  713. }
  714. // numTunnels returns the number of active and outstanding tunnels.
  715. // Oustanding is the number of tunnels required to fill the pool of
  716. // active tunnels.
  717. func (controller *Controller) numTunnels() (int, int) {
  718. controller.tunnelMutex.Lock()
  719. defer controller.tunnelMutex.Unlock()
  720. active := len(controller.tunnels)
  721. outstanding := controller.config.TunnelPoolSize - len(controller.tunnels)
  722. return active, outstanding
  723. }
  724. // terminateTunnel removes a tunnel from the pool of active tunnels
  725. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  726. // is adjusted as required.
  727. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  728. controller.tunnelMutex.Lock()
  729. defer controller.tunnelMutex.Unlock()
  730. for index, activeTunnel := range controller.tunnels {
  731. if tunnel == activeTunnel {
  732. controller.tunnels = append(
  733. controller.tunnels[:index], controller.tunnels[index+1:]...)
  734. if controller.nextTunnel > index {
  735. controller.nextTunnel--
  736. }
  737. if controller.nextTunnel >= len(controller.tunnels) {
  738. controller.nextTunnel = 0
  739. }
  740. activeTunnel.Close(false)
  741. NoticeTunnels(len(controller.tunnels))
  742. break
  743. }
  744. }
  745. }
  746. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  747. // This is used when shutting down the controller.
  748. func (controller *Controller) terminateAllTunnels() {
  749. controller.tunnelMutex.Lock()
  750. defer controller.tunnelMutex.Unlock()
  751. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  752. // may take a few seconds to send a final status request. We only want
  753. // to wait as long as the single slowest tunnel.
  754. closeWaitGroup := new(sync.WaitGroup)
  755. closeWaitGroup.Add(len(controller.tunnels))
  756. for _, activeTunnel := range controller.tunnels {
  757. tunnel := activeTunnel
  758. go func() {
  759. defer closeWaitGroup.Done()
  760. tunnel.Close(false)
  761. }()
  762. }
  763. closeWaitGroup.Wait()
  764. controller.tunnels = make([]*Tunnel, 0)
  765. controller.nextTunnel = 0
  766. NoticeTunnels(len(controller.tunnels))
  767. }
  768. // getNextActiveTunnel returns the next tunnel from the pool of active
  769. // tunnels. Currently, tunnel selection order is simple round-robin.
  770. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  771. controller.tunnelMutex.Lock()
  772. defer controller.tunnelMutex.Unlock()
  773. for i := len(controller.tunnels); i > 0; i-- {
  774. tunnel = controller.tunnels[controller.nextTunnel]
  775. controller.nextTunnel =
  776. (controller.nextTunnel + 1) % len(controller.tunnels)
  777. return tunnel
  778. }
  779. return nil
  780. }
  781. // isActiveTunnelServerEntry is used to check if there's already
  782. // an existing tunnel to a candidate server.
  783. func (controller *Controller) isActiveTunnelServerEntry(
  784. serverEntry *protocol.ServerEntry) bool {
  785. controller.tunnelMutex.Lock()
  786. defer controller.tunnelMutex.Unlock()
  787. for _, activeTunnel := range controller.tunnels {
  788. if activeTunnel.serverEntry.IpAddress == serverEntry.IpAddress {
  789. return true
  790. }
  791. }
  792. return false
  793. }
  794. // Dial selects an active tunnel and establishes a port forward
  795. // connection through the selected tunnel. Failure to connect is considered
  796. // a port forward failure, for the purpose of monitoring tunnel health.
  797. func (controller *Controller) Dial(
  798. remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error) {
  799. tunnel := controller.getNextActiveTunnel()
  800. if tunnel == nil {
  801. return nil, common.ContextError(errors.New("no active tunnels"))
  802. }
  803. // Perform split tunnel classification when feature is enabled, and if the remote
  804. // address is classified as untunneled, dial directly.
  805. if !alwaysTunnel && controller.config.SplitTunnelDNSServer != "" {
  806. host, _, err := net.SplitHostPort(remoteAddr)
  807. if err != nil {
  808. return nil, common.ContextError(err)
  809. }
  810. // Note: a possible optimization, when split tunnel is active and IsUntunneled performs
  811. // a DNS resolution in order to make its classification, is to reuse that IP address in
  812. // the following Dials so they do not need to make their own resolutions. However, the
  813. // way this is currently implemented ensures that, e.g., DNS geo load balancing occurs
  814. // relative to the outbound network.
  815. if controller.splitTunnelClassifier.IsUntunneled(host) {
  816. return controller.DirectDial(remoteAddr)
  817. }
  818. }
  819. tunneledConn, err := tunnel.Dial(remoteAddr, alwaysTunnel, downstreamConn)
  820. if err != nil {
  821. return nil, common.ContextError(err)
  822. }
  823. return tunneledConn, nil
  824. }
  825. // DirectDial dials an untunneled TCP connection within the controller run context.
  826. func (controller *Controller) DirectDial(remoteAddr string) (conn net.Conn, err error) {
  827. return DialTCP(controller.runCtx, remoteAddr, controller.untunneledDialConfig)
  828. }
  829. // triggerFetches signals RSL, OSL, and upgrade download fetchers to begin, if
  830. // not already running. triggerFetches is called when tunnel establishment
  831. // fails to complete within a deadline and in other cases where local
  832. // circumvention capabilities are lacking and we may require new server
  833. // entries or client versions with new capabilities.
  834. func (controller *Controller) triggerFetches() {
  835. // Trigger a common remote server list fetch, since we may have failed
  836. // to connect with all known servers. Don't block sending signal, since
  837. // this signal may have already been sent.
  838. // Don't wait for fetch remote to succeed, since it may fail and
  839. // enter a retry loop and we're better off trying more known servers.
  840. // TODO: synchronize the fetch response, so it can be incorporated
  841. // into the server entry iterator as soon as available.
  842. select {
  843. case controller.signalFetchCommonRemoteServerList <- *new(struct{}):
  844. default:
  845. }
  846. // Trigger an OSL fetch in parallel. Both fetches are run in parallel
  847. // so that if one out of the common RLS and OSL set is large, it doesn't
  848. // doesn't entirely block fetching the other.
  849. select {
  850. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  851. default:
  852. }
  853. // Trigger an out-of-band upgrade availability check and download.
  854. // Since we may have failed to connect, we may benefit from upgrading
  855. // to a new client version with new circumvention capabilities.
  856. select {
  857. case controller.signalDownloadUpgrade <- "":
  858. default:
  859. }
  860. }
  861. type limitTunnelProtocolsState struct {
  862. useUpstreamProxy bool
  863. initialProtocols protocol.TunnelProtocols
  864. initialCandidateCount int
  865. protocols protocol.TunnelProtocols
  866. }
  867. func (l *limitTunnelProtocolsState) hasInitialProtocols() bool {
  868. return len(l.initialProtocols) > 0 && l.initialCandidateCount > 0
  869. }
  870. func (l *limitTunnelProtocolsState) isInitialCandidate(
  871. excludeIntensive bool, serverEntry *protocol.ServerEntry) bool {
  872. return l.hasInitialProtocols() &&
  873. len(serverEntry.GetSupportedProtocols(l.useUpstreamProxy, l.initialProtocols, excludeIntensive)) > 0
  874. }
  875. func (l *limitTunnelProtocolsState) isCandidate(
  876. excludeIntensive bool, serverEntry *protocol.ServerEntry) bool {
  877. return len(l.protocols) == 0 ||
  878. len(serverEntry.GetSupportedProtocols(l.useUpstreamProxy, l.protocols, excludeIntensive)) > 0
  879. }
  880. var errNoProtocolSupported = errors.New("server does not support any required protocol")
  881. func (l *limitTunnelProtocolsState) selectProtocol(
  882. connectTunnelCount int, excludeIntensive bool, serverEntry *protocol.ServerEntry) (string, error) {
  883. limitProtocols := l.protocols
  884. if len(l.initialProtocols) > 0 && l.initialCandidateCount > connectTunnelCount {
  885. limitProtocols = l.initialProtocols
  886. }
  887. candidateProtocols := serverEntry.GetSupportedProtocols(
  888. l.useUpstreamProxy,
  889. limitProtocols,
  890. excludeIntensive)
  891. if len(candidateProtocols) == 0 {
  892. return "", errNoProtocolSupported
  893. }
  894. // Pick at random from the supported protocols. This ensures that we'll
  895. // eventually try all possible protocols. Depending on network
  896. // configuration, it may be the case that some protocol is only available
  897. // through multi-capability servers, and a simpler ranked preference of
  898. // protocols could lead to that protocol never being selected.
  899. index, err := common.MakeSecureRandomInt(len(candidateProtocols))
  900. if err != nil {
  901. return "", common.ContextError(err)
  902. }
  903. selectedProtocol := candidateProtocols[index]
  904. return selectedProtocol, nil
  905. }
  906. type candidateServerEntry struct {
  907. serverEntry *protocol.ServerEntry
  908. isServerAffinityCandidate bool
  909. adjustedEstablishStartTime monotime.Time
  910. }
  911. // startEstablishing creates a pool of worker goroutines which will
  912. // attempt to establish tunnels to candidate servers. The candidates
  913. // are generated by another goroutine.
  914. func (controller *Controller) startEstablishing() {
  915. if controller.isEstablishing {
  916. return
  917. }
  918. NoticeInfo("start establishing")
  919. controller.concurrentEstablishTunnelsMutex.Lock()
  920. controller.establishConnectTunnelCount = 0
  921. controller.concurrentEstablishTunnels = 0
  922. controller.concurrentIntensiveEstablishTunnels = 0
  923. controller.peakConcurrentEstablishTunnels = 0
  924. controller.peakConcurrentIntensiveEstablishTunnels = 0
  925. controller.concurrentEstablishTunnelsMutex.Unlock()
  926. DoGarbageCollection()
  927. emitMemoryMetrics()
  928. // Note: the establish context cancelFunc, controller.stopEstablish,
  929. // is called in controller.stopEstablishing.
  930. controller.isEstablishing = true
  931. controller.establishCtx, controller.stopEstablish = context.WithCancel(controller.runCtx)
  932. controller.establishWaitGroup = new(sync.WaitGroup)
  933. controller.candidateServerEntries = make(chan *candidateServerEntry)
  934. // The server affinity mechanism attempts to favor the previously
  935. // used server when reconnecting. This is beneficial for user
  936. // applications which expect consistency in user IP address (for
  937. // example, a web site which prompts for additional user
  938. // authentication when the IP address changes).
  939. //
  940. // Only the very first server, as determined by
  941. // datastore.PromoteServerEntry(), is the server affinity candidate.
  942. // Concurrent connections attempts to many servers are launched
  943. // without delay, in case the affinity server connection fails.
  944. // While the affinity server connection is outstanding, when any
  945. // other connection is established, there is a short grace period
  946. // delay before delivering the established tunnel; this allows some
  947. // time for the affinity server connection to succeed first.
  948. // When the affinity server connection fails, any other established
  949. // tunnel is registered without delay.
  950. //
  951. // Note: the establishTunnelWorker that receives the affinity
  952. // candidate is solely resonsible for closing
  953. // controller.serverAffinityDoneBroadcast.
  954. controller.serverAffinityDoneBroadcast = make(chan struct{})
  955. controller.establishWaitGroup.Add(1)
  956. go controller.launchEstablishing()
  957. }
  958. func (controller *Controller) launchEstablishing() {
  959. defer controller.establishWaitGroup.Done()
  960. // Before starting the establish tunnel workers, get and apply
  961. // tactics, launching a tactics request if required.
  962. //
  963. // Wait only TacticsWaitPeriod for the tactics request to complete (or
  964. // fail) before proceeding with tunnel establishment, in case the tactics
  965. // request is blocked or takes very long to complete.
  966. //
  967. // An in-flight tactics request uses meek in round tripper mode, which
  968. // uses less resources than meek tunnel relay mode. For this reason, the
  969. // tactics request is not counted in concurrentIntensiveEstablishTunnels.
  970. //
  971. // TODO: HTTP/2 uses significantly more memory, so perhaps
  972. // concurrentIntensiveEstablishTunnels should be counted in that case.
  973. //
  974. // Any in-flight tactics request or pending retry will be
  975. // canceled when establishment is stopped.
  976. doTactics := !controller.config.DisableTactics &&
  977. controller.config.networkIDGetter != nil
  978. if doTactics {
  979. timeout := controller.config.clientParameters.Get().Duration(
  980. parameters.TacticsWaitPeriod)
  981. tacticsDone := make(chan struct{})
  982. tacticsWaitPeriod := time.NewTimer(timeout)
  983. defer tacticsWaitPeriod.Stop()
  984. controller.establishWaitGroup.Add(1)
  985. go controller.getTactics(tacticsDone)
  986. select {
  987. case <-tacticsDone:
  988. case <-tacticsWaitPeriod.C:
  989. }
  990. tacticsWaitPeriod.Stop()
  991. if controller.isStopEstablishing() {
  992. // This check isn't strictly required by avoids the
  993. // overhead of launching workers if establishment
  994. // stopped while awaiting a tactics request.
  995. return
  996. }
  997. }
  998. // LimitTunnelProtocols and ConnectionWorkerPoolSize may be set by
  999. // tactics.
  1000. // Initial- and LimitTunnelProtocols are set once per establishment, for
  1001. // consistent application of related probabilities (applied by
  1002. // ClientParametersSnapshot.TunnelProtocols). The
  1003. // establishLimitTunnelProtocolsState field must be read-only after this
  1004. // point, allowing concurrent reads by establishment workers.
  1005. p := controller.config.clientParameters.Get()
  1006. controller.establishLimitTunnelProtocolsState = &limitTunnelProtocolsState{
  1007. useUpstreamProxy: controller.config.UseUpstreamProxy(),
  1008. initialProtocols: p.TunnelProtocols(parameters.InitialLimitTunnelProtocols),
  1009. initialCandidateCount: p.Int(parameters.InitialLimitTunnelProtocolsCandidateCount),
  1010. protocols: p.TunnelProtocols(parameters.LimitTunnelProtocols),
  1011. }
  1012. workerPoolSize := controller.config.clientParameters.Get().Int(
  1013. parameters.ConnectionWorkerPoolSize)
  1014. p = nil
  1015. // If InitialLimitTunnelProtocols is configured but cannot be satisfied,
  1016. // skip the initial phase in this establishment. This avoids spinning,
  1017. // unable to connect, in this case. InitialLimitTunnelProtocols is
  1018. // intended to prioritize certain protocols, but not strictly select them.
  1019. //
  1020. // The candidate count check is made with egress region selection unset.
  1021. // When an egress region is selected, it's the responsibility of the outer
  1022. // client to react to the following ReportAvailableRegions output and
  1023. // clear the user's selected region to prevent spinning, unable to
  1024. // connect. The initial phase is skipped only when
  1025. // InitialLimitTunnelProtocols cannot be satisfied _regardless_ of region
  1026. // selection.
  1027. //
  1028. // We presume that, in practise, most clients will have embedded server
  1029. // entries with capabilities for most protocols; and that clients will
  1030. // often perform RSL checks. So clients should most often have the
  1031. // necessary capabilities to satisfy InitialLimitTunnelProtocols. When
  1032. // this check fails, RSL/OSL/upgrade checks are triggered in order to gain
  1033. // new capabilities.
  1034. //
  1035. // LimitTunnelProtocols remains a hard limit, as using prohibited
  1036. // protocols may have some bad effect, such as a firewall blocking all
  1037. // traffic from a host.
  1038. if controller.establishLimitTunnelProtocolsState.initialCandidateCount > 0 {
  1039. egressRegion := "" // no egress region
  1040. initialCount, count := CountServerEntriesWithLimits(
  1041. controller.config.UseUpstreamProxy(),
  1042. egressRegion,
  1043. controller.establishLimitTunnelProtocolsState)
  1044. if initialCount == 0 {
  1045. NoticeCandidateServers(
  1046. egressRegion,
  1047. controller.establishLimitTunnelProtocolsState,
  1048. initialCount,
  1049. count)
  1050. NoticeAlert("skipping initial limit tunnel protocols")
  1051. controller.establishLimitTunnelProtocolsState.initialCandidateCount = 0
  1052. // Since we were unable to satisfy the InitialLimitTunnelProtocols
  1053. // tactic, trigger RSL, OSL, and upgrade fetches to potentially
  1054. // gain new capabilities.
  1055. controller.triggerFetches()
  1056. }
  1057. }
  1058. // Report available egress regions. After a fresh install, the outer
  1059. // client may not have a list of regions to display; and
  1060. // LimitTunnelProtocols may reduce the number of available regions.
  1061. //
  1062. // When the outer client receives NoticeAvailableEgressRegions and the
  1063. // configured EgressRegion is not included in the region list, the outer
  1064. // client _should_ stop tunnel-core and prompt the user to change the
  1065. // region selection, as there are insufficient servers/capabilities to
  1066. // establish a tunnel in the selected region.
  1067. //
  1068. // This report is delayed until after tactics are likely to be applied;
  1069. // this avoids a ReportAvailableRegions reporting too many regions,
  1070. // followed shortly by a ReportAvailableRegions reporting fewer regions.
  1071. // That sequence could cause issues in the outer client UI.
  1072. //
  1073. // The reported regions are limited by establishLimitTunnelProtocolsState;
  1074. // in the case where an initial limit is in place, only regions available
  1075. // for the initial limit are reported. The initial phase will not complete
  1076. // if EgressRegion is set such that there are no server entries with the
  1077. // necessary protocol capabilities (either locally or from a remote server
  1078. // list fetch).
  1079. ReportAvailableRegions(
  1080. controller.config,
  1081. controller.establishLimitTunnelProtocolsState)
  1082. for i := 0; i < workerPoolSize; i++ {
  1083. controller.establishWaitGroup.Add(1)
  1084. go controller.establishTunnelWorker()
  1085. }
  1086. controller.establishWaitGroup.Add(1)
  1087. go controller.establishCandidateGenerator()
  1088. }
  1089. // stopEstablishing signals the establish goroutines to stop and waits
  1090. // for the group to halt.
  1091. func (controller *Controller) stopEstablishing() {
  1092. if !controller.isEstablishing {
  1093. return
  1094. }
  1095. NoticeInfo("stop establishing")
  1096. controller.stopEstablish()
  1097. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  1098. // (as it may be sending to that channel).
  1099. controller.establishWaitGroup.Wait()
  1100. NoticeInfo("stopped establishing")
  1101. controller.isEstablishing = false
  1102. controller.establishCtx = nil
  1103. controller.stopEstablish = nil
  1104. controller.establishWaitGroup = nil
  1105. controller.candidateServerEntries = nil
  1106. controller.serverAffinityDoneBroadcast = nil
  1107. controller.concurrentEstablishTunnelsMutex.Lock()
  1108. peakConcurrent := controller.peakConcurrentEstablishTunnels
  1109. peakConcurrentIntensive := controller.peakConcurrentIntensiveEstablishTunnels
  1110. controller.establishConnectTunnelCount = 0
  1111. controller.concurrentEstablishTunnels = 0
  1112. controller.concurrentIntensiveEstablishTunnels = 0
  1113. controller.peakConcurrentEstablishTunnels = 0
  1114. controller.peakConcurrentIntensiveEstablishTunnels = 0
  1115. controller.concurrentEstablishTunnelsMutex.Unlock()
  1116. NoticeInfo("peak concurrent establish tunnels: %d", peakConcurrent)
  1117. NoticeInfo("peak concurrent resource intensive establish tunnels: %d", peakConcurrentIntensive)
  1118. emitMemoryMetrics()
  1119. DoGarbageCollection()
  1120. }
  1121. func (controller *Controller) getTactics(done chan struct{}) {
  1122. defer controller.establishWaitGroup.Done()
  1123. defer close(done)
  1124. tacticsRecord, err := tactics.UseStoredTactics(
  1125. GetTacticsStorer(),
  1126. controller.config.networkIDGetter.GetNetworkID())
  1127. if err != nil {
  1128. NoticeAlert("get stored tactics failed: %s", err)
  1129. // The error will be due to a local datastore problem.
  1130. // While we could proceed with the tactics request, this
  1131. // could result in constant tactics requests. So, abort.
  1132. return
  1133. }
  1134. if tacticsRecord == nil {
  1135. iterator, err := NewTacticsServerEntryIterator(
  1136. controller.config)
  1137. if err != nil {
  1138. NoticeAlert("tactics iterator failed: %s", err)
  1139. return
  1140. }
  1141. defer iterator.Close()
  1142. for iteration := 0; ; iteration++ {
  1143. if !WaitForNetworkConnectivity(
  1144. controller.runCtx,
  1145. controller.config.NetworkConnectivityChecker) {
  1146. return
  1147. }
  1148. serverEntry, err := iterator.Next()
  1149. if err != nil {
  1150. NoticeAlert("tactics iterator failed: %s", err)
  1151. return
  1152. }
  1153. if serverEntry == nil {
  1154. if iteration == 0 {
  1155. NoticeAlert("tactics request skipped: no capable servers")
  1156. return
  1157. }
  1158. iterator.Reset()
  1159. continue
  1160. }
  1161. tacticsRecord, err = controller.doFetchTactics(serverEntry)
  1162. if err == nil {
  1163. break
  1164. }
  1165. NoticeAlert("tactics request failed: %s", err)
  1166. // On error, proceed with a retry, as the error is likely
  1167. // due to a network failure.
  1168. //
  1169. // TODO: distinguish network and local errors and abort
  1170. // on local errors.
  1171. p := controller.config.clientParameters.Get()
  1172. timeout := common.JitterDuration(
  1173. p.Duration(parameters.TacticsRetryPeriod),
  1174. p.Float(parameters.TacticsRetryPeriodJitter))
  1175. p = nil
  1176. tacticsRetryDelay := time.NewTimer(timeout)
  1177. select {
  1178. case <-controller.establishCtx.Done():
  1179. return
  1180. case <-tacticsRetryDelay.C:
  1181. }
  1182. tacticsRetryDelay.Stop()
  1183. }
  1184. }
  1185. if tacticsRecord != nil &&
  1186. common.FlipWeightedCoin(tacticsRecord.Tactics.Probability) {
  1187. err := controller.config.SetClientParameters(
  1188. tacticsRecord.Tag, true, tacticsRecord.Tactics.Parameters)
  1189. if err != nil {
  1190. NoticeAlert("apply tactics failed: %s", err)
  1191. // The error will be due to invalid tactics values from
  1192. // the server. When ApplyClientParameters fails, all
  1193. // previous tactics values are left in place. Abort
  1194. // without retry since the server is highly unlikely
  1195. // to return different values immediately.
  1196. return
  1197. }
  1198. }
  1199. // Reclaim memory from the completed tactics request as we're likely
  1200. // to be proceeding to the memory-intensive tunnel establishment phase.
  1201. DoGarbageCollection()
  1202. emitMemoryMetrics()
  1203. }
  1204. func (controller *Controller) doFetchTactics(
  1205. serverEntry *protocol.ServerEntry) (*tactics.Record, error) {
  1206. tacticsProtocols := serverEntry.GetSupportedTacticsProtocols()
  1207. index, err := common.MakeSecureRandomInt(len(tacticsProtocols))
  1208. if err != nil {
  1209. return nil, common.ContextError(err)
  1210. }
  1211. tacticsProtocol := tacticsProtocols[index]
  1212. meekConfig, err := initMeekConfig(
  1213. controller.config,
  1214. serverEntry,
  1215. tacticsProtocol,
  1216. "")
  1217. if err != nil {
  1218. return nil, common.ContextError(err)
  1219. }
  1220. meekConfig.RoundTripperOnly = true
  1221. dialConfig, dialStats := initDialConfig(
  1222. controller.config, meekConfig, tacticsProtocol)
  1223. NoticeRequestingTactics(
  1224. serverEntry.IpAddress,
  1225. serverEntry.Region,
  1226. tacticsProtocol,
  1227. dialStats)
  1228. // TacticsTimeout should be a very long timeout, since it's not
  1229. // adjusted by tactics in a new network context, and so clients
  1230. // with very slow connections must be accomodated. This long
  1231. // timeout will not entirely block the beginning of tunnel
  1232. // establishment, which beings after the shorter TacticsWaitPeriod.
  1233. //
  1234. // Using controller.establishCtx will cancel FetchTactics
  1235. // if tunnel establishment completes first.
  1236. timeout := controller.config.clientParameters.Get().Duration(
  1237. parameters.TacticsTimeout)
  1238. ctx, cancelFunc := context.WithTimeout(
  1239. controller.establishCtx,
  1240. timeout)
  1241. defer cancelFunc()
  1242. // DialMeek completes the TCP/TLS handshakes for HTTPS
  1243. // meek protocols but _not_ for HTTP meek protocols.
  1244. //
  1245. // TODO: pre-dial HTTP protocols to conform with speed
  1246. // test RTT spec.
  1247. //
  1248. // TODO: ensure that meek in round trip mode will fail
  1249. // the request when the pre-dial connection is broken,
  1250. // to minimize the possibility of network ID mismatches.
  1251. meekConn, err := DialMeek(ctx, meekConfig, dialConfig)
  1252. if err != nil {
  1253. return nil, common.ContextError(err)
  1254. }
  1255. defer meekConn.Close()
  1256. apiParams := getBaseAPIParameters(
  1257. controller.config,
  1258. controller.sessionId,
  1259. serverEntry,
  1260. tacticsProtocol,
  1261. dialStats)
  1262. tacticsRecord, err := tactics.FetchTactics(
  1263. ctx,
  1264. controller.config.clientParameters,
  1265. GetTacticsStorer(),
  1266. controller.config.networkIDGetter.GetNetworkID,
  1267. apiParams,
  1268. serverEntry.Region,
  1269. tacticsProtocol,
  1270. serverEntry.TacticsRequestPublicKey,
  1271. serverEntry.TacticsRequestObfuscatedKey,
  1272. meekConn.RoundTrip)
  1273. if err != nil {
  1274. return nil, common.ContextError(err)
  1275. }
  1276. NoticeRequestedTactics(
  1277. serverEntry.IpAddress,
  1278. serverEntry.Region,
  1279. tacticsProtocol,
  1280. dialStats)
  1281. return tacticsRecord, nil
  1282. }
  1283. // establishCandidateGenerator populates the candidate queue with server entries
  1284. // from the data store. Server entries are iterated in rank order, so that promoted
  1285. // servers with higher rank are priority candidates.
  1286. func (controller *Controller) establishCandidateGenerator() {
  1287. defer controller.establishWaitGroup.Done()
  1288. defer close(controller.candidateServerEntries)
  1289. // establishStartTime is used to calculate and report the
  1290. // client's tunnel establishment duration.
  1291. //
  1292. // networkWaitDuration is the elapsed time spent waiting
  1293. // for network connectivity. This duration will be excluded
  1294. // from reported tunnel establishment duration.
  1295. establishStartTime := monotime.Now()
  1296. var totalNetworkWaitDuration time.Duration
  1297. applyServerAffinity, iterator, err := NewServerEntryIterator(controller.config)
  1298. if err != nil {
  1299. NoticeAlert("failed to iterate over candidates: %s", err)
  1300. controller.SignalComponentFailure()
  1301. return
  1302. }
  1303. defer iterator.Close()
  1304. // TODO: reconcile server affinity scheme with multi-tunnel mode
  1305. if controller.config.TunnelPoolSize > 1 {
  1306. applyServerAffinity = false
  1307. }
  1308. isServerAffinityCandidate := true
  1309. if !applyServerAffinity {
  1310. isServerAffinityCandidate = false
  1311. close(controller.serverAffinityDoneBroadcast)
  1312. }
  1313. loop:
  1314. // Repeat until stopped
  1315. for {
  1316. // For diagnostics, emits counts of the number of known server
  1317. // entries that satisfy both the egress region and tunnel protocol
  1318. // requirements (excluding excludeIntensive logic).
  1319. // Counts may change during establishment due to remote server
  1320. // list fetches, etc.
  1321. initialCount, count := CountServerEntriesWithLimits(
  1322. controller.config.UseUpstreamProxy(),
  1323. controller.config.EgressRegion,
  1324. controller.establishLimitTunnelProtocolsState)
  1325. NoticeCandidateServers(
  1326. controller.config.EgressRegion,
  1327. controller.establishLimitTunnelProtocolsState,
  1328. initialCount,
  1329. count)
  1330. // A "round" consists of a new shuffle of the server entries
  1331. // and attempted connections up to the end of the server entry
  1332. // list, or parameters.EstablishTunnelWorkTime elapsed. Time
  1333. // spent waiting for network connectivity is excluded from
  1334. // round elapsed time.
  1335. //
  1336. // If the first round ends with no connection, remote server
  1337. // list and upgrade checks are launched.
  1338. roundStartTime := monotime.Now()
  1339. var roundNetworkWaitDuration time.Duration
  1340. // Send each iterator server entry to the establish workers
  1341. for {
  1342. networkWaitStartTime := monotime.Now()
  1343. if !WaitForNetworkConnectivity(
  1344. controller.establishCtx,
  1345. controller.config.NetworkConnectivityChecker) {
  1346. break loop
  1347. }
  1348. networkWaitDuration := monotime.Since(networkWaitStartTime)
  1349. roundNetworkWaitDuration += networkWaitDuration
  1350. totalNetworkWaitDuration += networkWaitDuration
  1351. serverEntry, err := iterator.Next()
  1352. if err != nil {
  1353. NoticeAlert("failed to get next candidate: %s", err)
  1354. controller.SignalComponentFailure()
  1355. break loop
  1356. }
  1357. if serverEntry == nil {
  1358. // Completed this iteration
  1359. break
  1360. }
  1361. if controller.config.TargetApiProtocol == protocol.PSIPHON_SSH_API_PROTOCOL &&
  1362. !serverEntry.SupportsSSHAPIRequests() {
  1363. continue
  1364. }
  1365. // adjustedEstablishStartTime is establishStartTime shifted
  1366. // to exclude time spent waiting for network connectivity.
  1367. adjustedEstablishStartTime := establishStartTime.Add(totalNetworkWaitDuration)
  1368. candidate := &candidateServerEntry{
  1369. serverEntry: serverEntry,
  1370. isServerAffinityCandidate: isServerAffinityCandidate,
  1371. adjustedEstablishStartTime: adjustedEstablishStartTime,
  1372. }
  1373. wasServerAffinityCandidate := isServerAffinityCandidate
  1374. // Note: there must be only one server affinity candidate, as it
  1375. // closes the serverAffinityDoneBroadcast channel.
  1376. isServerAffinityCandidate = false
  1377. // TODO: here we could generate multiple candidates from the
  1378. // server entry when there are many MeekFrontingAddresses.
  1379. select {
  1380. case controller.candidateServerEntries <- candidate:
  1381. case <-controller.establishCtx.Done():
  1382. break loop
  1383. }
  1384. workTime := controller.config.clientParameters.Get().Duration(
  1385. parameters.EstablishTunnelWorkTime)
  1386. if roundStartTime.Add(-roundNetworkWaitDuration).Add(workTime).Before(monotime.Now()) {
  1387. // Start over, after a brief pause, with a new shuffle of the server
  1388. // entries, and potentially some newly fetched server entries.
  1389. break
  1390. }
  1391. if wasServerAffinityCandidate {
  1392. // Don't start the next candidate until either the server affinity
  1393. // candidate has completed (success or failure) or is still working
  1394. // and the grace period has elapsed.
  1395. gracePeriod := controller.config.clientParameters.Get().Duration(
  1396. parameters.EstablishTunnelServerAffinityGracePeriod)
  1397. if gracePeriod > 0 {
  1398. timer := time.NewTimer(gracePeriod)
  1399. select {
  1400. case <-timer.C:
  1401. case <-controller.serverAffinityDoneBroadcast:
  1402. case <-controller.establishCtx.Done():
  1403. timer.Stop()
  1404. break loop
  1405. }
  1406. timer.Stop()
  1407. }
  1408. } else {
  1409. p := controller.config.clientParameters.Get()
  1410. staggerPeriod := p.Duration(parameters.StaggerConnectionWorkersPeriod)
  1411. staggerJitter := p.Float(parameters.StaggerConnectionWorkersJitter)
  1412. p = nil
  1413. if staggerPeriod != 0 {
  1414. // Stagger concurrent connection workers.
  1415. timeout := common.JitterDuration(staggerPeriod, staggerJitter)
  1416. timer := time.NewTimer(timeout)
  1417. select {
  1418. case <-timer.C:
  1419. case <-controller.establishCtx.Done():
  1420. timer.Stop()
  1421. break loop
  1422. }
  1423. timer.Stop()
  1424. }
  1425. }
  1426. }
  1427. // Free up resources now, but don't reset until after the pause.
  1428. iterator.Close()
  1429. // Trigger RSL, OSL, and upgrade checks after failing to establish a
  1430. // tunnel in the first round.
  1431. controller.triggerFetches()
  1432. // After a complete iteration of candidate servers, pause before iterating again.
  1433. // This helps avoid some busy wait loop conditions, and also allows some time for
  1434. // network conditions to change. Also allows for fetch remote to complete,
  1435. // in typical conditions (it isn't strictly necessary to wait for this, there will
  1436. // be more rounds if required).
  1437. p := controller.config.clientParameters.Get()
  1438. timeout := common.JitterDuration(
  1439. p.Duration(parameters.EstablishTunnelPausePeriod),
  1440. p.Float(parameters.EstablishTunnelPausePeriodJitter))
  1441. p = nil
  1442. timer := time.NewTimer(timeout)
  1443. select {
  1444. case <-timer.C:
  1445. // Retry iterating
  1446. case <-controller.establishCtx.Done():
  1447. timer.Stop()
  1448. break loop
  1449. }
  1450. timer.Stop()
  1451. iterator.Reset()
  1452. }
  1453. }
  1454. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  1455. // a connection to the tunnel server, and delivers the connected tunnel to a channel.
  1456. func (controller *Controller) establishTunnelWorker() {
  1457. defer controller.establishWaitGroup.Done()
  1458. loop:
  1459. for candidateServerEntry := range controller.candidateServerEntries {
  1460. // Note: don't receive from candidateServerEntries and isStopEstablishing
  1461. // in the same select, since we want to prioritize receiving the stop signal
  1462. if controller.isStopEstablishing() {
  1463. break loop
  1464. }
  1465. // There may already be a tunnel to this candidate. If so, skip it.
  1466. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  1467. continue
  1468. }
  1469. // Select the tunnel protocol. The selection will be made at random from
  1470. // protocols supported by the server entry, optionally limited by
  1471. // LimitTunnelProtocols.
  1472. //
  1473. // When limiting concurrent resource intensive protocol connection
  1474. // workers, and at the limit, do not select resource intensive
  1475. // protocols since otherwise the candidate must be skipped.
  1476. //
  1477. // If at the limit and unabled to select a non-intensive protocol, skip the
  1478. // candidate entirely and move on to the next. Since candidates are shuffled
  1479. // it's likely that the next candidate is not intensive. In this case, a
  1480. // StaggerConnectionWorkersMilliseconds delay may still be incurred.
  1481. limitIntensiveConnectionWorkers := controller.config.clientParameters.Get().Int(
  1482. parameters.LimitIntensiveConnectionWorkers)
  1483. controller.concurrentEstablishTunnelsMutex.Lock()
  1484. excludeIntensive := false
  1485. if limitIntensiveConnectionWorkers > 0 &&
  1486. controller.concurrentIntensiveEstablishTunnels >= limitIntensiveConnectionWorkers {
  1487. excludeIntensive = true
  1488. }
  1489. selectedProtocol, err := controller.establishLimitTunnelProtocolsState.selectProtocol(
  1490. controller.establishConnectTunnelCount,
  1491. excludeIntensive,
  1492. candidateServerEntry.serverEntry)
  1493. if err != nil {
  1494. controller.concurrentEstablishTunnelsMutex.Unlock()
  1495. // selectProtocol returns errNoProtocolSupported when the server
  1496. // does not support any protocol that remains after applying the
  1497. // LimitTunnelProtocols parameter and the excludeIntensive flag.
  1498. // Silently skip the candidate in this case.
  1499. if err != errNoProtocolSupported {
  1500. NoticeInfo("failed to select protocol for %s: %s",
  1501. candidateServerEntry.serverEntry.IpAddress, err)
  1502. }
  1503. // Unblock other candidates immediately when server affinity
  1504. // candidate is skipped.
  1505. if candidateServerEntry.isServerAffinityCandidate {
  1506. close(controller.serverAffinityDoneBroadcast)
  1507. }
  1508. continue
  1509. }
  1510. // Increment establishConnectTunnelCount only after selectProtocol has
  1511. // succeeded to ensure InitialLimitTunnelProtocolsCandidateCount
  1512. // candidates use InitialLimitTunnelProtocols.
  1513. controller.establishConnectTunnelCount += 1
  1514. isIntensive := protocol.TunnelProtocolIsResourceIntensive(selectedProtocol)
  1515. if isIntensive {
  1516. controller.concurrentIntensiveEstablishTunnels += 1
  1517. if controller.concurrentIntensiveEstablishTunnels > controller.peakConcurrentIntensiveEstablishTunnels {
  1518. controller.peakConcurrentIntensiveEstablishTunnels = controller.concurrentIntensiveEstablishTunnels
  1519. }
  1520. }
  1521. controller.concurrentEstablishTunnels += 1
  1522. if controller.concurrentEstablishTunnels > controller.peakConcurrentEstablishTunnels {
  1523. controller.peakConcurrentEstablishTunnels = controller.concurrentEstablishTunnels
  1524. }
  1525. controller.concurrentEstablishTunnelsMutex.Unlock()
  1526. // ConnectTunnel will allocate significant memory, so first attempt to
  1527. // reclaim as much as possible.
  1528. DoGarbageCollection()
  1529. tunnel, err := ConnectTunnel(
  1530. controller.establishCtx,
  1531. controller.config,
  1532. controller.sessionId,
  1533. candidateServerEntry.serverEntry,
  1534. selectedProtocol,
  1535. candidateServerEntry.adjustedEstablishStartTime)
  1536. controller.concurrentEstablishTunnelsMutex.Lock()
  1537. if isIntensive {
  1538. controller.concurrentIntensiveEstablishTunnels -= 1
  1539. }
  1540. controller.concurrentEstablishTunnels -= 1
  1541. controller.concurrentEstablishTunnelsMutex.Unlock()
  1542. // Periodically emit memory metrics during the establishment cycle.
  1543. if !controller.isStopEstablishing() {
  1544. emitMemoryMetrics()
  1545. }
  1546. // Immediately reclaim memory allocated by the establishment. In the case
  1547. // of failure, first clear the reference to the tunnel. In the case of
  1548. // success, the garbage collection may still be effective as the initial
  1549. // phases of some protocols involve significant memory allocation that
  1550. // could now be reclaimed.
  1551. if err != nil {
  1552. tunnel = nil
  1553. }
  1554. DoGarbageCollection()
  1555. if err != nil {
  1556. // Unblock other candidates immediately when server affinity
  1557. // candidate fails.
  1558. if candidateServerEntry.isServerAffinityCandidate {
  1559. close(controller.serverAffinityDoneBroadcast)
  1560. }
  1561. // Before emitting error, check if establish interrupted, in which
  1562. // case the error is noise.
  1563. if controller.isStopEstablishing() {
  1564. break loop
  1565. }
  1566. NoticeInfo("failed to connect to %s: %s",
  1567. candidateServerEntry.serverEntry.IpAddress, err)
  1568. continue
  1569. }
  1570. // Deliver connected tunnel.
  1571. // Don't block. Assumes the receiver has a buffer large enough for
  1572. // the number of desired tunnels. If there's no room, the tunnel must
  1573. // not be required so it's discarded.
  1574. select {
  1575. case controller.connectedTunnels <- tunnel:
  1576. default:
  1577. controller.discardTunnel(tunnel)
  1578. // Clear the reference to this discarded tunnel and immediately run
  1579. // a garbage collection to reclaim its memory.
  1580. tunnel = nil
  1581. DoGarbageCollection()
  1582. }
  1583. // Unblock other candidates only after delivering when
  1584. // server affinity candidate succeeds.
  1585. if candidateServerEntry.isServerAffinityCandidate {
  1586. close(controller.serverAffinityDoneBroadcast)
  1587. }
  1588. }
  1589. }
  1590. func (controller *Controller) isStopEstablishing() bool {
  1591. select {
  1592. case <-controller.establishCtx.Done():
  1593. return true
  1594. default:
  1595. }
  1596. return false
  1597. }