controller.go 63 KB

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