controller.go 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868
  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. if !WaitForNetworkConnectivity(
  1090. controller.runCtx,
  1091. controller.config.NetworkConnectivityChecker) {
  1092. return
  1093. }
  1094. serverEntry, err := iterator.Next()
  1095. if err != nil {
  1096. NoticeAlert("tactics iterator failed: %s", err)
  1097. return
  1098. }
  1099. if serverEntry == nil {
  1100. if iteration == 0 {
  1101. NoticeAlert("tactics request skipped: no capable servers")
  1102. return
  1103. }
  1104. iterator.Reset()
  1105. continue
  1106. }
  1107. tacticsRecord, err = controller.doFetchTactics(serverEntry)
  1108. if err == nil {
  1109. break
  1110. }
  1111. NoticeAlert("tactics request failed: %s", err)
  1112. // On error, proceed with a retry, as the error is likely
  1113. // due to a network failure.
  1114. //
  1115. // TODO: distinguish network and local errors and abort
  1116. // on local errors.
  1117. p := controller.config.clientParameters.Get()
  1118. timeout := common.JitterDuration(
  1119. p.Duration(parameters.TacticsRetryPeriod),
  1120. p.Float(parameters.TacticsRetryPeriodJitter))
  1121. p = nil
  1122. tacticsRetryDelay := time.NewTimer(timeout)
  1123. select {
  1124. case <-controller.establishCtx.Done():
  1125. return
  1126. case <-tacticsRetryDelay.C:
  1127. default:
  1128. }
  1129. tacticsRetryDelay.Stop()
  1130. }
  1131. }
  1132. if tacticsRecord != nil &&
  1133. common.FlipWeightedCoin(tacticsRecord.Tactics.Probability) {
  1134. err := controller.config.SetClientParameters(
  1135. tacticsRecord.Tag, true, tacticsRecord.Tactics.Parameters)
  1136. if err != nil {
  1137. NoticeAlert("apply tactics failed: %s", err)
  1138. // The error will be due to invalid tactics values from
  1139. // the server. When ApplyClientParameters fails, all
  1140. // previous tactics values are left in place. Abort
  1141. // without retry since the server is highly unlikely
  1142. // to return different values immediately.
  1143. return
  1144. }
  1145. }
  1146. // Reclaim memory from the completed tactics request as we're likely
  1147. // to be proceeding to the memory-intensive tunnel establishment phase.
  1148. aggressiveGarbageCollection()
  1149. emitMemoryMetrics()
  1150. }
  1151. func (controller *Controller) doFetchTactics(
  1152. serverEntry *protocol.ServerEntry) (*tactics.Record, error) {
  1153. tacticsProtocols := serverEntry.GetSupportedTacticsProtocols()
  1154. index, err := common.MakeSecureRandomInt(len(tacticsProtocols))
  1155. if err != nil {
  1156. return nil, common.ContextError(err)
  1157. }
  1158. tacticsProtocol := tacticsProtocols[index]
  1159. meekConfig, err := initMeekConfig(
  1160. controller.config,
  1161. serverEntry,
  1162. tacticsProtocol,
  1163. "")
  1164. if err != nil {
  1165. return nil, common.ContextError(err)
  1166. }
  1167. meekConfig.RoundTripperOnly = true
  1168. dialConfig, dialStats := initDialConfig(controller.config, meekConfig)
  1169. NoticeRequestingTactics(
  1170. serverEntry.IpAddress,
  1171. serverEntry.Region,
  1172. tacticsProtocol,
  1173. dialStats)
  1174. // TacticsTimeout should be a very long timeout, since it's not
  1175. // adjusted by tactics in a new network context, and so clients
  1176. // with very slow connections must be accomodated. This long
  1177. // timeout will not entirely block the beginning of tunnel
  1178. // establishment, which beings after the shorter TacticsWaitPeriod.
  1179. //
  1180. // Using controller.establishCtx will cancel FetchTactics
  1181. // if tunnel establishment completes first.
  1182. timeout := controller.config.clientParameters.Get().Duration(
  1183. parameters.TacticsTimeout)
  1184. ctx, cancelFunc := context.WithTimeout(
  1185. controller.establishCtx,
  1186. timeout)
  1187. defer cancelFunc()
  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. //
  1194. // TODO: ensure that meek in round trip mode will fail
  1195. // the request when the pre-dial connection is broken,
  1196. // to minimize the possibility of network ID mismatches.
  1197. meekConn, err := DialMeek(ctx, meekConfig, dialConfig)
  1198. if err != nil {
  1199. return nil, common.ContextError(err)
  1200. }
  1201. defer meekConn.Close()
  1202. apiParams := getBaseAPIParameters(
  1203. controller.config,
  1204. controller.sessionId,
  1205. serverEntry,
  1206. tacticsProtocol,
  1207. dialStats)
  1208. tacticsRecord, err := tactics.FetchTactics(
  1209. ctx,
  1210. controller.config.clientParameters,
  1211. GetTacticsStorer(),
  1212. controller.config.NetworkIDGetter.GetNetworkID,
  1213. apiParams,
  1214. serverEntry.Region,
  1215. tacticsProtocol,
  1216. serverEntry.TacticsRequestPublicKey,
  1217. serverEntry.TacticsRequestObfuscatedKey,
  1218. meekConn.RoundTrip)
  1219. if err != nil {
  1220. return nil, common.ContextError(err)
  1221. }
  1222. NoticeRequestedTactics(
  1223. serverEntry.IpAddress,
  1224. serverEntry.Region,
  1225. tacticsProtocol,
  1226. dialStats)
  1227. return tacticsRecord, nil
  1228. }
  1229. // establishCandidateGenerator populates the candidate queue with server entries
  1230. // from the data store. Server entries are iterated in rank order, so that promoted
  1231. // servers with higher rank are priority candidates.
  1232. func (controller *Controller) establishCandidateGenerator(impairedProtocols []string) {
  1233. defer controller.establishWaitGroup.Done()
  1234. defer close(controller.candidateServerEntries)
  1235. // establishStartTime is used to calculate and report the
  1236. // client's tunnel establishment duration.
  1237. //
  1238. // networkWaitDuration is the elapsed time spent waiting
  1239. // for network connectivity. This duration will be excluded
  1240. // from reported tunnel establishment duration.
  1241. establishStartTime := monotime.Now()
  1242. var networkWaitDuration time.Duration
  1243. applyServerAffinity, iterator, err := NewServerEntryIterator(controller.config)
  1244. if err != nil {
  1245. NoticeAlert("failed to iterate over candidates: %s", err)
  1246. controller.SignalComponentFailure()
  1247. return
  1248. }
  1249. defer iterator.Close()
  1250. // TODO: reconcile server affinity scheme with multi-tunnel mode
  1251. if controller.config.TunnelPoolSize > 1 {
  1252. applyServerAffinity = false
  1253. }
  1254. isServerAffinityCandidate := true
  1255. if !applyServerAffinity {
  1256. isServerAffinityCandidate = false
  1257. close(controller.serverAffinityDoneBroadcast)
  1258. }
  1259. candidateCount := 0
  1260. loop:
  1261. // Repeat until stopped
  1262. for i := 0; ; i++ {
  1263. networkWaitStartTime := monotime.Now()
  1264. if !WaitForNetworkConnectivity(
  1265. controller.establishCtx,
  1266. controller.config.NetworkConnectivityChecker) {
  1267. break loop
  1268. }
  1269. networkWaitDuration += monotime.Since(networkWaitStartTime)
  1270. // Send each iterator server entry to the establish workers
  1271. startTime := monotime.Now()
  1272. for {
  1273. serverEntry, err := iterator.Next()
  1274. if err != nil {
  1275. NoticeAlert("failed to get next candidate: %s", err)
  1276. controller.SignalComponentFailure()
  1277. break loop
  1278. }
  1279. if serverEntry == nil {
  1280. // Completed this iteration
  1281. break
  1282. }
  1283. if controller.config.TargetApiProtocol == protocol.PSIPHON_SSH_API_PROTOCOL &&
  1284. !serverEntry.SupportsSSHAPIRequests() {
  1285. continue
  1286. }
  1287. // Use a prioritized tunnel protocol for the first
  1288. // PrioritizeTunnelProtocolsCandidateCount candidates.
  1289. // This facility can be used to favor otherwise slower
  1290. // protocols.
  1291. prioritizeCandidateCount := controller.config.clientParameters.Get().Int(
  1292. parameters.PrioritizeTunnelProtocolsCandidateCount)
  1293. usePriorityProtocol := candidateCount < prioritizeCandidateCount
  1294. // Disable impaired protocols. This is only done for the
  1295. // first iteration of the EstablishTunnelWorkTime
  1296. // loop since (a) one iteration should be sufficient to
  1297. // evade the attack; (b) there's a good chance of false
  1298. // positives (such as short tunnel durations due to network
  1299. // hopping on a mobile device).
  1300. var candidateImpairedProtocols []string
  1301. if i == 0 {
  1302. candidateImpairedProtocols = impairedProtocols
  1303. }
  1304. // adjustedEstablishStartTime is establishStartTime shifted
  1305. // to exclude time spent waiting for network connectivity.
  1306. adjustedEstablishStartTime := establishStartTime.Add(networkWaitDuration)
  1307. candidate := &candidateServerEntry{
  1308. serverEntry: serverEntry,
  1309. isServerAffinityCandidate: isServerAffinityCandidate,
  1310. usePriorityProtocol: usePriorityProtocol,
  1311. impairedProtocols: candidateImpairedProtocols,
  1312. adjustedEstablishStartTime: adjustedEstablishStartTime,
  1313. }
  1314. wasServerAffinityCandidate := isServerAffinityCandidate
  1315. // Note: there must be only one server affinity candidate, as it
  1316. // closes the serverAffinityDoneBroadcast channel.
  1317. isServerAffinityCandidate = false
  1318. // TODO: here we could generate multiple candidates from the
  1319. // server entry when there are many MeekFrontingAddresses.
  1320. candidateCount++
  1321. select {
  1322. case controller.candidateServerEntries <- candidate:
  1323. case <-controller.establishCtx.Done():
  1324. break loop
  1325. }
  1326. workTime := controller.config.clientParameters.Get().Duration(
  1327. parameters.EstablishTunnelWorkTime)
  1328. if startTime.Add(workTime).Before(monotime.Now()) {
  1329. // Start over, after a brief pause, with a new shuffle of the server
  1330. // entries, and potentially some newly fetched server entries.
  1331. break
  1332. }
  1333. if wasServerAffinityCandidate {
  1334. // Don't start the next candidate until either the server affinity
  1335. // candidate has completed (success or failure) or is still working
  1336. // and the grace period has elapsed.
  1337. gracePeriod := controller.config.clientParameters.Get().Duration(
  1338. parameters.EstablishTunnelServerAffinityGracePeriod)
  1339. if gracePeriod > 0 {
  1340. timer := time.NewTimer(gracePeriod)
  1341. select {
  1342. case <-timer.C:
  1343. case <-controller.serverAffinityDoneBroadcast:
  1344. case <-controller.establishCtx.Done():
  1345. timer.Stop()
  1346. break loop
  1347. }
  1348. timer.Stop()
  1349. }
  1350. } else {
  1351. p := controller.config.clientParameters.Get()
  1352. staggerPeriod := p.Duration(parameters.StaggerConnectionWorkersPeriod)
  1353. staggerJitter := p.Float(parameters.StaggerConnectionWorkersJitter)
  1354. p = nil
  1355. if staggerPeriod != 0 {
  1356. // Stagger concurrent connection workers.
  1357. timeout := common.JitterDuration(staggerPeriod, staggerJitter)
  1358. timer := time.NewTimer(timeout)
  1359. select {
  1360. case <-timer.C:
  1361. case <-controller.establishCtx.Done():
  1362. timer.Stop()
  1363. break loop
  1364. }
  1365. timer.Stop()
  1366. }
  1367. }
  1368. }
  1369. // Free up resources now, but don't reset until after the pause.
  1370. iterator.Close()
  1371. // Trigger a common remote server list fetch, since we may have failed
  1372. // to connect with all known servers. Don't block sending signal, since
  1373. // this signal may have already been sent.
  1374. // Don't wait for fetch remote to succeed, since it may fail and
  1375. // enter a retry loop and we're better off trying more known servers.
  1376. // TODO: synchronize the fetch response, so it can be incorporated
  1377. // into the server entry iterator as soon as available.
  1378. select {
  1379. case controller.signalFetchCommonRemoteServerList <- *new(struct{}):
  1380. default:
  1381. }
  1382. // Trigger an OSL fetch in parallel. Both fetches are run in parallel
  1383. // so that if one out of the common RLS and OSL set is large, it doesn't
  1384. // doesn't entirely block fetching the other.
  1385. select {
  1386. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  1387. default:
  1388. }
  1389. // Trigger an out-of-band upgrade availability check and download.
  1390. // Since we may have failed to connect, we may benefit from upgrading
  1391. // to a new client version with new circumvention capabilities.
  1392. select {
  1393. case controller.signalDownloadUpgrade <- "":
  1394. default:
  1395. }
  1396. // After a complete iteration of candidate servers, pause before iterating again.
  1397. // This helps avoid some busy wait loop conditions, and also allows some time for
  1398. // network conditions to change. Also allows for fetch remote to complete,
  1399. // in typical conditions (it isn't strictly necessary to wait for this, there will
  1400. // be more rounds if required).
  1401. p := controller.config.clientParameters.Get()
  1402. timeout := common.JitterDuration(
  1403. p.Duration(parameters.EstablishTunnelPausePeriod),
  1404. p.Float(parameters.EstablishTunnelPausePeriodJitter))
  1405. p = nil
  1406. timer := time.NewTimer(timeout)
  1407. select {
  1408. case <-timer.C:
  1409. // Retry iterating
  1410. case <-controller.establishCtx.Done():
  1411. timer.Stop()
  1412. break loop
  1413. }
  1414. timer.Stop()
  1415. iterator.Reset()
  1416. }
  1417. }
  1418. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  1419. // a connection to the tunnel server, and delivers the connected tunnel to a channel.
  1420. func (controller *Controller) establishTunnelWorker() {
  1421. defer controller.establishWaitGroup.Done()
  1422. loop:
  1423. for candidateServerEntry := range controller.candidateServerEntries {
  1424. // Note: don't receive from candidateServerEntries and isStopEstablishing
  1425. // in the same select, since we want to prioritize receiving the stop signal
  1426. if controller.isStopEstablishing() {
  1427. break loop
  1428. }
  1429. // There may already be a tunnel to this candidate. If so, skip it.
  1430. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  1431. continue
  1432. }
  1433. // ConnectTunnel will allocate significant memory, so first attempt to
  1434. // reclaim as much as possible.
  1435. defaultGarbageCollection()
  1436. // Select the tunnel protocol. The selection will be made at random from
  1437. // protocols supported by the server entry, optionally limited by
  1438. // LimitTunnelProtocols.
  1439. //
  1440. // When limiting concurrent meek connection workers, and at the limit,
  1441. // do not select meek since otherwise the candidate must be skipped.
  1442. //
  1443. // If at the limit and unabled to select a non-meek protocol, skip the
  1444. // candidate entirely and move on to the next. Since candidates are shuffled
  1445. // it's probable that the next candidate is not meek. In this case, a
  1446. // StaggerConnectionWorkersMilliseconds delay may still be incurred.
  1447. limitMeekConnectionWorkers := controller.config.clientParameters.Get().Int(
  1448. parameters.LimitMeekConnectionWorkers)
  1449. excludeMeek := false
  1450. controller.concurrentEstablishTunnelsMutex.Lock()
  1451. if limitMeekConnectionWorkers > 0 &&
  1452. controller.concurrentMeekEstablishTunnels >=
  1453. limitMeekConnectionWorkers {
  1454. excludeMeek = true
  1455. }
  1456. controller.concurrentEstablishTunnelsMutex.Unlock()
  1457. selectedProtocol, err := selectProtocol(
  1458. controller.config,
  1459. candidateServerEntry.serverEntry,
  1460. candidateServerEntry.impairedProtocols,
  1461. excludeMeek,
  1462. candidateServerEntry.usePriorityProtocol)
  1463. if err == errNoProtocolSupported {
  1464. // selectProtocol returns errNoProtocolSupported when the server
  1465. // does not support any protocol that remains after applying the
  1466. // LimitTunnelProtocols parameter, the impaired protocol filter,
  1467. // and the excludeMeek flag.
  1468. // Skip this candidate.
  1469. // Unblock other candidates immediately when
  1470. // server affinity candidate is skipped.
  1471. if candidateServerEntry.isServerAffinityCandidate {
  1472. close(controller.serverAffinityDoneBroadcast)
  1473. }
  1474. continue
  1475. }
  1476. var tunnel *Tunnel
  1477. if err == nil {
  1478. isMeek := protocol.TunnelProtocolUsesMeek(selectedProtocol)
  1479. controller.concurrentEstablishTunnelsMutex.Lock()
  1480. if isMeek {
  1481. // Recheck the limit now that we know we're selecting meek and
  1482. // adjusting concurrentMeekEstablishTunnels.
  1483. if limitMeekConnectionWorkers > 0 &&
  1484. controller.concurrentMeekEstablishTunnels >=
  1485. limitMeekConnectionWorkers {
  1486. // Skip this candidate.
  1487. controller.concurrentEstablishTunnelsMutex.Unlock()
  1488. continue
  1489. }
  1490. controller.concurrentMeekEstablishTunnels += 1
  1491. if controller.concurrentMeekEstablishTunnels > controller.peakConcurrentMeekEstablishTunnels {
  1492. controller.peakConcurrentMeekEstablishTunnels = controller.concurrentMeekEstablishTunnels
  1493. }
  1494. }
  1495. controller.concurrentEstablishTunnels += 1
  1496. if controller.concurrentEstablishTunnels > controller.peakConcurrentEstablishTunnels {
  1497. controller.peakConcurrentEstablishTunnels = controller.concurrentEstablishTunnels
  1498. }
  1499. controller.concurrentEstablishTunnelsMutex.Unlock()
  1500. tunnel, err = ConnectTunnel(
  1501. controller.establishCtx,
  1502. controller.config,
  1503. controller.sessionId,
  1504. candidateServerEntry.serverEntry,
  1505. selectedProtocol,
  1506. candidateServerEntry.adjustedEstablishStartTime)
  1507. controller.concurrentEstablishTunnelsMutex.Lock()
  1508. if isMeek {
  1509. controller.concurrentMeekEstablishTunnels -= 1
  1510. }
  1511. controller.concurrentEstablishTunnels -= 1
  1512. controller.concurrentEstablishTunnelsMutex.Unlock()
  1513. }
  1514. // Periodically emit memory metrics during the establishment cycle.
  1515. if !controller.isStopEstablishing() {
  1516. emitMemoryMetrics()
  1517. }
  1518. // Immediately reclaim memory allocated by the establishment. In the case
  1519. // of failure, first clear the reference to the tunnel. In the case of
  1520. // success, the garbage collection may still be effective as the initial
  1521. // phases of some protocols involve significant memory allocation that
  1522. // could now be reclaimed.
  1523. if err != nil {
  1524. tunnel = nil
  1525. }
  1526. defaultGarbageCollection()
  1527. if err != nil {
  1528. // Unblock other candidates immediately when
  1529. // server affinity candidate fails.
  1530. if candidateServerEntry.isServerAffinityCandidate {
  1531. close(controller.serverAffinityDoneBroadcast)
  1532. }
  1533. // Before emitting error, check if establish interrupted, in which
  1534. // case the error is noise.
  1535. if controller.isStopEstablishing() {
  1536. break loop
  1537. }
  1538. NoticeInfo("failed to connect to %s: %s", candidateServerEntry.serverEntry.IpAddress, err)
  1539. continue
  1540. }
  1541. // Deliver connected tunnel.
  1542. // Don't block. Assumes the receiver has a buffer large enough for
  1543. // the number of desired tunnels. If there's no room, the tunnel must
  1544. // not be required so it's discarded.
  1545. select {
  1546. case controller.connectedTunnels <- tunnel:
  1547. default:
  1548. controller.discardTunnel(tunnel)
  1549. // Clear the reference to this discarded tunnel and immediately run
  1550. // a garbage collection to reclaim its memory.
  1551. tunnel = nil
  1552. defaultGarbageCollection()
  1553. }
  1554. // Unblock other candidates only after delivering when
  1555. // server affinity candidate succeeds.
  1556. if candidateServerEntry.isServerAffinityCandidate {
  1557. close(controller.serverAffinityDoneBroadcast)
  1558. }
  1559. }
  1560. }
  1561. func (controller *Controller) isStopEstablishing() bool {
  1562. select {
  1563. case <-controller.establishCtx.Done():
  1564. return true
  1565. default:
  1566. }
  1567. return false
  1568. }