controller.go 82 KB

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