controller.go 66 KB

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