controller.go 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367
  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. "fmt"
  27. "math/rand"
  28. "net"
  29. "runtime"
  30. "sync"
  31. "sync/atomic"
  32. "time"
  33. tls "github.com/Psiphon-Labs/psiphon-tls"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/resolver"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  41. lrucache "github.com/cognusion/go-cache-lru"
  42. utls "github.com/refraction-networking/utls"
  43. )
  44. // Controller is a tunnel lifecycle coordinator. It manages lists of servers to
  45. // connect to; establishes and monitors tunnels; and runs local proxies which
  46. // route traffic through the tunnels.
  47. type Controller struct {
  48. config *Config
  49. runCtx context.Context
  50. stopRunning context.CancelFunc
  51. runWaitGroup *sync.WaitGroup
  52. connectedTunnels chan *Tunnel
  53. failedTunnels chan *Tunnel
  54. tunnelMutex sync.Mutex
  55. establishedOnce bool
  56. tunnelPoolSize int
  57. tunnels []*Tunnel
  58. nextTunnel int
  59. isEstablishing bool
  60. establishStartTime time.Time
  61. protocolSelectionConstraints *protocolSelectionConstraints
  62. concurrentEstablishTunnelsMutex sync.Mutex
  63. establishConnectTunnelCount int
  64. concurrentEstablishTunnels int
  65. concurrentIntensiveEstablishTunnels int
  66. peakConcurrentEstablishTunnels int
  67. peakConcurrentIntensiveEstablishTunnels int
  68. establishCtx context.Context
  69. stopEstablish context.CancelFunc
  70. establishWaitGroup *sync.WaitGroup
  71. establishedTunnelsCount int32
  72. candidateServerEntries chan *candidateServerEntry
  73. untunneledDialConfig *DialConfig
  74. untunneledSplitTunnelClassifications *lrucache.Cache
  75. splitTunnelClassificationTTL time.Duration
  76. splitTunnelClassificationMaxEntries int
  77. signalFetchCommonRemoteServerList chan struct{}
  78. signalFetchObfuscatedServerLists chan struct{}
  79. signalDownloadUpgrade chan string
  80. signalReportServerEntries chan *serverEntriesReportRequest
  81. signalReportConnected chan struct{}
  82. signalRestartEstablishing chan struct{}
  83. serverAffinityDoneBroadcast chan struct{}
  84. packetTunnelClient *tun.Client
  85. packetTunnelTransport *PacketTunnelTransport
  86. staggerMutex sync.Mutex
  87. resolver *resolver.Resolver
  88. steeringIPCache *lrucache.Cache
  89. tlsClientSessionCache tls.ClientSessionCache
  90. utlsClientSessionCache utls.ClientSessionCache
  91. }
  92. // NewController initializes a new controller.
  93. func NewController(config *Config) (controller *Controller, err error) {
  94. if !config.IsCommitted() {
  95. return nil, errors.TraceNew("uncommitted config")
  96. }
  97. // Needed by regen, at least
  98. rand.Seed(int64(time.Now().Nanosecond()))
  99. // The session ID for the Psiphon server API is used across all
  100. // tunnels established by the controller.
  101. NoticeSessionId(config.SessionID)
  102. // Attempt to apply any valid, local stored tactics. The pre-done context
  103. // ensures no tactics request is attempted now.
  104. doneContext, cancelFunc := context.WithCancel(context.Background())
  105. cancelFunc()
  106. GetTactics(doneContext, config)
  107. p := config.GetParameters().Get()
  108. splitTunnelClassificationTTL :=
  109. p.Duration(parameters.SplitTunnelClassificationTTL)
  110. splitTunnelClassificationMaxEntries :=
  111. p.Int(parameters.SplitTunnelClassificationMaxEntries)
  112. steeringIPCacheTTL := p.Duration(parameters.SteeringIPCacheTTL)
  113. steeringIPCacheMaxEntries := p.Int(parameters.SteeringIPCacheMaxEntries)
  114. controller = &Controller{
  115. config: config,
  116. runWaitGroup: new(sync.WaitGroup),
  117. // connectedTunnels and failedTunnels buffer sizes are large enough to
  118. // receive full pools of tunnels without blocking. Senders should not block.
  119. connectedTunnels: make(chan *Tunnel, MAX_TUNNEL_POOL_SIZE),
  120. failedTunnels: make(chan *Tunnel, MAX_TUNNEL_POOL_SIZE),
  121. tunnelPoolSize: TUNNEL_POOL_SIZE,
  122. tunnels: make([]*Tunnel, 0),
  123. establishedOnce: false,
  124. isEstablishing: false,
  125. untunneledSplitTunnelClassifications: lrucache.NewWithLRU(
  126. splitTunnelClassificationTTL,
  127. 1*time.Minute,
  128. splitTunnelClassificationMaxEntries),
  129. // TODO: Add a buffer of 1 so we don't miss a signal while receiver is
  130. // starting? Trade-off is potential back-to-back fetch remotes. As-is,
  131. // establish will eventually signal another fetch remote.
  132. signalFetchCommonRemoteServerList: make(chan struct{}),
  133. signalFetchObfuscatedServerLists: make(chan struct{}),
  134. signalDownloadUpgrade: make(chan string),
  135. signalReportConnected: make(chan struct{}),
  136. // Using a buffer of 1 to ensure there's no race between the first signal
  137. // sent and a channel receiver initializing; a side effect is that this
  138. // allows 1 additional scan to enqueue while a scan is in progress, possibly
  139. // resulting in one unnecessary scan.
  140. signalReportServerEntries: make(chan *serverEntriesReportRequest, 1),
  141. // signalRestartEstablishing has a buffer of 1 to ensure sending the
  142. // signal doesn't block and receiving won't miss a signal.
  143. signalRestartEstablishing: make(chan struct{}, 1),
  144. steeringIPCache: lrucache.NewWithLRU(
  145. steeringIPCacheTTL,
  146. 1*time.Minute,
  147. steeringIPCacheMaxEntries),
  148. tlsClientSessionCache: tls.NewLRUClientSessionCache(0),
  149. utlsClientSessionCache: utls.NewLRUClientSessionCache(0),
  150. }
  151. // Initialize untunneledDialConfig, used by untunneled dials including
  152. // remote server list and upgrade downloads.
  153. controller.untunneledDialConfig = &DialConfig{
  154. UpstreamProxyURL: controller.config.UpstreamProxyURL,
  155. CustomHeaders: controller.config.CustomHeaders,
  156. DeviceBinder: controller.config.deviceBinder,
  157. IPv6Synthesizer: controller.config.IPv6Synthesizer,
  158. ResolveIP: func(ctx context.Context, hostname string) ([]net.IP, error) {
  159. // Note: when domain fronting would be used for untunneled dials a
  160. // copy of untunneledDialConfig should be used instead, which
  161. // redefines ResolveIP such that the corresponding fronting
  162. // provider ID is passed into UntunneledResolveIP to enable the use
  163. // of pre-resolved IPs.
  164. IPs, err := UntunneledResolveIP(
  165. ctx, controller.config, controller.resolver, hostname, "")
  166. if err != nil {
  167. return nil, errors.Trace(err)
  168. }
  169. return IPs, nil
  170. },
  171. TrustedCACertificatesFilename: controller.config.TrustedCACertificatesFilename,
  172. }
  173. if config.PacketTunnelTunFileDescriptor > 0 {
  174. // Run a packet tunnel client. The lifetime of the tun.Client is the
  175. // lifetime of the Controller, so it exists across tunnel establishments
  176. // and reestablishments. The PacketTunnelTransport provides a layer
  177. // that presents a continuosuly existing transport to the tun.Client;
  178. // it's set to use new SSH channels after new SSH tunnel establishes.
  179. packetTunnelTransport := NewPacketTunnelTransport()
  180. packetTunnelClient, err := tun.NewClient(&tun.ClientConfig{
  181. Logger: NoticeCommonLogger(),
  182. TunFileDescriptor: config.PacketTunnelTunFileDescriptor,
  183. TransparentDNSIPv4Address: config.PacketTunnelTransparentDNSIPv4Address,
  184. TransparentDNSIPv6Address: config.PacketTunnelTransparentDNSIPv6Address,
  185. Transport: packetTunnelTransport,
  186. })
  187. if err != nil {
  188. return nil, errors.Trace(err)
  189. }
  190. controller.packetTunnelClient = packetTunnelClient
  191. controller.packetTunnelTransport = packetTunnelTransport
  192. }
  193. return controller, nil
  194. }
  195. // Run executes the controller. Run exits if a controller
  196. // component fails or the parent context is canceled.
  197. func (controller *Controller) Run(ctx context.Context) {
  198. if controller.config.LimitCPUThreads {
  199. runtime.GOMAXPROCS(1)
  200. }
  201. pprofRun()
  202. // Ensure fresh repetitive notice state for each run, so the
  203. // client will always get an AvailableEgressRegions notice,
  204. // an initial instance of any repetitive error notice, etc.
  205. ResetRepetitiveNotices()
  206. runCtx, stopRunning := context.WithCancel(ctx)
  207. defer stopRunning()
  208. controller.runCtx = runCtx
  209. controller.stopRunning = stopRunning
  210. // Start components
  211. // Initialize a single resolver to be used by all dials. Sharing a single
  212. // resolver ensures cached results are shared, and that network state
  213. // query overhead is amortized over all dials. Multiple dials can resolve
  214. // domain concurrently.
  215. //
  216. // config.SetResolver makes this resolver available to MakeDialParameters.
  217. controller.resolver = NewResolver(controller.config, true)
  218. defer controller.resolver.Stop()
  219. controller.config.SetResolver(controller.resolver)
  220. // Maintain a cache of steering IPs to be applied to dials. A steering IP
  221. // is an alternate dial IP; for example, steering IPs may be specified by
  222. // a CDN service and used to load balance CDN traffic.
  223. controller.steeringIPCache.Flush()
  224. // TODO: IPv6 support
  225. var listenIP string
  226. if controller.config.ListenInterface == "" {
  227. listenIP = "127.0.0.1"
  228. } else if controller.config.ListenInterface == "any" {
  229. listenIP = "0.0.0.0"
  230. } else {
  231. IPv4Address, _, err := common.GetInterfaceIPAddresses(controller.config.ListenInterface)
  232. if err == nil && IPv4Address == nil {
  233. err = fmt.Errorf("no IPv4 address for interface %s", controller.config.ListenInterface)
  234. }
  235. if err != nil {
  236. NoticeError("error getting listener IP: %v", errors.Trace(err))
  237. return
  238. }
  239. listenIP = IPv4Address.String()
  240. }
  241. if !controller.config.DisableLocalSocksProxy {
  242. socksProxy, err := NewSocksProxy(controller.config, controller, listenIP)
  243. if err != nil {
  244. NoticeError("error initializing local SOCKS proxy: %v", errors.Trace(err))
  245. return
  246. }
  247. defer socksProxy.Close()
  248. }
  249. if !controller.config.DisableLocalHTTPProxy {
  250. httpProxy, err := NewHttpProxy(controller.config, controller, listenIP)
  251. if err != nil {
  252. NoticeError("error initializing local HTTP proxy: %v", errors.Trace(err))
  253. return
  254. }
  255. defer httpProxy.Close()
  256. }
  257. if !controller.config.DisableRemoteServerListFetcher {
  258. if controller.config.RemoteServerListURLs != nil {
  259. controller.runWaitGroup.Add(1)
  260. go controller.remoteServerListFetcher(
  261. "common",
  262. FetchCommonRemoteServerList,
  263. controller.signalFetchCommonRemoteServerList)
  264. }
  265. if controller.config.ObfuscatedServerListRootURLs != nil {
  266. controller.runWaitGroup.Add(1)
  267. go controller.remoteServerListFetcher(
  268. "obfuscated",
  269. FetchObfuscatedServerLists,
  270. controller.signalFetchObfuscatedServerLists)
  271. }
  272. }
  273. if controller.config.EnableUpgradeDownload {
  274. controller.runWaitGroup.Add(1)
  275. go controller.upgradeDownloader()
  276. }
  277. controller.runWaitGroup.Add(1)
  278. go controller.serverEntriesReporter()
  279. controller.runWaitGroup.Add(1)
  280. go controller.connectedReporter()
  281. controller.runWaitGroup.Add(1)
  282. go controller.establishTunnelWatcher()
  283. controller.runWaitGroup.Add(1)
  284. go controller.runTunnels()
  285. if controller.packetTunnelClient != nil {
  286. controller.packetTunnelClient.Start()
  287. }
  288. // Wait while running
  289. <-controller.runCtx.Done()
  290. NoticeInfo("controller stopped")
  291. if controller.packetTunnelClient != nil {
  292. controller.packetTunnelClient.Stop()
  293. }
  294. // All workers -- runTunnels, establishment workers, and auxilliary
  295. // workers such as fetch remote server list and untunneled uprade
  296. // download -- operate with the controller run context and will all
  297. // be interrupted when the run context is done.
  298. controller.runWaitGroup.Wait()
  299. NoticeInfo("exiting controller")
  300. NoticeExiting()
  301. }
  302. // SignalComponentFailure notifies the controller that an associated component has failed.
  303. // This will terminate the controller.
  304. func (controller *Controller) SignalComponentFailure() {
  305. NoticeWarning("controller shutdown due to component failure")
  306. controller.stopRunning()
  307. }
  308. // SetDynamicConfig overrides the sponsor ID and authorizations fields of the
  309. // Controller config with the input values. The new values will be used in the
  310. // next tunnel connection.
  311. func (controller *Controller) SetDynamicConfig(sponsorID string, authorizations []string) {
  312. controller.config.SetDynamicConfig(sponsorID, authorizations)
  313. }
  314. // TerminateNextActiveTunnel terminates the active tunnel, which will initiate
  315. // establishment of a new tunnel.
  316. func (controller *Controller) TerminateNextActiveTunnel() {
  317. tunnel := controller.getNextActiveTunnel()
  318. if tunnel != nil {
  319. controller.SignalTunnelFailure(tunnel)
  320. NoticeInfo("terminated tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  321. }
  322. }
  323. // ExportExchangePayload creates a payload for client-to-client server
  324. // connection info exchange. See the comment for psiphon.ExportExchangePayload
  325. // for more details.
  326. func (controller *Controller) ExportExchangePayload() string {
  327. return ExportExchangePayload(controller.config)
  328. }
  329. // ImportExchangePayload imports a payload generated by ExportExchangePayload.
  330. // See the comment for psiphon.ImportExchangePayload for more details about
  331. // the import.
  332. //
  333. // When the import is successful, a signal is set to trigger a restart any
  334. // establishment in progress. This will cause the newly imported server entry
  335. // to be prioritized, which it otherwise would not be in later establishment
  336. // rounds. The establishment process continues after ImportExchangePayload
  337. // returns.
  338. //
  339. // If the client already has a connected tunnel, or a tunnel connection is
  340. // established concurrently with the import, the signal has no effect as the
  341. // overall goal is establish _any_ connection.
  342. func (controller *Controller) ImportExchangePayload(payload string) bool {
  343. // Race condition: if a new tunnel connection is established concurrently
  344. // with the import, either that tunnel's server entry of the imported server
  345. // entry may end up as the affinity server.
  346. ok := ImportExchangePayload(controller.config, payload)
  347. if !ok {
  348. return false
  349. }
  350. select {
  351. case controller.signalRestartEstablishing <- struct{}{}:
  352. default:
  353. }
  354. return true
  355. }
  356. // remoteServerListFetcher fetches an out-of-band list of server entries
  357. // for more tunnel candidates. It fetches when signalled, with retries
  358. // on failure.
  359. func (controller *Controller) remoteServerListFetcher(
  360. name string,
  361. fetcher RemoteServerListFetcher,
  362. signal <-chan struct{}) {
  363. defer controller.runWaitGroup.Done()
  364. var lastFetchTime time.Time
  365. fetcherLoop:
  366. for {
  367. // Wait for a signal before fetching
  368. select {
  369. case <-signal:
  370. case <-controller.runCtx.Done():
  371. break fetcherLoop
  372. }
  373. // Skip fetch entirely (i.e., send no request at all, even when ETag would save
  374. // on response size) when a recent fetch was successful
  375. stalePeriod := controller.config.GetParameters().Get().Duration(
  376. parameters.FetchRemoteServerListStalePeriod)
  377. if !lastFetchTime.IsZero() &&
  378. lastFetchTime.Add(stalePeriod).After(time.Now()) {
  379. continue
  380. }
  381. retryLoop:
  382. for attempt := 0; ; attempt++ {
  383. // Don't attempt to fetch while there is no network connectivity,
  384. // to avoid alert notice noise.
  385. if !WaitForNetworkConnectivity(
  386. controller.runCtx,
  387. controller.config.NetworkConnectivityChecker) {
  388. break fetcherLoop
  389. }
  390. // Pick any active tunnel and make the next fetch attempt. If there's
  391. // no active tunnel, the untunneledDialConfig will be used.
  392. tunnel := controller.getNextActiveTunnel()
  393. err := fetcher(
  394. controller.runCtx,
  395. controller.config,
  396. attempt,
  397. tunnel,
  398. controller.untunneledDialConfig)
  399. if err == nil {
  400. lastFetchTime = time.Now()
  401. break retryLoop
  402. }
  403. NoticeWarning("failed to fetch %s remote server list: %v",
  404. name, errors.Trace(err))
  405. retryPeriod := controller.config.GetParameters().Get().Duration(
  406. parameters.FetchRemoteServerListRetryPeriod)
  407. timer := time.NewTimer(retryPeriod)
  408. select {
  409. case <-timer.C:
  410. case <-controller.runCtx.Done():
  411. timer.Stop()
  412. break fetcherLoop
  413. }
  414. }
  415. }
  416. NoticeInfo("exiting %s remote server list fetcher", name)
  417. }
  418. // upgradeDownloader makes periodic attempts to complete a client upgrade
  419. // download. DownloadUpgrade() is resumable, so each attempt has potential for
  420. // getting closer to completion, even in conditions where the download or
  421. // tunnel is repeatedly interrupted.
  422. // An upgrade download is triggered by either a handshake response indicating
  423. // that a new version is available; or after failing to connect, in which case
  424. // it's useful to check, out-of-band, for an upgrade with new circumvention
  425. // capabilities.
  426. // Once the download operation completes successfully, the downloader exits
  427. // and is not run again: either there is not a newer version, or the upgrade
  428. // has been downloaded and is ready to be applied.
  429. // We're assuming that the upgrade will be applied and the entire system
  430. // restarted before another upgrade is to be downloaded.
  431. //
  432. // TODO: refactor upgrade downloader and remote server list fetcher to use
  433. // common code (including the resumable download routines).
  434. func (controller *Controller) upgradeDownloader() {
  435. defer controller.runWaitGroup.Done()
  436. var lastDownloadTime time.Time
  437. downloadLoop:
  438. for {
  439. // Wait for a signal before downloading
  440. var handshakeVersion string
  441. select {
  442. case handshakeVersion = <-controller.signalDownloadUpgrade:
  443. case <-controller.runCtx.Done():
  444. break downloadLoop
  445. }
  446. stalePeriod := controller.config.GetParameters().Get().Duration(
  447. parameters.FetchUpgradeStalePeriod)
  448. // Unless handshake is explicitly advertizing a new version, skip
  449. // checking entirely when a recent download was successful.
  450. if handshakeVersion == "" &&
  451. !lastDownloadTime.IsZero() &&
  452. lastDownloadTime.Add(stalePeriod).After(time.Now()) {
  453. continue
  454. }
  455. retryLoop:
  456. for attempt := 0; ; attempt++ {
  457. // Don't attempt to download while there is no network connectivity,
  458. // to avoid alert notice noise.
  459. if !WaitForNetworkConnectivity(
  460. controller.runCtx,
  461. controller.config.NetworkConnectivityChecker) {
  462. break downloadLoop
  463. }
  464. // Pick any active tunnel and make the next download attempt. If there's
  465. // no active tunnel, the untunneledDialConfig will be used.
  466. tunnel := controller.getNextActiveTunnel()
  467. err := DownloadUpgrade(
  468. controller.runCtx,
  469. controller.config,
  470. attempt,
  471. handshakeVersion,
  472. tunnel,
  473. controller.untunneledDialConfig)
  474. if err == nil {
  475. lastDownloadTime = time.Now()
  476. break retryLoop
  477. }
  478. NoticeWarning("failed to download upgrade: %v", errors.Trace(err))
  479. timeout := controller.config.GetParameters().Get().Duration(
  480. parameters.FetchUpgradeRetryPeriod)
  481. timer := time.NewTimer(timeout)
  482. select {
  483. case <-timer.C:
  484. case <-controller.runCtx.Done():
  485. timer.Stop()
  486. break downloadLoop
  487. }
  488. }
  489. }
  490. NoticeInfo("exiting upgrade downloader")
  491. }
  492. type serverEntriesReportRequest struct {
  493. constraints *protocolSelectionConstraints
  494. awaitResponse chan *serverEntriesReportResponse
  495. }
  496. type serverEntriesReportResponse struct {
  497. err error
  498. candidates int
  499. initialCandidates int
  500. initialCandidatesAnyEgressRegion int
  501. availableEgressRegions []string
  502. }
  503. // serverEntriesReporter performs scans over all server entries to report on
  504. // available tunnel candidates, subject to protocol selection constraints, and
  505. // available egress regions.
  506. //
  507. // Because scans may be slow, depending on the client device and server entry
  508. // list size, serverEntriesReporter is used to perform asychronous, background
  509. // operations that would otherwise block establishment. This includes emitting
  510. // diagnotic notices that are informational (CandidateServers) or which do not
  511. // need to emit before establishment starts (AvailableEgressRegions).
  512. //
  513. // serverEntriesReporter also serves to combine these scans, which would
  514. // otherwise be logically independent, due to the performance impact of scans.
  515. //
  516. // The underlying datastore implementation _may_ block write transactions
  517. // while there are open read transactions. For example, bolt write
  518. // transactions which need to re-map the data file (when the datastore grows)
  519. // will block on open read transactions. In these scenarios, a slow scan will
  520. // still block other operations.
  521. //
  522. // serverEntriesReporter runs beyond the establishment phase, since it's
  523. // important for notices such as AvailableEgressRegions to eventually emit
  524. // even if already established. serverEntriesReporter scans are cancellable,
  525. // so controller shutdown is not blocked by slow scans.
  526. //
  527. // In some special cases, establishment cannot begin without candidate counts
  528. // up front. In these cases only, the request contains a non-nil
  529. // awaitResponse, a channel which is used by the requester to block until the
  530. // scan is complete and the candidate counts are available.
  531. func (controller *Controller) serverEntriesReporter() {
  532. defer controller.runWaitGroup.Done()
  533. loop:
  534. for {
  535. var request *serverEntriesReportRequest
  536. select {
  537. case request = <-controller.signalReportServerEntries:
  538. case <-controller.runCtx.Done():
  539. break loop
  540. }
  541. egressRegion := controller.config.EgressRegion
  542. constraints := request.constraints
  543. var response serverEntriesReportResponse
  544. regions := make(map[string]bool)
  545. callback := func(serverEntry *protocol.ServerEntry) bool {
  546. // In establishment, excludeIntensive depends on what set of protocols are
  547. // already being dialed. For these reports, don't exclude intensive
  548. // protocols as any intensive candidate can always be an available
  549. // candidate at some point.
  550. excludeIntensive := false
  551. isInitialCandidate := constraints.isInitialCandidate(excludeIntensive, serverEntry)
  552. isCandidate := constraints.isCandidate(excludeIntensive, serverEntry)
  553. if isInitialCandidate {
  554. response.initialCandidatesAnyEgressRegion += 1
  555. }
  556. if egressRegion == "" || serverEntry.Region == egressRegion {
  557. if isInitialCandidate {
  558. response.initialCandidates += 1
  559. }
  560. if isCandidate {
  561. response.candidates += 1
  562. }
  563. }
  564. isAvailable := isCandidate
  565. if constraints.hasInitialProtocols() {
  566. // Available egress regions is subject to an initial limit constraint, if
  567. // present: see AvailableEgressRegions comment in launchEstablishing.
  568. isAvailable = isInitialCandidate
  569. }
  570. if isAvailable {
  571. // Ignore server entries with no region field.
  572. if serverEntry.Region != "" {
  573. regions[serverEntry.Region] = true
  574. }
  575. }
  576. select {
  577. case <-controller.runCtx.Done():
  578. // Don't block controller shutdown: cancel the scan.
  579. return false
  580. default:
  581. return true
  582. }
  583. }
  584. startTime := time.Now()
  585. response.err = ScanServerEntries(callback)
  586. // Report this duration in CandidateServers as an indication of datastore
  587. // performance.
  588. duration := time.Since(startTime)
  589. response.availableEgressRegions = make([]string, 0, len(regions))
  590. for region := range regions {
  591. response.availableEgressRegions = append(response.availableEgressRegions, region)
  592. }
  593. if response.err != nil {
  594. // For diagnostics, we'll post this even when cancelled due to shutdown.
  595. NoticeWarning("ScanServerEntries failed: %v", errors.Trace(response.err))
  596. // Continue and send error reponse. Clear any partial data to avoid
  597. // misuse.
  598. response.candidates = 0
  599. response.initialCandidates = 0
  600. response.initialCandidatesAnyEgressRegion = 0
  601. response.availableEgressRegions = []string{}
  602. }
  603. if request.awaitResponse != nil {
  604. select {
  605. case request.awaitResponse <- &response:
  606. case <-controller.runCtx.Done():
  607. // The receiver may be gone when shutting down.
  608. }
  609. }
  610. if response.err == nil {
  611. NoticeCandidateServers(
  612. controller.config.EgressRegion,
  613. controller.protocolSelectionConstraints,
  614. response.initialCandidates,
  615. response.candidates,
  616. duration)
  617. NoticeAvailableEgressRegions(
  618. response.availableEgressRegions)
  619. }
  620. }
  621. NoticeInfo("exiting server entries reporter")
  622. }
  623. // signalServerEntriesReporter triggers a new server entry report. Set
  624. // request.awaitResponse to obtain the report output. When awaitResponse is
  625. // set, signalServerEntriesReporter blocks until the reporter receives the
  626. // request, guaranteeing the new report runs. Otherwise, the report is
  627. // considered to be informational and may or may not run, depending on whether
  628. // another run is already in progress.
  629. func (controller *Controller) signalServerEntriesReporter(request *serverEntriesReportRequest) {
  630. if request.awaitResponse == nil {
  631. select {
  632. case controller.signalReportServerEntries <- request:
  633. default:
  634. }
  635. } else {
  636. controller.signalReportServerEntries <- request
  637. }
  638. }
  639. // connectedReporter sends periodic "connected" requests to the Psiphon API.
  640. // These requests are for server-side unique user stats calculation. See the
  641. // comment in DoConnectedRequest for a description of the request mechanism.
  642. //
  643. // To correctly count daily unique users, only one connected request is made
  644. // across all simultaneous multi-tunnels; and the connected request is
  645. // repeated every 24h.
  646. //
  647. // The signalReportConnected mechanism is used to trigger a connected request
  648. // immediately after a reconnect. While strictly only one connected request
  649. // per 24h is required in order to count daily unique users, the connected
  650. // request also delivers the establishment duration metric (which includes
  651. // time elapsed performing the handshake request) and additional fragmentation
  652. // metrics; these metrics are measured for each tunnel.
  653. func (controller *Controller) connectedReporter() {
  654. defer controller.runWaitGroup.Done()
  655. // session is nil when DisableApi is set
  656. if controller.config.DisableApi {
  657. return
  658. }
  659. select {
  660. case <-controller.signalReportConnected:
  661. // Make the initial connected request
  662. case <-controller.runCtx.Done():
  663. return
  664. }
  665. loop:
  666. for {
  667. // Pick any active tunnel and make the next connected request. No error is
  668. // logged if there's no active tunnel, as that's not an unexpected
  669. // condition.
  670. reported := false
  671. tunnel := controller.getNextActiveTunnel()
  672. if tunnel != nil {
  673. err := tunnel.serverContext.DoConnectedRequest()
  674. if err == nil {
  675. reported = true
  676. } else {
  677. NoticeWarning("failed to make connected request: %v",
  678. errors.Trace(err))
  679. }
  680. }
  681. // Schedule the next connected request and wait. This duration is not a
  682. // dynamic ClientParameter as the daily unique user stats logic specifically
  683. // requires a "connected" request no more or less often than every 24h.
  684. var duration time.Duration
  685. if reported {
  686. duration = 24 * time.Hour
  687. } else {
  688. duration = controller.config.GetParameters().Get().Duration(
  689. parameters.PsiphonAPIConnectedRequestRetryPeriod)
  690. }
  691. timer := time.NewTimer(duration)
  692. doBreak := false
  693. select {
  694. case <-controller.signalReportConnected:
  695. case <-timer.C:
  696. // Make another connected request
  697. case <-controller.runCtx.Done():
  698. doBreak = true
  699. }
  700. timer.Stop()
  701. if doBreak {
  702. break loop
  703. }
  704. }
  705. NoticeInfo("exiting connected reporter")
  706. }
  707. func (controller *Controller) signalConnectedReporter() {
  708. // session is nil when DisableApi is set
  709. if controller.config.DisableApi {
  710. return
  711. }
  712. select {
  713. case controller.signalReportConnected <- struct{}{}:
  714. default:
  715. }
  716. }
  717. // establishTunnelWatcher terminates the controller if a tunnel
  718. // has not been established in the configured time period. This
  719. // is regardless of how many tunnels are presently active -- meaning
  720. // that if an active tunnel was established and lost the controller
  721. // is left running (to re-establish).
  722. func (controller *Controller) establishTunnelWatcher() {
  723. defer controller.runWaitGroup.Done()
  724. timeout := controller.config.GetParameters().Get().Duration(
  725. parameters.EstablishTunnelTimeout)
  726. if timeout > 0 {
  727. timer := time.NewTimer(timeout)
  728. defer timer.Stop()
  729. select {
  730. case <-timer.C:
  731. if !controller.hasEstablishedOnce() {
  732. NoticeEstablishTunnelTimeout(timeout)
  733. controller.SignalComponentFailure()
  734. }
  735. case <-controller.runCtx.Done():
  736. }
  737. }
  738. NoticeInfo("exiting establish tunnel watcher")
  739. }
  740. // runTunnels is the controller tunnel management main loop. It starts and stops
  741. // establishing tunnels based on the target tunnel pool size and the current size
  742. // of the pool. Tunnels are established asynchronously using worker goroutines.
  743. //
  744. // When there are no server entries for the target region/protocol, the
  745. // establishCandidateGenerator will yield no candidates and wait before
  746. // trying again. In the meantime, a remote server entry fetch may supply
  747. // valid candidates.
  748. //
  749. // When a tunnel is established, it's added to the active pool. The tunnel's
  750. // operateTunnel goroutine monitors the tunnel.
  751. //
  752. // When a tunnel fails, it's removed from the pool and the establish process is
  753. // restarted to fill the pool.
  754. func (controller *Controller) runTunnels() {
  755. defer controller.runWaitGroup.Done()
  756. // Start running
  757. controller.startEstablishing()
  758. loop:
  759. for {
  760. select {
  761. case <-controller.signalRestartEstablishing:
  762. // signalRestartEstablishing restarts any establishment in progress. One
  763. // use case for this is to prioritize a newly imported, exchanged server
  764. // entry, which will be in the affinity position.
  765. //
  766. // It's possible for another connection to establish concurrent to signalling;
  767. // since the overall goal remains to establish _any_ connection, we accept that
  768. // in some cases the exchanged server entry may not get used.
  769. if controller.isEstablishing {
  770. controller.stopEstablishing()
  771. controller.startEstablishing()
  772. }
  773. case failedTunnel := <-controller.failedTunnels:
  774. NoticeWarning("tunnel failed: %s", failedTunnel.dialParams.ServerEntry.GetDiagnosticID())
  775. controller.terminateTunnel(failedTunnel)
  776. // Clear the reference to this tunnel before calling startEstablishing,
  777. // which will invoke a garbage collection.
  778. failedTunnel = nil
  779. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing,
  780. // which reference controller.isEstablishing.
  781. controller.startEstablishing()
  782. case connectedTunnel := <-controller.connectedTunnels:
  783. // Tunnel establishment has two phases: connection and activation.
  784. //
  785. // Connection is run concurrently by the establishTunnelWorkers, to minimize
  786. // delay when it's not yet known which server and protocol will be available
  787. // and unblocked.
  788. //
  789. // Activation is run serially, here, to minimize the overhead of making a
  790. // handshake request and starting the operateTunnel management worker for a
  791. // tunnel which may be discarded.
  792. //
  793. // When the active tunnel will complete establishment, establishment is
  794. // stopped before activation. This interrupts all connecting tunnels and
  795. // garbage collects their memory. The purpose is to minimize memory
  796. // pressure when the handshake request is made. In the unlikely case that the
  797. // handshake fails, establishment is restarted.
  798. //
  799. // Any delays in stopEstablishing will delay the handshake for the last
  800. // active tunnel.
  801. //
  802. // In the typical case of tunnelPoolSize of 1, only a single handshake is
  803. // performed and the homepages notices file, when used, will not be modifed
  804. // after the NoticeTunnels(1) [i.e., connected] until NoticeTunnels(0) [i.e.,
  805. // disconnected]. For tunnelPoolSize > 1, serial handshakes only ensures that
  806. // each set of emitted NoticeHomepages is contiguous.
  807. active, outstanding := controller.numTunnels()
  808. // discardTunnel will be true here when already fully established.
  809. discardTunnel := (outstanding <= 0)
  810. isFirstTunnel := (active == 0)
  811. isLastTunnel := (outstanding == 1)
  812. if !discardTunnel {
  813. if isLastTunnel {
  814. controller.stopEstablishing()
  815. }
  816. err := connectedTunnel.Activate(controller.runCtx, controller)
  817. if err != nil {
  818. NoticeWarning("failed to activate %s: %v",
  819. connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(),
  820. errors.Trace(err))
  821. discardTunnel = true
  822. } else {
  823. // It's unlikely that registerTunnel will fail, since only this goroutine
  824. // calls registerTunnel -- and after checking numTunnels; so failure is not
  825. // expected.
  826. if !controller.registerTunnel(connectedTunnel) {
  827. NoticeWarning("failed to register %s: %v",
  828. connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(),
  829. errors.Trace(err))
  830. discardTunnel = true
  831. }
  832. }
  833. // May need to replace this tunnel
  834. if isLastTunnel && discardTunnel {
  835. controller.startEstablishing()
  836. }
  837. }
  838. if discardTunnel {
  839. controller.discardTunnel(connectedTunnel)
  840. // Clear the reference to this discarded tunnel and immediately run
  841. // a garbage collection to reclaim its memory.
  842. connectedTunnel = nil
  843. DoGarbageCollection()
  844. // Skip the rest of this case
  845. break
  846. }
  847. atomic.AddInt32(&controller.establishedTunnelsCount, 1)
  848. NoticeActiveTunnel(
  849. connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(),
  850. connectedTunnel.dialParams.TunnelProtocol,
  851. connectedTunnel.dialParams.ServerEntry.SupportsSSHAPIRequests())
  852. if isFirstTunnel {
  853. // Signal a connected request on each 1st tunnel establishment. For
  854. // multi-tunnels, the session is connected as long as at least one
  855. // tunnel is established.
  856. controller.signalConnectedReporter()
  857. // If the handshake indicated that a new client version is available,
  858. // trigger an upgrade download.
  859. // Note: serverContext is nil when DisableApi is set
  860. if connectedTunnel.serverContext != nil &&
  861. connectedTunnel.serverContext.clientUpgradeVersion != "" {
  862. handshakeVersion := connectedTunnel.serverContext.clientUpgradeVersion
  863. select {
  864. case controller.signalDownloadUpgrade <- handshakeVersion:
  865. default:
  866. }
  867. }
  868. }
  869. // Set the new tunnel as the transport for the packet tunnel. The packet tunnel
  870. // client remains up when reestablishing, but no packets are relayed while there
  871. // is no connected tunnel. UseTunnel will establish a new packet tunnel SSH
  872. // channel over the new SSH tunnel and configure the packet tunnel client to use
  873. // the new SSH channel as its transport.
  874. //
  875. // Note: as is, this logic is suboptimal for tunnelPoolSize > 1, as this would
  876. // continuously initialize new packet tunnel sessions for each established
  877. // server. For now, config validation requires tunnelPoolSize == 1 when
  878. // the packet tunnel is used.
  879. if controller.packetTunnelTransport != nil {
  880. controller.packetTunnelTransport.UseTunnel(connectedTunnel)
  881. }
  882. if controller.isFullyEstablished() {
  883. controller.stopEstablishing()
  884. }
  885. case <-controller.runCtx.Done():
  886. break loop
  887. }
  888. }
  889. // Stop running
  890. controller.stopEstablishing()
  891. controller.terminateAllTunnels()
  892. // Drain tunnel channels
  893. close(controller.connectedTunnels)
  894. for tunnel := range controller.connectedTunnels {
  895. controller.discardTunnel(tunnel)
  896. }
  897. close(controller.failedTunnels)
  898. for tunnel := range controller.failedTunnels {
  899. controller.discardTunnel(tunnel)
  900. }
  901. NoticeInfo("exiting run tunnels")
  902. }
  903. // SignalSeededNewSLOK implements the TunnelOwner interface. This function
  904. // is called by Tunnel.operateTunnel when the tunnel has received a new,
  905. // previously unknown SLOK from the server. The Controller triggers an OSL
  906. // fetch, as the new SLOK may be sufficient to access new OSLs.
  907. func (controller *Controller) SignalSeededNewSLOK() {
  908. select {
  909. case controller.signalFetchObfuscatedServerLists <- struct{}{}:
  910. default:
  911. }
  912. }
  913. // SignalTunnelFailure implements the TunnelOwner interface. This function
  914. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  915. // has failed. The Controller will signal runTunnels to create a new
  916. // tunnel and/or remove the tunnel from the list of active tunnels.
  917. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  918. // Don't block. Assumes the receiver has a buffer large enough for
  919. // the typical number of operated tunnels. In case there's no room,
  920. // terminate the tunnel (runTunnels won't get a signal in this case,
  921. // but the tunnel will be removed from the list of active tunnels).
  922. select {
  923. case controller.failedTunnels <- tunnel:
  924. default:
  925. controller.terminateTunnel(tunnel)
  926. }
  927. }
  928. // discardTunnel disposes of a successful connection that is no longer required.
  929. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  930. NoticeInfo("discard tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  931. // TODO: not calling PromoteServerEntry, since that would rank the
  932. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  933. // be promoted (since it connects), but with lower rank than all active
  934. // tunnels?
  935. tunnel.Close(true)
  936. }
  937. // registerTunnel adds the connected tunnel to the pool of active tunnels
  938. // which are candidates for port forwarding. Returns true if the pool has an
  939. // empty slot and false if the pool is full (caller should discard the tunnel).
  940. func (controller *Controller) registerTunnel(tunnel *Tunnel) bool {
  941. controller.tunnelMutex.Lock()
  942. defer controller.tunnelMutex.Unlock()
  943. if len(controller.tunnels) >= controller.tunnelPoolSize {
  944. return false
  945. }
  946. // Perform a final check just in case we've established
  947. // a duplicate connection.
  948. for _, activeTunnel := range controller.tunnels {
  949. if activeTunnel.dialParams.ServerEntry.IpAddress ==
  950. tunnel.dialParams.ServerEntry.IpAddress {
  951. NoticeWarning("duplicate tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  952. return false
  953. }
  954. }
  955. controller.establishedOnce = true
  956. controller.tunnels = append(controller.tunnels, tunnel)
  957. NoticeTunnels(len(controller.tunnels))
  958. // Promote this successful tunnel to first rank so it's one
  959. // of the first candidates next time establish runs.
  960. // Connecting to a TargetServerEntry does not change the
  961. // ranking.
  962. if controller.config.TargetServerEntry == "" {
  963. PromoteServerEntry(controller.config, tunnel.dialParams.ServerEntry.IpAddress)
  964. }
  965. return true
  966. }
  967. // hasEstablishedOnce indicates if at least one active tunnel has
  968. // been established up to this point. This is regardeless of how many
  969. // tunnels are presently active.
  970. func (controller *Controller) hasEstablishedOnce() bool {
  971. controller.tunnelMutex.Lock()
  972. defer controller.tunnelMutex.Unlock()
  973. return controller.establishedOnce
  974. }
  975. // isFullyEstablished indicates if the pool of active tunnels is full.
  976. func (controller *Controller) isFullyEstablished() bool {
  977. controller.tunnelMutex.Lock()
  978. defer controller.tunnelMutex.Unlock()
  979. return len(controller.tunnels) >= controller.tunnelPoolSize
  980. }
  981. // numTunnels returns the number of active and outstanding tunnels.
  982. // Oustanding is the number of tunnels required to fill the pool of
  983. // active tunnels.
  984. func (controller *Controller) numTunnels() (int, int) {
  985. controller.tunnelMutex.Lock()
  986. defer controller.tunnelMutex.Unlock()
  987. active := len(controller.tunnels)
  988. outstanding := controller.tunnelPoolSize - len(controller.tunnels)
  989. return active, outstanding
  990. }
  991. // terminateTunnel removes a tunnel from the pool of active tunnels
  992. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  993. // is adjusted as required.
  994. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  995. controller.tunnelMutex.Lock()
  996. defer controller.tunnelMutex.Unlock()
  997. for index, activeTunnel := range controller.tunnels {
  998. if tunnel == activeTunnel {
  999. controller.tunnels = append(
  1000. controller.tunnels[:index], controller.tunnels[index+1:]...)
  1001. if controller.nextTunnel > index {
  1002. controller.nextTunnel--
  1003. }
  1004. if controller.nextTunnel >= len(controller.tunnels) {
  1005. controller.nextTunnel = 0
  1006. }
  1007. activeTunnel.Close(false)
  1008. NoticeTunnels(len(controller.tunnels))
  1009. break
  1010. }
  1011. }
  1012. }
  1013. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  1014. // This is used when shutting down the controller.
  1015. func (controller *Controller) terminateAllTunnels() {
  1016. controller.tunnelMutex.Lock()
  1017. defer controller.tunnelMutex.Unlock()
  1018. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  1019. // may take a few seconds to send a final status request. We only want
  1020. // to wait as long as the single slowest tunnel.
  1021. closeWaitGroup := new(sync.WaitGroup)
  1022. closeWaitGroup.Add(len(controller.tunnels))
  1023. for _, activeTunnel := range controller.tunnels {
  1024. tunnel := activeTunnel
  1025. go func() {
  1026. defer closeWaitGroup.Done()
  1027. tunnel.Close(false)
  1028. }()
  1029. }
  1030. closeWaitGroup.Wait()
  1031. controller.tunnels = make([]*Tunnel, 0)
  1032. controller.nextTunnel = 0
  1033. NoticeTunnels(len(controller.tunnels))
  1034. }
  1035. // getNextActiveTunnel returns the next tunnel from the pool of active
  1036. // tunnels. Currently, tunnel selection order is simple round-robin.
  1037. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  1038. controller.tunnelMutex.Lock()
  1039. defer controller.tunnelMutex.Unlock()
  1040. if len(controller.tunnels) == 0 {
  1041. return nil
  1042. }
  1043. tunnel = controller.tunnels[controller.nextTunnel]
  1044. controller.nextTunnel =
  1045. (controller.nextTunnel + 1) % len(controller.tunnels)
  1046. return tunnel
  1047. }
  1048. // isActiveTunnelServerEntry is used to check if there's already
  1049. // an existing tunnel to a candidate server.
  1050. func (controller *Controller) isActiveTunnelServerEntry(
  1051. serverEntry *protocol.ServerEntry) bool {
  1052. controller.tunnelMutex.Lock()
  1053. defer controller.tunnelMutex.Unlock()
  1054. for _, activeTunnel := range controller.tunnels {
  1055. if activeTunnel.dialParams.ServerEntry.IpAddress == serverEntry.IpAddress {
  1056. return true
  1057. }
  1058. }
  1059. return false
  1060. }
  1061. func (controller *Controller) setTunnelPoolSize(tunnelPoolSize int) {
  1062. controller.tunnelMutex.Lock()
  1063. defer controller.tunnelMutex.Unlock()
  1064. if tunnelPoolSize < 1 {
  1065. tunnelPoolSize = 1
  1066. }
  1067. if tunnelPoolSize > MAX_TUNNEL_POOL_SIZE {
  1068. tunnelPoolSize = MAX_TUNNEL_POOL_SIZE
  1069. }
  1070. controller.tunnelPoolSize = tunnelPoolSize
  1071. }
  1072. func (controller *Controller) getTunnelPoolSize() int {
  1073. controller.tunnelMutex.Lock()
  1074. defer controller.tunnelMutex.Unlock()
  1075. return controller.tunnelPoolSize
  1076. }
  1077. // Dial selects an active tunnel and establishes a port forward
  1078. // connection through the selected tunnel. Failure to connect is considered
  1079. // a port forward failure, for the purpose of monitoring tunnel health.
  1080. //
  1081. // When split tunnel mode is enabled, the connection may be untunneled,
  1082. // depending on GeoIP classification of the destination.
  1083. //
  1084. // downstreamConn is an optional parameter which specifies a connection to be
  1085. // explicitly closed when the dialed connection is closed. For instance, this
  1086. // is used to close downstreamConn App<->LocalProxy connections when the
  1087. // related LocalProxy<->SshPortForward connections close.
  1088. func (controller *Controller) Dial(
  1089. remoteAddr string, downstreamConn net.Conn) (conn net.Conn, err error) {
  1090. tunnel := controller.getNextActiveTunnel()
  1091. if tunnel == nil {
  1092. return nil, errors.TraceNew("no active tunnels")
  1093. }
  1094. if !tunnel.config.IsSplitTunnelEnabled() {
  1095. tunneledConn, splitTunnel, err := tunnel.DialTCPChannel(
  1096. remoteAddr, false, downstreamConn)
  1097. if err != nil {
  1098. return nil, errors.Trace(err)
  1099. }
  1100. if splitTunnel {
  1101. return nil, errors.TraceNew(
  1102. "unexpected split tunnel classification")
  1103. }
  1104. return tunneledConn, nil
  1105. }
  1106. // In split tunnel mode, TCP port forwards to destinations in the same
  1107. // country as the client are untunneled.
  1108. //
  1109. // Split tunnel is implemented with assistence from the server to classify
  1110. // destinations as being in the same country as the client. The server knows
  1111. // the client's public IP GeoIP data, and, for clients with split tunnel mode
  1112. // enabled, the server resolves the port forward destination address and
  1113. // checks the destination IP GeoIP data.
  1114. //
  1115. // When the countries match, the server "rejects" the port forward with a
  1116. // distinct response that indicates to the client that an untunneled port
  1117. // foward should be established locally.
  1118. //
  1119. // The client maintains a classification cache that allows it to make
  1120. // untunneled port forwards without requiring a round trip to the server.
  1121. // Only destinations classified as untunneled are stored in the cache: a
  1122. // destination classified as tunneled requires the same round trip as an
  1123. // unknown destination.
  1124. //
  1125. // When the countries do not match, the server establishes a port forward, as
  1126. // it does for all port forwards in non-split tunnel mode. There is no
  1127. // additional round trip for tunneled port forwards.
  1128. splitTunnelHost, _, err := net.SplitHostPort(remoteAddr)
  1129. if err != nil {
  1130. return nil, errors.Trace(err)
  1131. }
  1132. untunneledCache := controller.untunneledSplitTunnelClassifications
  1133. // If the destination hostname is in the untunneled split tunnel
  1134. // classifications cache, skip the round trip to the server and do the
  1135. // direct, untunneled dial immediately.
  1136. _, cachedUntunneled := untunneledCache.Get(splitTunnelHost)
  1137. if !cachedUntunneled {
  1138. tunneledConn, splitTunnel, err := tunnel.DialTCPChannel(
  1139. remoteAddr, false, downstreamConn)
  1140. if err != nil {
  1141. return nil, errors.Trace(err)
  1142. }
  1143. if !splitTunnel {
  1144. // Clear any cached untunneled classification entry for this destination
  1145. // hostname, as the server is now classifying it as tunneled.
  1146. untunneledCache.Delete(splitTunnelHost)
  1147. return tunneledConn, nil
  1148. }
  1149. // The server has indicated that the client should make a direct,
  1150. // untunneled dial. Cache the classification to avoid this round trip in
  1151. // the immediate future.
  1152. untunneledCache.Add(splitTunnelHost, true, lrucache.DefaultExpiration)
  1153. }
  1154. NoticeUntunneled(splitTunnelHost)
  1155. untunneledConn, err := controller.DirectDial(remoteAddr)
  1156. if err != nil {
  1157. return nil, errors.Trace(err)
  1158. }
  1159. return untunneledConn, nil
  1160. }
  1161. // DirectDial dials an untunneled TCP connection within the controller run context.
  1162. func (controller *Controller) DirectDial(remoteAddr string) (conn net.Conn, err error) {
  1163. return DialTCP(controller.runCtx, remoteAddr, controller.untunneledDialConfig)
  1164. }
  1165. // triggerFetches signals RSL, OSL, and upgrade download fetchers to begin, if
  1166. // not already running. triggerFetches is called when tunnel establishment
  1167. // fails to complete within a deadline and in other cases where local
  1168. // circumvention capabilities are lacking and we may require new server
  1169. // entries or client versions with new capabilities.
  1170. func (controller *Controller) triggerFetches() {
  1171. // Trigger a common remote server list fetch, since we may have failed
  1172. // to connect with all known servers. Don't block sending signal, since
  1173. // this signal may have already been sent.
  1174. // Don't wait for fetch remote to succeed, since it may fail and
  1175. // enter a retry loop and we're better off trying more known servers.
  1176. // TODO: synchronize the fetch response, so it can be incorporated
  1177. // into the server entry iterator as soon as available.
  1178. select {
  1179. case controller.signalFetchCommonRemoteServerList <- struct{}{}:
  1180. default:
  1181. }
  1182. // Trigger an OSL fetch in parallel. Both fetches are run in parallel
  1183. // so that if one out of the common RLS and OSL set is large, it doesn't
  1184. // doesn't entirely block fetching the other.
  1185. select {
  1186. case controller.signalFetchObfuscatedServerLists <- struct{}{}:
  1187. default:
  1188. }
  1189. // Trigger an out-of-band upgrade availability check and download.
  1190. // Since we may have failed to connect, we may benefit from upgrading
  1191. // to a new client version with new circumvention capabilities.
  1192. select {
  1193. case controller.signalDownloadUpgrade <- "":
  1194. default:
  1195. }
  1196. }
  1197. type protocolSelectionConstraints struct {
  1198. useUpstreamProxy bool
  1199. initialLimitTunnelProtocols protocol.TunnelProtocols
  1200. initialLimitTunnelProtocolsCandidateCount int
  1201. limitTunnelProtocols protocol.TunnelProtocols
  1202. limitTunnelDialPortNumbers protocol.TunnelProtocolPortLists
  1203. limitQUICVersions protocol.QUICVersions
  1204. replayCandidateCount int
  1205. }
  1206. func (p *protocolSelectionConstraints) hasInitialProtocols() bool {
  1207. return len(p.initialLimitTunnelProtocols) > 0 && p.initialLimitTunnelProtocolsCandidateCount > 0
  1208. }
  1209. func (p *protocolSelectionConstraints) isInitialCandidate(
  1210. excludeIntensive bool,
  1211. serverEntry *protocol.ServerEntry) bool {
  1212. return p.hasInitialProtocols() &&
  1213. len(serverEntry.GetSupportedProtocols(
  1214. conditionallyEnabledComponents{},
  1215. p.useUpstreamProxy,
  1216. p.initialLimitTunnelProtocols,
  1217. p.limitTunnelDialPortNumbers,
  1218. p.limitQUICVersions,
  1219. excludeIntensive)) > 0
  1220. }
  1221. func (p *protocolSelectionConstraints) isCandidate(
  1222. excludeIntensive bool,
  1223. serverEntry *protocol.ServerEntry) bool {
  1224. return len(serverEntry.GetSupportedProtocols(
  1225. conditionallyEnabledComponents{},
  1226. p.useUpstreamProxy,
  1227. p.limitTunnelProtocols,
  1228. p.limitTunnelDialPortNumbers,
  1229. p.limitQUICVersions,
  1230. excludeIntensive)) > 0
  1231. }
  1232. func (p *protocolSelectionConstraints) canReplay(
  1233. connectTunnelCount int,
  1234. excludeIntensive bool,
  1235. serverEntry *protocol.ServerEntry,
  1236. replayProtocol string) bool {
  1237. if p.replayCandidateCount != -1 && connectTunnelCount > p.replayCandidateCount {
  1238. return false
  1239. }
  1240. return common.Contains(
  1241. p.supportedProtocols(connectTunnelCount, excludeIntensive, serverEntry),
  1242. replayProtocol)
  1243. }
  1244. func (p *protocolSelectionConstraints) supportedProtocols(
  1245. connectTunnelCount int,
  1246. excludeIntensive bool,
  1247. serverEntry *protocol.ServerEntry) []string {
  1248. limitTunnelProtocols := p.limitTunnelProtocols
  1249. if len(p.initialLimitTunnelProtocols) > 0 &&
  1250. p.initialLimitTunnelProtocolsCandidateCount > connectTunnelCount {
  1251. limitTunnelProtocols = p.initialLimitTunnelProtocols
  1252. }
  1253. return serverEntry.GetSupportedProtocols(
  1254. conditionallyEnabledComponents{},
  1255. p.useUpstreamProxy,
  1256. limitTunnelProtocols,
  1257. p.limitTunnelDialPortNumbers,
  1258. p.limitQUICVersions,
  1259. excludeIntensive)
  1260. }
  1261. func (p *protocolSelectionConstraints) selectProtocol(
  1262. connectTunnelCount int,
  1263. excludeIntensive bool,
  1264. serverEntry *protocol.ServerEntry) (string, bool) {
  1265. candidateProtocols := p.supportedProtocols(connectTunnelCount, excludeIntensive, serverEntry)
  1266. if len(candidateProtocols) == 0 {
  1267. return "", false
  1268. }
  1269. // Pick at random from the supported protocols. This ensures that we'll
  1270. // eventually try all possible protocols. Depending on network
  1271. // configuration, it may be the case that some protocol is only available
  1272. // through multi-capability servers, and a simpler ranked preference of
  1273. // protocols could lead to that protocol never being selected.
  1274. index := prng.Intn(len(candidateProtocols))
  1275. return candidateProtocols[index], true
  1276. }
  1277. type candidateServerEntry struct {
  1278. serverEntry *protocol.ServerEntry
  1279. isServerAffinityCandidate bool
  1280. adjustedEstablishStartTime time.Time
  1281. }
  1282. // startEstablishing creates a pool of worker goroutines which will
  1283. // attempt to establish tunnels to candidate servers. The candidates
  1284. // are generated by another goroutine.
  1285. func (controller *Controller) startEstablishing() {
  1286. if controller.isEstablishing {
  1287. return
  1288. }
  1289. NoticeInfo("start establishing")
  1290. // establishStartTime is used to calculate and report the client's tunnel
  1291. // establishment duration. Establishment duration should include all
  1292. // initialization in launchEstablishing and establishCandidateGenerator,
  1293. // including any potentially long-running datastore iterations.
  1294. establishStartTime := time.Now()
  1295. controller.concurrentEstablishTunnelsMutex.Lock()
  1296. controller.establishConnectTunnelCount = 0
  1297. controller.concurrentEstablishTunnels = 0
  1298. controller.concurrentIntensiveEstablishTunnels = 0
  1299. controller.peakConcurrentEstablishTunnels = 0
  1300. controller.peakConcurrentIntensiveEstablishTunnels = 0
  1301. controller.concurrentEstablishTunnelsMutex.Unlock()
  1302. DoGarbageCollection()
  1303. emitMemoryMetrics()
  1304. // The establish context cancelFunc, controller.stopEstablish, is called in
  1305. // controller.stopEstablishing.
  1306. controller.isEstablishing = true
  1307. controller.establishStartTime = establishStartTime
  1308. controller.establishCtx, controller.stopEstablish = context.WithCancel(controller.runCtx)
  1309. controller.establishWaitGroup = new(sync.WaitGroup)
  1310. controller.candidateServerEntries = make(chan *candidateServerEntry)
  1311. // The server affinity mechanism attempts to favor the previously
  1312. // used server when reconnecting. This is beneficial for user
  1313. // applications which expect consistency in user IP address (for
  1314. // example, a web site which prompts for additional user
  1315. // authentication when the IP address changes).
  1316. //
  1317. // Only the very first server, as determined by
  1318. // datastore.PromoteServerEntry(), is the server affinity candidate.
  1319. // Concurrent connections attempts to many servers are launched
  1320. // without delay, in case the affinity server connection fails.
  1321. // While the affinity server connection is outstanding, when any
  1322. // other connection is established, there is a short grace period
  1323. // delay before delivering the established tunnel; this allows some
  1324. // time for the affinity server connection to succeed first.
  1325. // When the affinity server connection fails, any other established
  1326. // tunnel is registered without delay.
  1327. //
  1328. // Note: the establishTunnelWorker that receives the affinity
  1329. // candidate is solely resonsible for closing
  1330. // controller.serverAffinityDoneBroadcast.
  1331. controller.serverAffinityDoneBroadcast = make(chan struct{})
  1332. controller.establishWaitGroup.Add(1)
  1333. go controller.launchEstablishing()
  1334. }
  1335. func (controller *Controller) launchEstablishing() {
  1336. defer controller.establishWaitGroup.Done()
  1337. // Before starting the establish tunnel workers, get and apply
  1338. // tactics, launching a tactics request if required.
  1339. //
  1340. // Wait only TacticsWaitPeriod for the tactics request to complete (or
  1341. // fail) before proceeding with tunnel establishment, in case the tactics
  1342. // request is blocked or takes very long to complete.
  1343. //
  1344. // An in-flight tactics request uses meek in round tripper mode, which
  1345. // uses less resources than meek tunnel relay mode. For this reason, the
  1346. // tactics request is not counted in concurrentIntensiveEstablishTunnels.
  1347. //
  1348. // TODO: HTTP/2 uses significantly more memory, so perhaps
  1349. // concurrentIntensiveEstablishTunnels should be counted in that case.
  1350. //
  1351. // Any in-flight tactics request or pending retry will be
  1352. // canceled when establishment is stopped.
  1353. if !controller.config.DisableTactics {
  1354. timeout := controller.config.GetParameters().Get().Duration(
  1355. parameters.TacticsWaitPeriod)
  1356. tacticsDone := make(chan struct{})
  1357. tacticsWaitPeriod := time.NewTimer(timeout)
  1358. defer tacticsWaitPeriod.Stop()
  1359. controller.establishWaitGroup.Add(1)
  1360. go func() {
  1361. defer controller.establishWaitGroup.Done()
  1362. defer close(tacticsDone)
  1363. GetTactics(controller.establishCtx, controller.config)
  1364. }()
  1365. select {
  1366. case <-tacticsDone:
  1367. case <-tacticsWaitPeriod.C:
  1368. }
  1369. tacticsWaitPeriod.Stop()
  1370. if controller.isStopEstablishing() {
  1371. // This check isn't strictly required but avoids the overhead of launching
  1372. // workers if establishment stopped while awaiting a tactics request.
  1373. return
  1374. }
  1375. }
  1376. // Initial- and LimitTunnelProtocols may be set by tactics.
  1377. //
  1378. // These protocol limits are fixed once per establishment, for
  1379. // consistent application of related probabilities (applied by
  1380. // ParametersAccessor.TunnelProtocols). The
  1381. // establishLimitTunnelProtocolsState field must be read-only after this
  1382. // point, allowing concurrent reads by establishment workers.
  1383. p := controller.config.GetParameters().Get()
  1384. controller.protocolSelectionConstraints = &protocolSelectionConstraints{
  1385. useUpstreamProxy: controller.config.UseUpstreamProxy(),
  1386. initialLimitTunnelProtocols: p.TunnelProtocols(parameters.InitialLimitTunnelProtocols),
  1387. initialLimitTunnelProtocolsCandidateCount: p.Int(parameters.InitialLimitTunnelProtocolsCandidateCount),
  1388. limitTunnelProtocols: p.TunnelProtocols(parameters.LimitTunnelProtocols),
  1389. limitTunnelDialPortNumbers: protocol.TunnelProtocolPortLists(
  1390. p.TunnelProtocolPortLists(parameters.LimitTunnelDialPortNumbers)),
  1391. replayCandidateCount: p.Int(parameters.ReplayCandidateCount),
  1392. }
  1393. // ConnectionWorkerPoolSize may be set by tactics.
  1394. workerPoolSize := p.Int(parameters.ConnectionWorkerPoolSize)
  1395. // When TargetServerEntry is used, override any worker pool size config or
  1396. // tactic parameter and use a pool size of 1. The typical use case for
  1397. // TargetServerEntry is to test a specific server with a single connection
  1398. // attempt. Furthermore, too many concurrent attempts to connect to the
  1399. // same server will trigger rate limiting.
  1400. if controller.config.TargetServerEntry != "" {
  1401. workerPoolSize = 1
  1402. }
  1403. // TunnelPoolSize may be set by tactics, subject to local constraints. A pool
  1404. // size of one is forced in packet tunnel mode or when using a
  1405. // TargetServerEntry. The tunnel pool size is reduced when there are
  1406. // insufficent known server entries, within the set region and protocol
  1407. // constraints, to satisfy the target.
  1408. //
  1409. // Limitations, to simplify concurrent access to shared state: a ceiling of
  1410. // MAX_TUNNEL_POOL_SIZE is enforced by setTunnelPoolSize; the tunnel pool
  1411. // size target is not re-adjusted after an API handshake, even though the
  1412. // handshake response may deliver new tactics, or prune server entries which
  1413. // were potential candidates; nor is the target re-adjusted after fetching
  1414. // new server entries during this establishment.
  1415. tunnelPoolSize := p.Int(parameters.TunnelPoolSize)
  1416. if controller.config.PacketTunnelTunFileDescriptor > 0 ||
  1417. controller.config.TargetServerEntry != "" {
  1418. tunnelPoolSize = 1
  1419. }
  1420. p.Close()
  1421. // Trigger CandidateServers and AvailableEgressRegions notices. By default,
  1422. // this is an asynchronous operation, as the underlying full server entry
  1423. // list enumeration may be a slow operation. In certain cases, where
  1424. // candidate counts are required up front, await the result before
  1425. // proceeding.
  1426. awaitResponse := tunnelPoolSize > 1 ||
  1427. controller.protocolSelectionConstraints.initialLimitTunnelProtocolsCandidateCount > 0
  1428. // AvailableEgressRegions: after a fresh install, the outer client may not
  1429. // have a list of regions to display; and LimitTunnelProtocols may reduce the
  1430. // number of available regions.
  1431. //
  1432. // When the outer client receives NoticeAvailableEgressRegions and the
  1433. // configured EgressRegion is not included in the region list, the outer
  1434. // client _should_ stop tunnel-core and prompt the user to change the region
  1435. // selection, as there are insufficient servers/capabilities to establish a
  1436. // tunnel in the selected region.
  1437. //
  1438. // This report is delayed until after tactics are likely to be applied,
  1439. // above; this avoids a ReportAvailableRegions reporting too many regions,
  1440. // followed shortly by a ReportAvailableRegions reporting fewer regions. That
  1441. // sequence could cause issues in the outer client UI.
  1442. //
  1443. // The reported regions are limited by protocolSelectionConstraints; in the
  1444. // case where an initial limit is in place, only regions available for the
  1445. // initial limit are reported. The initial phase will not complete if
  1446. // EgressRegion is set such that there are no server entries with the
  1447. // necessary protocol capabilities (either locally or from a remote server
  1448. // list fetch).
  1449. // Concurrency note: controller.protocolSelectionConstraints may be
  1450. // overwritten before serverEntriesReporter reads it, and so cannot be
  1451. // accessed directly by serverEntriesReporter.
  1452. reportRequest := &serverEntriesReportRequest{
  1453. constraints: controller.protocolSelectionConstraints,
  1454. }
  1455. if awaitResponse {
  1456. // Buffer size of 1 ensures the sender, serverEntryReporter, won't block on
  1457. // sending the response in the case where launchEstablishing exits due to
  1458. // stopping establishment.
  1459. reportRequest.awaitResponse = make(chan *serverEntriesReportResponse, 1)
  1460. }
  1461. controller.signalServerEntriesReporter(reportRequest)
  1462. if awaitResponse {
  1463. var reportResponse *serverEntriesReportResponse
  1464. select {
  1465. case reportResponse = <-reportRequest.awaitResponse:
  1466. case <-controller.establishCtx.Done():
  1467. // The sender may be gone when shutting down, or may not send until after
  1468. // stopping establishment.
  1469. return
  1470. }
  1471. if reportResponse.err != nil {
  1472. NoticeError("failed to report server entries: %v",
  1473. errors.Trace(reportResponse.err))
  1474. controller.SignalComponentFailure()
  1475. return
  1476. }
  1477. // Make adjustments based on candidate counts.
  1478. if tunnelPoolSize > 1 {
  1479. // Initial canidate count is ignored as count candidates will eventually
  1480. // become available.
  1481. if reportResponse.candidates < tunnelPoolSize {
  1482. tunnelPoolSize = reportResponse.candidates
  1483. }
  1484. if tunnelPoolSize < 1 {
  1485. tunnelPoolSize = 1
  1486. }
  1487. }
  1488. controller.setTunnelPoolSize(tunnelPoolSize)
  1489. // If InitialLimitTunnelProtocols is configured but cannot be satisfied,
  1490. // skip the initial phase in this establishment. This avoids spinning,
  1491. // unable to connect, in this case. InitialLimitTunnelProtocols is
  1492. // intended to prioritize certain protocols, but not strictly select them.
  1493. //
  1494. // The candidate count check ignores egress region selection. When an egress
  1495. // region is selected, it's the responsibility of the outer client to react
  1496. // to the following ReportAvailableRegions output and clear the user's
  1497. // selected region to prevent spinning, unable to connect. The initial phase
  1498. // is skipped only when InitialLimitTunnelProtocols cannot be satisfied
  1499. // _regardless_ of region selection.
  1500. //
  1501. // We presume that, in practise, most clients will have embedded server
  1502. // entries with capabilities for most protocols; and that clients will
  1503. // often perform RSL checks. So clients should most often have the
  1504. // necessary capabilities to satisfy InitialLimitTunnelProtocols. When
  1505. // this check fails, RSL/OSL/upgrade checks are triggered in order to gain
  1506. // new capabilities.
  1507. //
  1508. // LimitTunnelProtocols remains a hard limit, as using prohibited
  1509. // protocols may have some bad effect, such as a firewall blocking all
  1510. // traffic from a host.
  1511. if controller.protocolSelectionConstraints.initialLimitTunnelProtocolsCandidateCount > 0 {
  1512. if reportResponse.initialCandidatesAnyEgressRegion == 0 {
  1513. NoticeWarning("skipping initial limit tunnel protocols")
  1514. controller.protocolSelectionConstraints.initialLimitTunnelProtocolsCandidateCount = 0
  1515. // Since we were unable to satisfy the InitialLimitTunnelProtocols
  1516. // tactic, trigger RSL, OSL, and upgrade fetches to potentially
  1517. // gain new capabilities.
  1518. controller.triggerFetches()
  1519. }
  1520. }
  1521. }
  1522. for i := 0; i < workerPoolSize; i++ {
  1523. controller.establishWaitGroup.Add(1)
  1524. go controller.establishTunnelWorker()
  1525. }
  1526. controller.establishWaitGroup.Add(1)
  1527. go controller.establishCandidateGenerator()
  1528. }
  1529. // stopEstablishing signals the establish goroutines to stop and waits
  1530. // for the group to halt.
  1531. func (controller *Controller) stopEstablishing() {
  1532. if !controller.isEstablishing {
  1533. return
  1534. }
  1535. NoticeInfo("stop establishing")
  1536. controller.stopEstablish()
  1537. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  1538. // (as it may be sending to that channel).
  1539. controller.establishWaitGroup.Wait()
  1540. NoticeInfo("stopped establishing")
  1541. controller.isEstablishing = false
  1542. controller.establishStartTime = time.Time{}
  1543. controller.establishCtx = nil
  1544. controller.stopEstablish = nil
  1545. controller.establishWaitGroup = nil
  1546. controller.candidateServerEntries = nil
  1547. controller.serverAffinityDoneBroadcast = nil
  1548. controller.concurrentEstablishTunnelsMutex.Lock()
  1549. peakConcurrent := controller.peakConcurrentEstablishTunnels
  1550. peakConcurrentIntensive := controller.peakConcurrentIntensiveEstablishTunnels
  1551. controller.establishConnectTunnelCount = 0
  1552. controller.concurrentEstablishTunnels = 0
  1553. controller.concurrentIntensiveEstablishTunnels = 0
  1554. controller.peakConcurrentEstablishTunnels = 0
  1555. controller.peakConcurrentIntensiveEstablishTunnels = 0
  1556. controller.concurrentEstablishTunnelsMutex.Unlock()
  1557. NoticeInfo("peak concurrent establish tunnels: %d", peakConcurrent)
  1558. NoticeInfo("peak concurrent resource intensive establish tunnels: %d", peakConcurrentIntensive)
  1559. emitMemoryMetrics()
  1560. DoGarbageCollection()
  1561. // Record datastore metrics after establishment, the phase which generates
  1562. // the bulk of all datastore transactions: iterating over server entries,
  1563. // storing new server entries, etc.
  1564. emitDatastoreMetrics()
  1565. // Similarly, establishment generates the bulk of domain resolves.
  1566. emitDNSMetrics(controller.resolver)
  1567. }
  1568. // establishCandidateGenerator populates the candidate queue with server entries
  1569. // from the data store. Server entries are iterated in rank order, so that promoted
  1570. // servers with higher rank are priority candidates.
  1571. func (controller *Controller) establishCandidateGenerator() {
  1572. defer controller.establishWaitGroup.Done()
  1573. defer close(controller.candidateServerEntries)
  1574. // networkWaitDuration is the elapsed time spent waiting
  1575. // for network connectivity. This duration will be excluded
  1576. // from reported tunnel establishment duration.
  1577. var totalNetworkWaitDuration time.Duration
  1578. applyServerAffinity, iterator, err := NewServerEntryIterator(controller.config)
  1579. if err != nil {
  1580. NoticeError("failed to iterate over candidates: %v", errors.Trace(err))
  1581. controller.SignalComponentFailure()
  1582. return
  1583. }
  1584. defer iterator.Close()
  1585. // TODO: reconcile server affinity scheme with multi-tunnel mode
  1586. if controller.getTunnelPoolSize() > 1 {
  1587. applyServerAffinity = false
  1588. }
  1589. isServerAffinityCandidate := true
  1590. if !applyServerAffinity {
  1591. isServerAffinityCandidate = false
  1592. close(controller.serverAffinityDoneBroadcast)
  1593. }
  1594. loop:
  1595. // Repeat until stopped
  1596. for {
  1597. // A "round" consists of a new shuffle of the server entries and attempted
  1598. // connections up to the end of the server entry iterator, or
  1599. // parameters.EstablishTunnelWorkTime elapsed. Time spent waiting for
  1600. // network connectivity is excluded from round elapsed time.
  1601. //
  1602. // After a round, if parameters.EstablishTunnelWorkTime has elapsed in total
  1603. // with no tunnel established, remote server list and upgrade checks are
  1604. // triggered.
  1605. //
  1606. // A complete server entry iteration does not trigger fetches since it's
  1607. // possible to have fewer than parameters.ConnectionWorkerPoolSize
  1608. // candidates, in which case rounds end instantly due to the complete server
  1609. // entry iteration. An exception is made for an empty server entry iterator;
  1610. // in that case fetches may be triggered immediately.
  1611. //
  1612. // The number of server candidates may change during this loop, due to
  1613. // remote server list fetches. Due to the performance impact, we will not
  1614. // trigger additional, informational CandidateServer notices while in the
  1615. // establishing loop. Clients typically re-establish often enough that we
  1616. // will see the effect of the remote server list fetch in diagnostics.
  1617. roundStartTime := time.Now()
  1618. var roundNetworkWaitDuration time.Duration
  1619. workTime := controller.config.GetParameters().Get().Duration(
  1620. parameters.EstablishTunnelWorkTime)
  1621. candidateServerEntryCount := 0
  1622. // Send each iterator server entry to the establish workers
  1623. for {
  1624. networkWaitStartTime := time.Now()
  1625. if !WaitForNetworkConnectivity(
  1626. controller.establishCtx,
  1627. controller.config.NetworkConnectivityChecker) {
  1628. break loop
  1629. }
  1630. networkWaitDuration := time.Since(networkWaitStartTime)
  1631. roundNetworkWaitDuration += networkWaitDuration
  1632. totalNetworkWaitDuration += networkWaitDuration
  1633. serverEntry, err := iterator.Next()
  1634. if err != nil {
  1635. NoticeError("failed to get next candidate: %v", errors.Trace(err))
  1636. controller.SignalComponentFailure()
  1637. break loop
  1638. }
  1639. if serverEntry == nil {
  1640. // Completed this iteration
  1641. NoticeInfo("completed server entry iteration")
  1642. break
  1643. }
  1644. if controller.config.TargetApiProtocol == protocol.PSIPHON_SSH_API_PROTOCOL &&
  1645. !serverEntry.SupportsSSHAPIRequests() {
  1646. continue
  1647. }
  1648. candidateServerEntryCount += 1
  1649. // adjustedEstablishStartTime is establishStartTime shifted
  1650. // to exclude time spent waiting for network connectivity.
  1651. adjustedEstablishStartTime := controller.establishStartTime.Add(
  1652. totalNetworkWaitDuration)
  1653. candidate := &candidateServerEntry{
  1654. serverEntry: serverEntry,
  1655. isServerAffinityCandidate: isServerAffinityCandidate,
  1656. adjustedEstablishStartTime: adjustedEstablishStartTime,
  1657. }
  1658. wasServerAffinityCandidate := isServerAffinityCandidate
  1659. // Note: there must be only one server affinity candidate, as it
  1660. // closes the serverAffinityDoneBroadcast channel.
  1661. isServerAffinityCandidate = false
  1662. // TODO: here we could generate multiple candidates from the
  1663. // server entry when there are many MeekFrontingAddresses.
  1664. select {
  1665. case controller.candidateServerEntries <- candidate:
  1666. case <-controller.establishCtx.Done():
  1667. break loop
  1668. }
  1669. if time.Since(roundStartTime)-roundNetworkWaitDuration > workTime {
  1670. // Start over, after a brief pause, with a new shuffle of the server
  1671. // entries, and potentially some newly fetched server entries.
  1672. break
  1673. }
  1674. if wasServerAffinityCandidate {
  1675. // Don't start the next candidate until either the server affinity
  1676. // candidate has completed (success or failure) or is still working
  1677. // and the grace period has elapsed.
  1678. gracePeriod := controller.config.GetParameters().Get().Duration(
  1679. parameters.EstablishTunnelServerAffinityGracePeriod)
  1680. if gracePeriod > 0 {
  1681. timer := time.NewTimer(gracePeriod)
  1682. select {
  1683. case <-timer.C:
  1684. case <-controller.serverAffinityDoneBroadcast:
  1685. case <-controller.establishCtx.Done():
  1686. timer.Stop()
  1687. break loop
  1688. }
  1689. timer.Stop()
  1690. }
  1691. }
  1692. }
  1693. // Free up resources now, but don't reset until after the pause.
  1694. iterator.Close()
  1695. // Trigger RSL, OSL, and upgrade checks after failing to establish a
  1696. // tunnel within parameters.EstablishTunnelWorkTime, or if there are
  1697. // no server entries present.
  1698. //
  1699. // While the trigger is made after each round,
  1700. // parameter.FetchRemoteServerListStalePeriod will limit the actual
  1701. // frequency of fetches. Continuing to trigger allows for very long running
  1702. // establishments to perhaps eventually succeed.
  1703. //
  1704. // No fetches are triggered when TargetServerEntry is specified. In that
  1705. // case, we're only trying to connect to a specific server entry.
  1706. if (candidateServerEntryCount == 0 ||
  1707. time.Since(controller.establishStartTime)-totalNetworkWaitDuration > workTime) &&
  1708. controller.config.TargetServerEntry == "" {
  1709. controller.triggerFetches()
  1710. }
  1711. // After a complete iteration of candidate servers, pause before iterating again.
  1712. // This helps avoid some busy wait loop conditions, and also allows some time for
  1713. // network conditions to change. Also allows for fetch remote to complete,
  1714. // in typical conditions (it isn't strictly necessary to wait for this, there will
  1715. // be more rounds if required).
  1716. p := controller.config.GetParameters().Get()
  1717. timeout := prng.JitterDuration(
  1718. p.Duration(parameters.EstablishTunnelPausePeriod),
  1719. p.Float(parameters.EstablishTunnelPausePeriodJitter))
  1720. p.Close()
  1721. timer := time.NewTimer(timeout)
  1722. select {
  1723. case <-timer.C:
  1724. // Retry iterating
  1725. case <-controller.establishCtx.Done():
  1726. timer.Stop()
  1727. break loop
  1728. }
  1729. timer.Stop()
  1730. iterator.Reset()
  1731. }
  1732. }
  1733. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  1734. // a connection to the tunnel server, and delivers the connected tunnel to a channel.
  1735. func (controller *Controller) establishTunnelWorker() {
  1736. defer controller.establishWaitGroup.Done()
  1737. loop:
  1738. for candidateServerEntry := range controller.candidateServerEntries {
  1739. // Note: don't receive from candidateServerEntries and isStopEstablishing
  1740. // in the same select, since we want to prioritize receiving the stop signal
  1741. if controller.isStopEstablishing() {
  1742. break loop
  1743. }
  1744. // There may already be a tunnel to this candidate. If so, skip it.
  1745. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  1746. continue
  1747. }
  1748. // TODO: we allow multiple, concurrent workers to attempt to connect to the
  1749. // same server. This is not wasteful if the server supports several
  1750. // different protocols, some of which may be blocked while others are not
  1751. // blocked. Limiting protocols with [Initial]LimitTunnelProtocols may make
  1752. // these multiple attempts redundent. Also, replay should be used only by
  1753. // the first attempt.
  1754. // upstreamProxyErrorCallback will post NoticeUpstreamProxyError when the
  1755. // tunnel dial fails due to an upstream proxy error. As the upstream proxy
  1756. // is user configured, the error message may need to be relayed to the user.
  1757. // As the callback may be invoked after establishment is over (e.g., if an
  1758. // initial dial isn't fully shutdown when ConnectTunnel returns; or a meek
  1759. // underlying TCP connection re-dial) don't access these variables
  1760. // directly.
  1761. callbackCandidateServerEntry := candidateServerEntry
  1762. callbackEstablishCtx := controller.establishCtx
  1763. upstreamProxyErrorCallback := func(err error) {
  1764. // Do not post the notice when overall establishment context is canceled or
  1765. // timed-out: the upstream proxy connection error is likely a result of the
  1766. // cancellation, and not a condition to be fixed by the user. In the case
  1767. // of meek underlying TCP connection re-dials, this condition will always
  1768. // be true; however in this case the initial dial succeeded with the
  1769. // current upstream proxy settings, so any upstream proxy error is
  1770. // transient.
  1771. if callbackEstablishCtx.Err() != nil {
  1772. return
  1773. }
  1774. // Another class of non-fatal upstream proxy error arises from proxies
  1775. // which limit permitted proxied ports. In this case, some tunnels may fail
  1776. // due to dial port, while others may eventually succeed. To avoid this
  1777. // class of errors, delay posting the notice. If the upstream proxy works,
  1778. // _some_ tunnel should connect. If the upstream proxy configuration is
  1779. // broken, the error should persist and eventually get posted.
  1780. p := controller.config.GetParameters().Get()
  1781. workerPoolSize := p.Int(parameters.ConnectionWorkerPoolSize)
  1782. minWaitDuration := p.Duration(parameters.UpstreamProxyErrorMinWaitDuration)
  1783. maxWaitDuration := p.Duration(parameters.UpstreamProxyErrorMaxWaitDuration)
  1784. p.Close()
  1785. controller.concurrentEstablishTunnelsMutex.Lock()
  1786. establishConnectTunnelCount := controller.establishConnectTunnelCount
  1787. controller.concurrentEstablishTunnelsMutex.Unlock()
  1788. // Delay UpstreamProxyErrorMinWaitDuration (excluding time spent waiting
  1789. // for network connectivity) and then until either
  1790. // UpstreamProxyErrorMaxWaitDuration has elapsed or, to post sooner if many
  1791. // candidates are failing, at least workerPoolSize tunnel connection
  1792. // attempts have completed. We infer that at least workerPoolSize
  1793. // candidates have completed by checking that at least 2*workerPoolSize
  1794. // candidates have started.
  1795. elapsedTime := time.Since(
  1796. callbackCandidateServerEntry.adjustedEstablishStartTime)
  1797. if elapsedTime < minWaitDuration ||
  1798. (elapsedTime < maxWaitDuration &&
  1799. establishConnectTunnelCount < 2*workerPoolSize) {
  1800. return
  1801. }
  1802. NoticeUpstreamProxyError(err)
  1803. }
  1804. // Select the tunnel protocol. The selection will be made at random
  1805. // from protocols supported by the server entry, optionally limited by
  1806. // LimitTunnelProtocols.
  1807. //
  1808. // When limiting concurrent resource intensive protocol connection
  1809. // workers, and at the limit, do not select resource intensive
  1810. // protocols since otherwise the candidate must be skipped.
  1811. //
  1812. // If at the limit and unabled to select a non-intensive protocol,
  1813. // skip the candidate entirely and move on to the next. Since
  1814. // candidates are shuffled it's likely that the next candidate is not
  1815. // intensive. In this case, a StaggerConnectionWorkersMilliseconds
  1816. // delay may still be incurred.
  1817. limitIntensiveConnectionWorkers := controller.config.GetParameters().Get().Int(
  1818. parameters.LimitIntensiveConnectionWorkers)
  1819. controller.concurrentEstablishTunnelsMutex.Lock()
  1820. excludeIntensive := false
  1821. if limitIntensiveConnectionWorkers > 0 &&
  1822. controller.concurrentIntensiveEstablishTunnels >= limitIntensiveConnectionWorkers {
  1823. excludeIntensive = true
  1824. }
  1825. canReplay := func(serverEntry *protocol.ServerEntry, replayProtocol string) bool {
  1826. return controller.protocolSelectionConstraints.canReplay(
  1827. controller.establishConnectTunnelCount,
  1828. excludeIntensive,
  1829. serverEntry,
  1830. replayProtocol)
  1831. }
  1832. selectProtocol := func(serverEntry *protocol.ServerEntry) (string, bool) {
  1833. return controller.protocolSelectionConstraints.selectProtocol(
  1834. controller.establishConnectTunnelCount,
  1835. excludeIntensive,
  1836. serverEntry)
  1837. }
  1838. // MakeDialParameters may return a replay instance, if the server
  1839. // entry has a previous, recent successful connection and
  1840. // tactics/config has not changed.
  1841. //
  1842. // In the first round -- and later rounds, with some probability -- of
  1843. // establishing, ServerEntryIterator will move potential replay candidates
  1844. // to the front of the iterator after the random shuffle, which greatly
  1845. // prioritizes previously successful servers for that round.
  1846. //
  1847. // As ServerEntryIterator does not unmarshal and validate replay
  1848. // candidate dial parameters, some potential replay candidates may
  1849. // have expired or otherwise ineligible dial parameters; in this case
  1850. // the candidate proceeds without replay.
  1851. //
  1852. // The ReplayCandidateCount tactic determines how many candidates may use
  1853. // replay. After ReplayCandidateCount candidates of any type, replay or no,
  1854. // replay is skipped. If ReplayCandidateCount exceeds the intial round,
  1855. // replay may still be performed but the iterator may no longer move
  1856. // potential replay server entries to the front. When ReplayCandidateCount
  1857. // is set to -1, unlimited candidates may use replay.
  1858. dialParams, err := MakeDialParameters(
  1859. controller.config,
  1860. controller.steeringIPCache,
  1861. controller.tlsClientSessionCache,
  1862. controller.utlsClientSessionCache,
  1863. upstreamProxyErrorCallback,
  1864. canReplay,
  1865. selectProtocol,
  1866. candidateServerEntry.serverEntry,
  1867. false,
  1868. controller.establishConnectTunnelCount,
  1869. int(atomic.LoadInt32(&controller.establishedTunnelsCount)))
  1870. if dialParams == nil || err != nil {
  1871. controller.concurrentEstablishTunnelsMutex.Unlock()
  1872. // MakeDialParameters returns nil/nil when the server entry is to
  1873. // be skipped. See MakeDialParameters for skip cases and skip
  1874. // logging. Silently fail the candidate in this case. Otherwise,
  1875. // emit error.
  1876. if err != nil {
  1877. NoticeInfo("failed to make dial parameters for %s: %v",
  1878. candidateServerEntry.serverEntry.GetDiagnosticID(),
  1879. errors.Trace(err))
  1880. }
  1881. // Unblock other candidates immediately when server affinity
  1882. // candidate is skipped.
  1883. if candidateServerEntry.isServerAffinityCandidate {
  1884. close(controller.serverAffinityDoneBroadcast)
  1885. }
  1886. continue
  1887. }
  1888. // Increment establishConnectTunnelCount only after selectProtocol has
  1889. // succeeded to ensure InitialLimitTunnelProtocolsCandidateCount
  1890. // candidates use InitialLimitTunnelProtocols.
  1891. establishConnectTunnelCount := controller.establishConnectTunnelCount
  1892. controller.establishConnectTunnelCount += 1
  1893. isIntensive := protocol.TunnelProtocolIsResourceIntensive(dialParams.TunnelProtocol)
  1894. if isIntensive {
  1895. controller.concurrentIntensiveEstablishTunnels += 1
  1896. if controller.concurrentIntensiveEstablishTunnels > controller.peakConcurrentIntensiveEstablishTunnels {
  1897. controller.peakConcurrentIntensiveEstablishTunnels = controller.concurrentIntensiveEstablishTunnels
  1898. }
  1899. }
  1900. controller.concurrentEstablishTunnels += 1
  1901. if controller.concurrentEstablishTunnels > controller.peakConcurrentEstablishTunnels {
  1902. controller.peakConcurrentEstablishTunnels = controller.concurrentEstablishTunnels
  1903. }
  1904. controller.concurrentEstablishTunnelsMutex.Unlock()
  1905. // Apply stagger only now that we're past MakeDialParameters and
  1906. // protocol selection logic which may have caused the candidate to be
  1907. // skipped. The stagger logic delays dialing, and we don't want to
  1908. // incur that delay that when skipping.
  1909. //
  1910. // Locking staggerMutex serializes staggers, so that multiple workers
  1911. // don't simply sleep in parallel.
  1912. //
  1913. // The stagger is applied when establishConnectTunnelCount > 0 -- that
  1914. // is, for all but the first dial.
  1915. p := controller.config.GetParameters().Get()
  1916. staggerPeriod := p.Duration(parameters.StaggerConnectionWorkersPeriod)
  1917. staggerJitter := p.Float(parameters.StaggerConnectionWorkersJitter)
  1918. p.Close()
  1919. if establishConnectTunnelCount > 0 && staggerPeriod != 0 {
  1920. controller.staggerMutex.Lock()
  1921. timer := time.NewTimer(prng.JitterDuration(staggerPeriod, staggerJitter))
  1922. select {
  1923. case <-timer.C:
  1924. case <-controller.establishCtx.Done():
  1925. }
  1926. timer.Stop()
  1927. controller.staggerMutex.Unlock()
  1928. }
  1929. // ConnectTunnel will allocate significant memory, so first attempt to
  1930. // reclaim as much as possible.
  1931. DoGarbageCollection()
  1932. tunnel, err := ConnectTunnel(
  1933. controller.establishCtx,
  1934. controller.config,
  1935. candidateServerEntry.adjustedEstablishStartTime,
  1936. dialParams)
  1937. controller.concurrentEstablishTunnelsMutex.Lock()
  1938. if isIntensive {
  1939. controller.concurrentIntensiveEstablishTunnels -= 1
  1940. }
  1941. controller.concurrentEstablishTunnels -= 1
  1942. controller.concurrentEstablishTunnelsMutex.Unlock()
  1943. // Periodically emit memory metrics during the establishment cycle.
  1944. if !controller.isStopEstablishing() {
  1945. emitMemoryMetrics()
  1946. }
  1947. // Immediately reclaim memory allocated by the establishment. In the case
  1948. // of failure, first clear the reference to the tunnel. In the case of
  1949. // success, the garbage collection may still be effective as the initial
  1950. // phases of some protocols involve significant memory allocation that
  1951. // could now be reclaimed.
  1952. if err != nil {
  1953. tunnel = nil
  1954. }
  1955. DoGarbageCollection()
  1956. if err != nil {
  1957. // Unblock other candidates immediately when server affinity
  1958. // candidate fails.
  1959. if candidateServerEntry.isServerAffinityCandidate {
  1960. close(controller.serverAffinityDoneBroadcast)
  1961. }
  1962. // Before emitting error, check if establish interrupted, in which
  1963. // case the error is noise.
  1964. if controller.isStopEstablishing() {
  1965. break loop
  1966. }
  1967. NoticeInfo("failed to connect to %s: %v",
  1968. candidateServerEntry.serverEntry.GetDiagnosticID(),
  1969. errors.Trace(err))
  1970. continue
  1971. }
  1972. // Deliver connected tunnel.
  1973. // Don't block. Assumes the receiver has a buffer large enough for
  1974. // the number of desired tunnels. If there's no room, the tunnel must
  1975. // not be required so it's discarded.
  1976. select {
  1977. case controller.connectedTunnels <- tunnel:
  1978. default:
  1979. controller.discardTunnel(tunnel)
  1980. // Clear the reference to this discarded tunnel and immediately run
  1981. // a garbage collection to reclaim its memory.
  1982. tunnel = nil
  1983. DoGarbageCollection()
  1984. }
  1985. // Unblock other candidates only after delivering when
  1986. // server affinity candidate succeeds.
  1987. if candidateServerEntry.isServerAffinityCandidate {
  1988. close(controller.serverAffinityDoneBroadcast)
  1989. }
  1990. }
  1991. }
  1992. func (controller *Controller) isStopEstablishing() bool {
  1993. select {
  1994. case <-controller.establishCtx.Done():
  1995. return true
  1996. default:
  1997. }
  1998. return false
  1999. }