controller.go 83 KB

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