controller.go 62 KB

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