controller.go 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869
  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. ResetRepetitiveNotices()
  151. ReportAvailableRegions(controller.config)
  152. runCtx, stopRunning := context.WithCancel(ctx)
  153. defer stopRunning()
  154. controller.runCtx = runCtx
  155. controller.stopRunning = stopRunning
  156. // Start components
  157. // TODO: IPv6 support
  158. var listenIP string
  159. if controller.config.ListenInterface == "" {
  160. listenIP = "127.0.0.1"
  161. } else if controller.config.ListenInterface == "any" {
  162. listenIP = "0.0.0.0"
  163. } else {
  164. IPv4Address, _, err := common.GetInterfaceIPAddresses(controller.config.ListenInterface)
  165. if err == nil && IPv4Address == nil {
  166. err = fmt.Errorf("no IPv4 address for interface %s", controller.config.ListenInterface)
  167. }
  168. if err != nil {
  169. NoticeError("error getting listener IP: %s", err)
  170. return
  171. }
  172. listenIP = IPv4Address.String()
  173. }
  174. if !controller.config.DisableLocalSocksProxy {
  175. socksProxy, err := NewSocksProxy(controller.config, controller, listenIP)
  176. if err != nil {
  177. NoticeAlert("error initializing local SOCKS proxy: %s", err)
  178. return
  179. }
  180. defer socksProxy.Close()
  181. }
  182. if !controller.config.DisableLocalHTTPProxy {
  183. httpProxy, err := NewHttpProxy(controller.config, controller, listenIP)
  184. if err != nil {
  185. NoticeAlert("error initializing local HTTP proxy: %s", err)
  186. return
  187. }
  188. defer httpProxy.Close()
  189. }
  190. if !controller.config.DisableRemoteServerListFetcher {
  191. if controller.config.RemoteServerListURLs != nil {
  192. controller.runWaitGroup.Add(1)
  193. go controller.remoteServerListFetcher(
  194. "common",
  195. FetchCommonRemoteServerList,
  196. controller.signalFetchCommonRemoteServerList)
  197. }
  198. if controller.config.ObfuscatedServerListRootURLs != nil {
  199. controller.runWaitGroup.Add(1)
  200. go controller.remoteServerListFetcher(
  201. "obfuscated",
  202. FetchObfuscatedServerLists,
  203. controller.signalFetchObfuscatedServerLists)
  204. }
  205. }
  206. if controller.config.UpgradeDownloadURLs != nil {
  207. controller.runWaitGroup.Add(1)
  208. go controller.upgradeDownloader()
  209. }
  210. /// Note: the connected reporter isn't started until a tunnel is
  211. // established
  212. controller.runWaitGroup.Add(1)
  213. go controller.runTunnels()
  214. controller.runWaitGroup.Add(1)
  215. go controller.establishTunnelWatcher()
  216. if controller.packetTunnelClient != nil {
  217. controller.packetTunnelClient.Start()
  218. }
  219. // Wait while running
  220. <-controller.runCtx.Done()
  221. NoticeInfo("controller stopped")
  222. if controller.packetTunnelClient != nil {
  223. controller.packetTunnelClient.Stop()
  224. }
  225. // All workers -- runTunnels, establishment workers, and auxilliary
  226. // workers such as fetch remote server list and untunneled uprade
  227. // download -- operate with the controller run context and will all
  228. // be interrupted when the run context is done.
  229. controller.runWaitGroup.Wait()
  230. controller.splitTunnelClassifier.Shutdown()
  231. NoticeInfo("exiting controller")
  232. NoticeExiting()
  233. }
  234. // SignalComponentFailure notifies the controller that an associated component has failed.
  235. // This will terminate the controller.
  236. func (controller *Controller) SignalComponentFailure() {
  237. NoticeAlert("controller shutdown due to component failure")
  238. controller.stopRunning()
  239. }
  240. // SetClientVerificationPayloadForActiveTunnels sets the client verification
  241. // payload that is to be sent in client verification requests to all established
  242. // tunnels.
  243. //
  244. // Client verification is used to verify that the client is a
  245. // valid Psiphon client, which will determine how the server treats
  246. // the client traffic. The proof-of-validity is platform-specific
  247. // and the payload is opaque to this function but assumed to be JSON.
  248. //
  249. // Since, in some cases, verification payload cannot be determined until
  250. // after tunnel-core starts, the payload cannot be simply specified in
  251. // the Config.
  252. //
  253. // SetClientVerificationPayloadForActiveTunnels will not block enqueuing a new verification
  254. // payload. One new payload can be enqueued, after which additional payloads
  255. // will be dropped if a payload is still enqueued.
  256. func (controller *Controller) SetClientVerificationPayloadForActiveTunnels(clientVerificationPayload string) {
  257. select {
  258. case controller.newClientVerificationPayload <- clientVerificationPayload:
  259. default:
  260. }
  261. }
  262. // remoteServerListFetcher fetches an out-of-band list of server entries
  263. // for more tunnel candidates. It fetches when signalled, with retries
  264. // on failure.
  265. func (controller *Controller) remoteServerListFetcher(
  266. name string,
  267. fetcher RemoteServerListFetcher,
  268. signal <-chan struct{}) {
  269. defer controller.runWaitGroup.Done()
  270. var lastFetchTime monotime.Time
  271. fetcherLoop:
  272. for {
  273. // Wait for a signal before fetching
  274. select {
  275. case <-signal:
  276. case <-controller.runCtx.Done():
  277. break fetcherLoop
  278. }
  279. // Skip fetch entirely (i.e., send no request at all, even when ETag would save
  280. // on response size) when a recent fetch was successful
  281. stalePeriod := controller.config.clientParameters.Get().Duration(
  282. parameters.FetchRemoteServerListStalePeriod)
  283. if lastFetchTime != 0 &&
  284. lastFetchTime.Add(stalePeriod).After(monotime.Now()) {
  285. continue
  286. }
  287. retryLoop:
  288. for attempt := 0; ; attempt++ {
  289. // Don't attempt to fetch while there is no network connectivity,
  290. // to avoid alert notice noise.
  291. if !WaitForNetworkConnectivity(
  292. controller.runCtx,
  293. controller.config.NetworkConnectivityChecker) {
  294. break fetcherLoop
  295. }
  296. // Pick any active tunnel and make the next fetch attempt. If there's
  297. // no active tunnel, the untunneledDialConfig will be used.
  298. tunnel := controller.getNextActiveTunnel()
  299. err := fetcher(
  300. controller.runCtx,
  301. controller.config,
  302. attempt,
  303. tunnel,
  304. controller.untunneledDialConfig)
  305. if err == nil {
  306. lastFetchTime = monotime.Now()
  307. break retryLoop
  308. }
  309. NoticeAlert("failed to fetch %s remote server list: %s", name, err)
  310. retryPeriod := controller.config.clientParameters.Get().Duration(
  311. parameters.FetchRemoteServerListRetryPeriod)
  312. timer := time.NewTimer(retryPeriod)
  313. select {
  314. case <-timer.C:
  315. case <-controller.runCtx.Done():
  316. timer.Stop()
  317. break fetcherLoop
  318. }
  319. }
  320. }
  321. NoticeInfo("exiting %s remote server list fetcher", name)
  322. }
  323. // establishTunnelWatcher terminates the controller if a tunnel
  324. // has not been established in the configured time period. This
  325. // is regardless of how many tunnels are presently active -- meaning
  326. // that if an active tunnel was established and lost the controller
  327. // is left running (to re-establish).
  328. func (controller *Controller) establishTunnelWatcher() {
  329. defer controller.runWaitGroup.Done()
  330. timeout := controller.config.clientParameters.Get().Duration(
  331. parameters.EstablishTunnelTimeout)
  332. if timeout > 0 {
  333. timer := time.NewTimer(timeout)
  334. defer timer.Stop()
  335. select {
  336. case <-timer.C:
  337. if !controller.hasEstablishedOnce() {
  338. NoticeAlert("failed to establish tunnel before timeout")
  339. controller.SignalComponentFailure()
  340. }
  341. case <-controller.runCtx.Done():
  342. }
  343. }
  344. NoticeInfo("exiting establish tunnel watcher")
  345. }
  346. // connectedReporter sends periodic "connected" requests to the Psiphon API.
  347. // These requests are for server-side unique user stats calculation. See the
  348. // comment in DoConnectedRequest for a description of the request mechanism.
  349. // To ensure we don't over- or under-count unique users, only one connected
  350. // request is made across all simultaneous multi-tunnels; and the connected
  351. // request is repeated periodically for very long-lived tunnels.
  352. // The signalReportConnected mechanism is used to trigger another connected
  353. // request immediately after a reconnect.
  354. func (controller *Controller) connectedReporter() {
  355. defer controller.runWaitGroup.Done()
  356. loop:
  357. for {
  358. // Pick any active tunnel and make the next connected request. No error
  359. // is logged if there's no active tunnel, as that's not an unexpected condition.
  360. reported := false
  361. tunnel := controller.getNextActiveTunnel()
  362. if tunnel != nil {
  363. err := tunnel.serverContext.DoConnectedRequest()
  364. if err == nil {
  365. reported = true
  366. } else {
  367. NoticeAlert("failed to make connected request: %s", err)
  368. }
  369. }
  370. // Schedule the next connected request and wait.
  371. // Note: this duration is not a dynamic ClientParameter as
  372. // the daily unique user stats logic specifically requires
  373. // a "connected" request no more or less often than every
  374. // 24 hours.
  375. var duration time.Duration
  376. if reported {
  377. duration = 24 * time.Hour
  378. } else {
  379. duration = controller.config.clientParameters.Get().Duration(
  380. parameters.PsiphonAPIConnectedRequestRetryPeriod)
  381. }
  382. timer := time.NewTimer(duration)
  383. doBreak := false
  384. select {
  385. case <-controller.signalReportConnected:
  386. case <-timer.C:
  387. // Make another connected request
  388. case <-controller.runCtx.Done():
  389. doBreak = true
  390. }
  391. timer.Stop()
  392. if doBreak {
  393. break loop
  394. }
  395. }
  396. NoticeInfo("exiting connected reporter")
  397. }
  398. func (controller *Controller) startOrSignalConnectedReporter() {
  399. // session is nil when DisableApi is set
  400. if controller.config.DisableApi {
  401. return
  402. }
  403. // Start the connected reporter after the first tunnel is established.
  404. // Concurrency note: only the runTunnels goroutine may access startedConnectedReporter.
  405. if !controller.startedConnectedReporter {
  406. controller.startedConnectedReporter = true
  407. controller.runWaitGroup.Add(1)
  408. go controller.connectedReporter()
  409. } else {
  410. select {
  411. case controller.signalReportConnected <- *new(struct{}):
  412. default:
  413. }
  414. }
  415. }
  416. // upgradeDownloader makes periodic attempts to complete a client upgrade
  417. // download. DownloadUpgrade() is resumable, so each attempt has potential for
  418. // getting closer to completion, even in conditions where the download or
  419. // tunnel is repeatedly interrupted.
  420. // An upgrade download is triggered by either a handshake response indicating
  421. // that a new version is available; or after failing to connect, in which case
  422. // it's useful to check, out-of-band, for an upgrade with new circumvention
  423. // capabilities.
  424. // Once the download operation completes successfully, the downloader exits
  425. // and is not run again: either there is not a newer version, or the upgrade
  426. // has been downloaded and is ready to be applied.
  427. // We're assuming that the upgrade will be applied and the entire system
  428. // restarted before another upgrade is to be downloaded.
  429. //
  430. // TODO: refactor upgrade downloader and remote server list fetcher to use
  431. // common code (including the resumable download routines).
  432. //
  433. func (controller *Controller) upgradeDownloader() {
  434. defer controller.runWaitGroup.Done()
  435. var lastDownloadTime monotime.Time
  436. downloadLoop:
  437. for {
  438. // Wait for a signal before downloading
  439. var handshakeVersion string
  440. select {
  441. case handshakeVersion = <-controller.signalDownloadUpgrade:
  442. case <-controller.runCtx.Done():
  443. break downloadLoop
  444. }
  445. stalePeriod := controller.config.clientParameters.Get().Duration(
  446. parameters.FetchUpgradeStalePeriod)
  447. // Unless handshake is explicitly advertizing a new version, skip
  448. // checking entirely when a recent download was successful.
  449. if handshakeVersion == "" &&
  450. lastDownloadTime != 0 &&
  451. lastDownloadTime.Add(stalePeriod).After(monotime.Now()) {
  452. continue
  453. }
  454. retryLoop:
  455. for attempt := 0; ; attempt++ {
  456. // Don't attempt to download while there is no network connectivity,
  457. // to avoid alert notice noise.
  458. if !WaitForNetworkConnectivity(
  459. controller.runCtx,
  460. controller.config.NetworkConnectivityChecker) {
  461. break downloadLoop
  462. }
  463. // Pick any active tunnel and make the next download attempt. If there's
  464. // no active tunnel, the untunneledDialConfig will be used.
  465. tunnel := controller.getNextActiveTunnel()
  466. err := DownloadUpgrade(
  467. controller.runCtx,
  468. controller.config,
  469. attempt,
  470. handshakeVersion,
  471. tunnel,
  472. controller.untunneledDialConfig)
  473. if err == nil {
  474. lastDownloadTime = monotime.Now()
  475. break retryLoop
  476. }
  477. NoticeAlert("failed to download upgrade: %s", err)
  478. timeout := controller.config.clientParameters.Get().Duration(
  479. parameters.FetchUpgradeRetryPeriod)
  480. timer := time.NewTimer(timeout)
  481. select {
  482. case <-timer.C:
  483. case <-controller.runCtx.Done():
  484. timer.Stop()
  485. break downloadLoop
  486. }
  487. }
  488. }
  489. NoticeInfo("exiting upgrade downloader")
  490. }
  491. // runTunnels is the controller tunnel management main loop. It starts and stops
  492. // establishing tunnels based on the target tunnel pool size and the current size
  493. // of the pool. Tunnels are established asynchronously using worker goroutines.
  494. //
  495. // When there are no server entries for the target region/protocol, the
  496. // establishCandidateGenerator will yield no candidates and wait before
  497. // trying again. In the meantime, a remote server entry fetch may supply
  498. // valid candidates.
  499. //
  500. // When a tunnel is established, it's added to the active pool. The tunnel's
  501. // operateTunnel goroutine monitors the tunnel.
  502. //
  503. // When a tunnel fails, it's removed from the pool and the establish process is
  504. // restarted to fill the pool.
  505. func (controller *Controller) runTunnels() {
  506. defer controller.runWaitGroup.Done()
  507. var clientVerificationPayload string
  508. // Start running
  509. controller.startEstablishing()
  510. loop:
  511. for {
  512. select {
  513. case failedTunnel := <-controller.failedTunnels:
  514. NoticeAlert("tunnel failed: %s", failedTunnel.serverEntry.IpAddress)
  515. controller.terminateTunnel(failedTunnel)
  516. controller.classifyImpairedProtocol(failedTunnel)
  517. // Clear the reference to this tunnel before calling startEstablishing,
  518. // which will invoke a garbage collection.
  519. failedTunnel = nil
  520. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing,
  521. // which reference controller.isEstablishing.
  522. controller.startEstablishing()
  523. case connectedTunnel := <-controller.connectedTunnels:
  524. if controller.isImpairedProtocol(connectedTunnel.protocol) {
  525. // Protocol was classified as impaired while this tunnel established.
  526. // This is most likely to occur with TunnelPoolSize > 0. We log the
  527. // event but take no action. Discarding the tunnel would break the
  528. // impaired logic unless we did that (a) only if there are other
  529. // unimpaired protocols; (b) only during the first iteration of the
  530. // ESTABLISH_TUNNEL_WORK_TIME loop. By not discarding here, a true
  531. // impaired protocol may require an extra reconnect.
  532. NoticeAlert("connected tunnel with impaired protocol: %s", connectedTunnel.protocol)
  533. }
  534. // Tunnel establishment has two phases: connection and activation.
  535. //
  536. // Connection is run concurrently by the establishTunnelWorkers, to minimize
  537. // delay when it's not yet known which server and protocol will be available
  538. // and unblocked.
  539. //
  540. // Activation is run serially, here, to minimize the overhead of making a
  541. // handshake request and starting the operateTunnel management worker for a
  542. // tunnel which may be discarded.
  543. //
  544. // When the active tunnel will complete establishment, establishment is
  545. // stopped before activation. This interrupts all connecting tunnels and
  546. // garbage collects their memory. The purpose is to minimize memory
  547. // pressure when the handshake request is made. In the unlikely case that the
  548. // handshake fails, establishment is restarted.
  549. //
  550. // Any delays in stopEstablishing will delay the handshake for the last
  551. // active tunnel.
  552. //
  553. // In the typical case of TunnelPoolSize of 1, only a single handshake is
  554. // performed and the homepages notices file, when used, will not be modifed
  555. // after the NoticeTunnels(1) [i.e., connected] until NoticeTunnels(0) [i.e.,
  556. // disconnected]. For TunnelPoolSize > 1, serial handshakes only ensures that
  557. // each set of emitted NoticeHomepages is contiguous.
  558. active, outstanding := controller.numTunnels()
  559. // discardTunnel will be true here when already fully established.
  560. discardTunnel := (outstanding <= 0)
  561. isFirstTunnel := (active == 0)
  562. isLastTunnel := (outstanding == 1)
  563. if !discardTunnel {
  564. if isLastTunnel {
  565. controller.stopEstablishing()
  566. }
  567. err := connectedTunnel.Activate(controller.runCtx, controller)
  568. if err != nil {
  569. // Assume the Activate failed due to a broken tunnel connection,
  570. // currently the most likely case, and classify as impaired, as in
  571. // the failed tunnel case above.
  572. // TODO: distinguish between network and other errors
  573. controller.classifyImpairedProtocol(connectedTunnel)
  574. NoticeAlert("failed to activate %s: %s", connectedTunnel.serverEntry.IpAddress, err)
  575. discardTunnel = true
  576. } else {
  577. // It's unlikely that registerTunnel will fail, since only this goroutine
  578. // calls registerTunnel -- and after checking numTunnels; so failure is not
  579. // expected.
  580. if !controller.registerTunnel(connectedTunnel) {
  581. NoticeAlert("failed to register %s: %s", connectedTunnel.serverEntry.IpAddress)
  582. discardTunnel = true
  583. }
  584. }
  585. // May need to replace this tunnel
  586. if isLastTunnel && discardTunnel {
  587. controller.startEstablishing()
  588. }
  589. }
  590. if discardTunnel {
  591. controller.discardTunnel(connectedTunnel)
  592. // Clear the reference to this discarded tunnel and immediately run
  593. // a garbage collection to reclaim its memory.
  594. connectedTunnel = nil
  595. defaultGarbageCollection()
  596. // Skip the rest of this case
  597. break
  598. }
  599. NoticeActiveTunnel(
  600. connectedTunnel.serverEntry.IpAddress,
  601. connectedTunnel.protocol,
  602. connectedTunnel.serverEntry.SupportsSSHAPIRequests())
  603. if isFirstTunnel {
  604. // The split tunnel classifier is started once the first tunnel is
  605. // established. This first tunnel is passed in to be used to make
  606. // the routes data request.
  607. // A long-running controller may run while the host device is present
  608. // in different regions. In this case, we want the split tunnel logic
  609. // to switch to routes for new regions and not classify traffic based
  610. // on routes installed for older regions.
  611. // We assume that when regions change, the host network will also
  612. // change, and so all tunnels will fail and be re-established. Under
  613. // that assumption, the classifier will be re-Start()-ed here when
  614. // the region has changed.
  615. controller.splitTunnelClassifier.Start(connectedTunnel)
  616. // Signal a connected request on each 1st tunnel establishment. For
  617. // multi-tunnels, the session is connected as long as at least one
  618. // tunnel is established.
  619. controller.startOrSignalConnectedReporter()
  620. // If the handshake indicated that a new client version is available,
  621. // trigger an upgrade download.
  622. // Note: serverContext is nil when DisableApi is set
  623. if connectedTunnel.serverContext != nil &&
  624. connectedTunnel.serverContext.clientUpgradeVersion != "" {
  625. handshakeVersion := connectedTunnel.serverContext.clientUpgradeVersion
  626. select {
  627. case controller.signalDownloadUpgrade <- handshakeVersion:
  628. default:
  629. }
  630. }
  631. }
  632. // Set the new tunnel as the transport for the packet tunnel. The packet tunnel
  633. // client remains up when reestablishing, but no packets are relayed while there
  634. // is no connected tunnel. UseTunnel will establish a new packet tunnel SSH
  635. // channel over the new SSH tunnel and configure the packet tunnel client to use
  636. // the new SSH channel as its transport.
  637. //
  638. // Note: as is, this logic is suboptimal for TunnelPoolSize > 1, as this would
  639. // continuously initialize new packet tunnel sessions for each established
  640. // server. For now, config validation requires TunnelPoolSize == 1 when
  641. // the packet tunnel is used.
  642. if controller.packetTunnelTransport != nil {
  643. controller.packetTunnelTransport.UseTunnel(connectedTunnel)
  644. }
  645. // TODO: design issue -- might not be enough server entries with region/caps to ever fill tunnel slots;
  646. // possible solution is establish target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  647. if controller.isFullyEstablished() {
  648. controller.stopEstablishing()
  649. }
  650. case clientVerificationPayload = <-controller.newClientVerificationPayload:
  651. controller.setClientVerificationPayloadForActiveTunnels(clientVerificationPayload)
  652. case <-controller.runCtx.Done():
  653. break loop
  654. }
  655. }
  656. // Stop running
  657. controller.stopEstablishing()
  658. controller.terminateAllTunnels()
  659. // Drain tunnel channels
  660. close(controller.connectedTunnels)
  661. for tunnel := range controller.connectedTunnels {
  662. controller.discardTunnel(tunnel)
  663. }
  664. close(controller.failedTunnels)
  665. for tunnel := range controller.failedTunnels {
  666. controller.discardTunnel(tunnel)
  667. }
  668. NoticeInfo("exiting run tunnels")
  669. }
  670. // TerminateNextActiveTunnel is a support routine for
  671. // test code that must terminate the active tunnel and
  672. // restart establishing. This function is not guaranteed
  673. // to be safe for use in other cases.
  674. func (controller *Controller) TerminateNextActiveTunnel() {
  675. tunnel := controller.getNextActiveTunnel()
  676. if tunnel != nil {
  677. controller.SignalTunnelFailure(tunnel)
  678. NoticeInfo("terminated tunnel: %s", tunnel.serverEntry.IpAddress)
  679. }
  680. }
  681. // classifyImpairedProtocol tracks "impaired" protocol classifications for failed
  682. // tunnels. A protocol is classified as impaired if a tunnel using that protocol
  683. // fails, repeatedly, shortly after the start of the connection. During tunnel
  684. // establishment, impaired protocols are briefly skipped.
  685. //
  686. // One purpose of this measure is to defend against an attack where the adversary,
  687. // for example, tags an OSSH TCP connection as an "unidentified" protocol; allows
  688. // it to connect; but then kills the underlying TCP connection after a short time.
  689. // Since OSSH has less latency than other protocols that may bypass an "unidentified"
  690. // filter, these other protocols might never be selected for use.
  691. //
  692. // Concurrency note: only the runTunnels() goroutine may call classifyImpairedProtocol
  693. func (controller *Controller) classifyImpairedProtocol(failedTunnel *Tunnel) {
  694. // If the tunnel failed while activating, its establishedTime will be 0.
  695. duration := controller.config.clientParameters.Get().Duration(
  696. parameters.ImpairedProtocolClassificationDuration)
  697. if failedTunnel.establishedTime == 0 ||
  698. failedTunnel.establishedTime.Add(duration).After(monotime.Now()) {
  699. controller.impairedProtocolClassification[failedTunnel.protocol] += 1
  700. } else {
  701. controller.impairedProtocolClassification[failedTunnel.protocol] = 0
  702. }
  703. // Reset classification once all known protocols are classified as impaired, as
  704. // there is now no way to proceed with only unimpaired protocols. The network
  705. // situation (or attack) resulting in classification may not be protocol-specific.
  706. if CountNonImpairedProtocols(
  707. controller.config.EgressRegion,
  708. controller.config.clientParameters.Get().TunnelProtocols(
  709. parameters.LimitTunnelProtocols),
  710. controller.getImpairedProtocols()) == 0 {
  711. controller.impairedProtocolClassification = make(map[string]int)
  712. }
  713. }
  714. // getImpairedProtocols returns a list of protocols that have sufficient
  715. // classifications to be considered impaired protocols.
  716. //
  717. // Concurrency note: only the runTunnels() goroutine may call getImpairedProtocols
  718. func (controller *Controller) getImpairedProtocols() []string {
  719. NoticeImpairedProtocolClassification(controller.impairedProtocolClassification)
  720. threshold := controller.config.clientParameters.Get().Int(
  721. parameters.ImpairedProtocolClassificationThreshold)
  722. impairedProtocols := make([]string, 0)
  723. for protocol, count := range controller.impairedProtocolClassification {
  724. if count >= threshold {
  725. impairedProtocols = append(impairedProtocols, protocol)
  726. }
  727. }
  728. return impairedProtocols
  729. }
  730. // isImpairedProtocol checks if the specified protocol is classified as impaired.
  731. //
  732. // Concurrency note: only the runTunnels() goroutine may call isImpairedProtocol
  733. func (controller *Controller) isImpairedProtocol(protocol string) bool {
  734. threshold := controller.config.clientParameters.Get().Int(
  735. parameters.ImpairedProtocolClassificationThreshold)
  736. count, ok := controller.impairedProtocolClassification[protocol]
  737. return ok && count >= threshold
  738. }
  739. // SignalSeededNewSLOK implements the TunnelOwner interface. This function
  740. // is called by Tunnel.operateTunnel when the tunnel has received a new,
  741. // previously unknown SLOK from the server. The Controller triggers an OSL
  742. // fetch, as the new SLOK may be sufficient to access new OSLs.
  743. func (controller *Controller) SignalSeededNewSLOK() {
  744. select {
  745. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  746. default:
  747. }
  748. }
  749. // SignalTunnelFailure implements the TunnelOwner interface. This function
  750. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  751. // has failed. The Controller will signal runTunnels to create a new
  752. // tunnel and/or remove the tunnel from the list of active tunnels.
  753. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  754. // Don't block. Assumes the receiver has a buffer large enough for
  755. // the typical number of operated tunnels. In case there's no room,
  756. // terminate the tunnel (runTunnels won't get a signal in this case,
  757. // but the tunnel will be removed from the list of active tunnels).
  758. select {
  759. case controller.failedTunnels <- tunnel:
  760. default:
  761. controller.terminateTunnel(tunnel)
  762. }
  763. }
  764. // discardTunnel disposes of a successful connection that is no longer required.
  765. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  766. NoticeInfo("discard tunnel: %s", tunnel.serverEntry.IpAddress)
  767. // TODO: not calling PromoteServerEntry, since that would rank the
  768. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  769. // be promoted (since it connects), but with lower rank than all active
  770. // tunnels?
  771. tunnel.Close(true)
  772. }
  773. // registerTunnel adds the connected tunnel to the pool of active tunnels
  774. // which are candidates for port forwarding. Returns true if the pool has an
  775. // empty slot and false if the pool is full (caller should discard the tunnel).
  776. func (controller *Controller) registerTunnel(tunnel *Tunnel) bool {
  777. controller.tunnelMutex.Lock()
  778. defer controller.tunnelMutex.Unlock()
  779. if len(controller.tunnels) >= controller.config.TunnelPoolSize {
  780. return false
  781. }
  782. // Perform a final check just in case we've established
  783. // a duplicate connection.
  784. for _, activeTunnel := range controller.tunnels {
  785. if activeTunnel.serverEntry.IpAddress == tunnel.serverEntry.IpAddress {
  786. NoticeAlert("duplicate tunnel: %s", tunnel.serverEntry.IpAddress)
  787. return false
  788. }
  789. }
  790. controller.establishedOnce = true
  791. controller.tunnels = append(controller.tunnels, tunnel)
  792. NoticeTunnels(len(controller.tunnels))
  793. // Promote this successful tunnel to first rank so it's one
  794. // of the first candidates next time establish runs.
  795. // Connecting to a TargetServerEntry does not change the
  796. // ranking.
  797. if controller.config.TargetServerEntry == "" {
  798. PromoteServerEntry(controller.config, tunnel.serverEntry.IpAddress)
  799. }
  800. return true
  801. }
  802. // hasEstablishedOnce indicates if at least one active tunnel has
  803. // been established up to this point. This is regardeless of how many
  804. // tunnels are presently active.
  805. func (controller *Controller) hasEstablishedOnce() bool {
  806. controller.tunnelMutex.Lock()
  807. defer controller.tunnelMutex.Unlock()
  808. return controller.establishedOnce
  809. }
  810. // isFullyEstablished indicates if the pool of active tunnels is full.
  811. func (controller *Controller) isFullyEstablished() bool {
  812. controller.tunnelMutex.Lock()
  813. defer controller.tunnelMutex.Unlock()
  814. return len(controller.tunnels) >= controller.config.TunnelPoolSize
  815. }
  816. // numTunnels returns the number of active and outstanding tunnels.
  817. // Oustanding is the number of tunnels required to fill the pool of
  818. // active tunnels.
  819. func (controller *Controller) numTunnels() (int, int) {
  820. controller.tunnelMutex.Lock()
  821. defer controller.tunnelMutex.Unlock()
  822. active := len(controller.tunnels)
  823. outstanding := controller.config.TunnelPoolSize - len(controller.tunnels)
  824. return active, outstanding
  825. }
  826. // terminateTunnel removes a tunnel from the pool of active tunnels
  827. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  828. // is adjusted as required.
  829. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  830. controller.tunnelMutex.Lock()
  831. defer controller.tunnelMutex.Unlock()
  832. for index, activeTunnel := range controller.tunnels {
  833. if tunnel == activeTunnel {
  834. controller.tunnels = append(
  835. controller.tunnels[:index], controller.tunnels[index+1:]...)
  836. if controller.nextTunnel > index {
  837. controller.nextTunnel--
  838. }
  839. if controller.nextTunnel >= len(controller.tunnels) {
  840. controller.nextTunnel = 0
  841. }
  842. activeTunnel.Close(false)
  843. NoticeTunnels(len(controller.tunnels))
  844. break
  845. }
  846. }
  847. }
  848. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  849. // This is used when shutting down the controller.
  850. func (controller *Controller) terminateAllTunnels() {
  851. controller.tunnelMutex.Lock()
  852. defer controller.tunnelMutex.Unlock()
  853. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  854. // may take a few seconds to send a final status request. We only want
  855. // to wait as long as the single slowest tunnel.
  856. closeWaitGroup := new(sync.WaitGroup)
  857. closeWaitGroup.Add(len(controller.tunnels))
  858. for _, activeTunnel := range controller.tunnels {
  859. tunnel := activeTunnel
  860. go func() {
  861. defer closeWaitGroup.Done()
  862. tunnel.Close(false)
  863. }()
  864. }
  865. closeWaitGroup.Wait()
  866. controller.tunnels = make([]*Tunnel, 0)
  867. controller.nextTunnel = 0
  868. NoticeTunnels(len(controller.tunnels))
  869. }
  870. // getNextActiveTunnel returns the next tunnel from the pool of active
  871. // tunnels. Currently, tunnel selection order is simple round-robin.
  872. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  873. controller.tunnelMutex.Lock()
  874. defer controller.tunnelMutex.Unlock()
  875. for i := len(controller.tunnels); i > 0; i-- {
  876. tunnel = controller.tunnels[controller.nextTunnel]
  877. controller.nextTunnel =
  878. (controller.nextTunnel + 1) % len(controller.tunnels)
  879. return tunnel
  880. }
  881. return nil
  882. }
  883. // isActiveTunnelServerEntry is used to check if there's already
  884. // an existing tunnel to a candidate server.
  885. func (controller *Controller) isActiveTunnelServerEntry(
  886. serverEntry *protocol.ServerEntry) bool {
  887. controller.tunnelMutex.Lock()
  888. defer controller.tunnelMutex.Unlock()
  889. for _, activeTunnel := range controller.tunnels {
  890. if activeTunnel.serverEntry.IpAddress == serverEntry.IpAddress {
  891. return true
  892. }
  893. }
  894. return false
  895. }
  896. // setClientVerificationPayloadForActiveTunnels triggers the client verification
  897. // request for all active tunnels.
  898. func (controller *Controller) setClientVerificationPayloadForActiveTunnels(
  899. clientVerificationPayload string) {
  900. controller.tunnelMutex.Lock()
  901. defer controller.tunnelMutex.Unlock()
  902. for _, activeTunnel := range controller.tunnels {
  903. activeTunnel.SetClientVerificationPayload(clientVerificationPayload)
  904. }
  905. }
  906. // Dial selects an active tunnel and establishes a port forward
  907. // connection through the selected tunnel. Failure to connect is considered
  908. // a port forward failure, for the purpose of monitoring tunnel health.
  909. func (controller *Controller) Dial(
  910. remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error) {
  911. tunnel := controller.getNextActiveTunnel()
  912. if tunnel == nil {
  913. return nil, common.ContextError(errors.New("no active tunnels"))
  914. }
  915. // Perform split tunnel classification when feature is enabled, and if the remote
  916. // address is classified as untunneled, dial directly.
  917. if !alwaysTunnel && controller.config.SplitTunnelDNSServer != "" {
  918. host, _, err := net.SplitHostPort(remoteAddr)
  919. if err != nil {
  920. return nil, common.ContextError(err)
  921. }
  922. // Note: a possible optimization, when split tunnel is active and IsUntunneled performs
  923. // a DNS resolution in order to make its classification, is to reuse that IP address in
  924. // the following Dials so they do not need to make their own resolutions. However, the
  925. // way this is currently implemented ensures that, e.g., DNS geo load balancing occurs
  926. // relative to the outbound network.
  927. if controller.splitTunnelClassifier.IsUntunneled(host) {
  928. return controller.DirectDial(remoteAddr)
  929. }
  930. }
  931. tunneledConn, err := tunnel.Dial(remoteAddr, alwaysTunnel, downstreamConn)
  932. if err != nil {
  933. return nil, common.ContextError(err)
  934. }
  935. return tunneledConn, nil
  936. }
  937. // DirectDial dials an untunneled TCP connection within the controller run context.
  938. func (controller *Controller) DirectDial(remoteAddr string) (conn net.Conn, err error) {
  939. return DialTCP(controller.runCtx, remoteAddr, controller.untunneledDialConfig)
  940. }
  941. // startEstablishing creates a pool of worker goroutines which will
  942. // attempt to establish tunnels to candidate servers. The candidates
  943. // are generated by another goroutine.
  944. func (controller *Controller) startEstablishing() {
  945. if controller.isEstablishing {
  946. return
  947. }
  948. NoticeInfo("start establishing")
  949. controller.concurrentEstablishTunnelsMutex.Lock()
  950. controller.concurrentEstablishTunnels = 0
  951. controller.concurrentMeekEstablishTunnels = 0
  952. controller.peakConcurrentEstablishTunnels = 0
  953. controller.peakConcurrentMeekEstablishTunnels = 0
  954. controller.concurrentEstablishTunnelsMutex.Unlock()
  955. aggressiveGarbageCollection()
  956. emitMemoryMetrics()
  957. // Note: the establish context cancelFunc, controller.stopEstablish,
  958. // is called in controller.stopEstablishing.
  959. controller.isEstablishing = true
  960. controller.establishCtx, controller.stopEstablish = context.WithCancel(controller.runCtx)
  961. controller.establishWaitGroup = new(sync.WaitGroup)
  962. controller.candidateServerEntries = make(chan *candidateServerEntry)
  963. // The server affinity mechanism attempts to favor the previously
  964. // used server when reconnecting. This is beneficial for user
  965. // applications which expect consistency in user IP address (for
  966. // example, a web site which prompts for additional user
  967. // authentication when the IP address changes).
  968. //
  969. // Only the very first server, as determined by
  970. // datastore.PromoteServerEntry(), is the server affinity candidate.
  971. // Concurrent connections attempts to many servers are launched
  972. // without delay, in case the affinity server connection fails.
  973. // While the affinity server connection is outstanding, when any
  974. // other connection is established, there is a short grace period
  975. // delay before delivering the established tunnel; this allows some
  976. // time for the affinity server connection to succeed first.
  977. // When the affinity server connection fails, any other established
  978. // tunnel is registered without delay.
  979. //
  980. // Note: the establishTunnelWorker that receives the affinity
  981. // candidate is solely resonsible for closing
  982. // controller.serverAffinityDoneBroadcast.
  983. controller.serverAffinityDoneBroadcast = make(chan struct{})
  984. controller.establishWaitGroup.Add(1)
  985. go controller.launchEstablishing()
  986. }
  987. func (controller *Controller) launchEstablishing() {
  988. defer controller.establishWaitGroup.Done()
  989. // Before starting the establish tunnel workers, get and apply
  990. // tactics, launching a tactics request if required.
  991. //
  992. // Wait only TacticsWaitPeriod for the tactics request to complete (or
  993. // fail) before proceeding with tunnel establishment, in case the tactics
  994. // request is blocked or takes very long to complete.
  995. //
  996. // An in-flight tactics request uses meek in round tripper mode, which
  997. // uses less resources than meek tunnel relay mode. For this reason, the
  998. // tactics request is not counted in concurrentMeekEstablishTunnels.
  999. //
  1000. // TODO: HTTP/2 uses significantly more memory, so perhaps
  1001. // concurrentMeekEstablishTunnels should be counted in that case.
  1002. //
  1003. // Any in-flight tactics request or pending retry will be
  1004. // canceled when establishment is stopped.
  1005. doTactics := (controller.config.NetworkIDGetter != nil)
  1006. if doTactics {
  1007. timeout := controller.config.clientParameters.Get().Duration(
  1008. parameters.TacticsWaitPeriod)
  1009. tacticsDone := make(chan struct{})
  1010. tacticsWaitPeriod := time.NewTimer(timeout)
  1011. defer tacticsWaitPeriod.Stop()
  1012. controller.establishWaitGroup.Add(1)
  1013. go controller.getTactics(tacticsDone)
  1014. select {
  1015. case <-tacticsDone:
  1016. case <-tacticsWaitPeriod.C:
  1017. }
  1018. tacticsWaitPeriod.Stop()
  1019. if controller.isStopEstablishing() {
  1020. // This check isn't strictly required by avoids the
  1021. // overhead of launching workers if establishment
  1022. // stopped while awaiting a tactics request.
  1023. return
  1024. }
  1025. }
  1026. // The ConnectionWorkerPoolSize may be set by tactics.
  1027. size := controller.config.clientParameters.Get().Int(
  1028. parameters.ConnectionWorkerPoolSize)
  1029. for i := 0; i < size; i++ {
  1030. controller.establishWaitGroup.Add(1)
  1031. go controller.establishTunnelWorker()
  1032. }
  1033. controller.establishWaitGroup.Add(1)
  1034. go controller.establishCandidateGenerator(
  1035. controller.getImpairedProtocols())
  1036. }
  1037. // stopEstablishing signals the establish goroutines to stop and waits
  1038. // for the group to halt.
  1039. func (controller *Controller) stopEstablishing() {
  1040. if !controller.isEstablishing {
  1041. return
  1042. }
  1043. NoticeInfo("stop establishing")
  1044. controller.stopEstablish()
  1045. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  1046. // (as it may be sending to that channel).
  1047. controller.establishWaitGroup.Wait()
  1048. NoticeInfo("stopped establishing")
  1049. controller.isEstablishing = false
  1050. controller.establishCtx = nil
  1051. controller.stopEstablish = nil
  1052. controller.establishWaitGroup = nil
  1053. controller.candidateServerEntries = nil
  1054. controller.serverAffinityDoneBroadcast = nil
  1055. controller.concurrentEstablishTunnelsMutex.Lock()
  1056. peakConcurrent := controller.peakConcurrentEstablishTunnels
  1057. peakConcurrentMeek := controller.peakConcurrentMeekEstablishTunnels
  1058. controller.concurrentEstablishTunnels = 0
  1059. controller.concurrentMeekEstablishTunnels = 0
  1060. controller.peakConcurrentEstablishTunnels = 0
  1061. controller.peakConcurrentMeekEstablishTunnels = 0
  1062. controller.concurrentEstablishTunnelsMutex.Unlock()
  1063. NoticeInfo("peak concurrent establish tunnels: %d", peakConcurrent)
  1064. NoticeInfo("peak concurrent meek establish tunnels: %d", peakConcurrentMeek)
  1065. emitMemoryMetrics()
  1066. standardGarbageCollection()
  1067. }
  1068. func (controller *Controller) getTactics(done chan struct{}) {
  1069. defer controller.establishWaitGroup.Done()
  1070. defer close(done)
  1071. tacticsRecord, err := tactics.UseStoredTactics(
  1072. GetTacticsStorer(),
  1073. controller.config.NetworkIDGetter.GetNetworkID())
  1074. if err != nil {
  1075. NoticeAlert("get stored tactics failed: %s", err)
  1076. // The error will be due to a local datastore problem.
  1077. // While we could proceed with the tactics request, this
  1078. // could result in constant tactics requests. So, abort.
  1079. return
  1080. }
  1081. if tacticsRecord == nil {
  1082. iterator, err := NewTacticsServerEntryIterator(
  1083. controller.config)
  1084. if err != nil {
  1085. NoticeAlert("tactics iterator failed: %s", err)
  1086. return
  1087. }
  1088. defer iterator.Close()
  1089. for iteration := 0; ; iteration++ {
  1090. if !WaitForNetworkConnectivity(
  1091. controller.runCtx,
  1092. controller.config.NetworkConnectivityChecker) {
  1093. return
  1094. }
  1095. serverEntry, err := iterator.Next()
  1096. if err != nil {
  1097. NoticeAlert("tactics iterator failed: %s", err)
  1098. return
  1099. }
  1100. if serverEntry == nil {
  1101. if iteration == 0 {
  1102. NoticeAlert("tactics request skipped: no capable servers")
  1103. return
  1104. }
  1105. iterator.Reset()
  1106. continue
  1107. }
  1108. tacticsRecord, err = controller.doFetchTactics(serverEntry)
  1109. if err == nil {
  1110. break
  1111. }
  1112. NoticeAlert("tactics request failed: %s", err)
  1113. // On error, proceed with a retry, as the error is likely
  1114. // due to a network failure.
  1115. //
  1116. // TODO: distinguish network and local errors and abort
  1117. // on local errors.
  1118. p := controller.config.clientParameters.Get()
  1119. timeout := common.JitterDuration(
  1120. p.Duration(parameters.TacticsRetryPeriod),
  1121. p.Float(parameters.TacticsRetryPeriodJitter))
  1122. p = nil
  1123. tacticsRetryDelay := time.NewTimer(timeout)
  1124. select {
  1125. case <-controller.establishCtx.Done():
  1126. return
  1127. case <-tacticsRetryDelay.C:
  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. }