controller.go 65 KB

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