controller.go 62 KB

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