controller.go 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. // Package psiphon implements the core tunnel functionality of a Psiphon client.
  20. // The main function is RunForever, which runs a Controller that obtains lists of
  21. // servers, establishes tunnel connections, and runs local proxies through which
  22. // tunneled traffic may be sent.
  23. package psiphon
  24. import (
  25. "context"
  26. "errors"
  27. "fmt"
  28. "math/rand"
  29. "net"
  30. "sync"
  31. "time"
  32. "github.com/Psiphon-Labs/goarista/monotime"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  39. )
  40. // Controller is a tunnel lifecycle coordinator. It manages lists of servers to
  41. // connect to; establishes and monitors tunnels; and runs local proxies which
  42. // route traffic through the tunnels.
  43. type Controller struct {
  44. config *Config
  45. sessionId string
  46. runCtx context.Context
  47. stopRunning context.CancelFunc
  48. runWaitGroup *sync.WaitGroup
  49. connectedTunnels chan *Tunnel
  50. failedTunnels chan *Tunnel
  51. tunnelMutex sync.Mutex
  52. establishedOnce bool
  53. tunnels []*Tunnel
  54. nextTunnel int
  55. startedConnectedReporter bool
  56. isEstablishing bool
  57. protocolSelectionConstraints *protocolSelectionConstraints
  58. concurrentEstablishTunnelsMutex sync.Mutex
  59. establishConnectTunnelCount int
  60. concurrentEstablishTunnels int
  61. concurrentIntensiveEstablishTunnels int
  62. peakConcurrentEstablishTunnels int
  63. peakConcurrentIntensiveEstablishTunnels int
  64. establishCtx context.Context
  65. stopEstablish context.CancelFunc
  66. establishWaitGroup *sync.WaitGroup
  67. candidateServerEntries chan *candidateServerEntry
  68. untunneledDialConfig *DialConfig
  69. splitTunnelClassifier *SplitTunnelClassifier
  70. signalFetchCommonRemoteServerList chan struct{}
  71. signalFetchObfuscatedServerLists chan struct{}
  72. signalDownloadUpgrade chan string
  73. signalReportConnected chan struct{}
  74. serverAffinityDoneBroadcast chan struct{}
  75. packetTunnelClient *tun.Client
  76. packetTunnelTransport *PacketTunnelTransport
  77. }
  78. // NewController initializes a new controller.
  79. func NewController(config *Config) (controller *Controller, err error) {
  80. if !config.IsCommitted() {
  81. return nil, common.ContextError(errors.New("uncommitted config"))
  82. }
  83. // Needed by regen, at least
  84. rand.Seed(int64(time.Now().Nanosecond()))
  85. // The session ID for the Psiphon server API is used across all
  86. // tunnels established by the controller.
  87. NoticeSessionId(config.SessionID)
  88. untunneledDialConfig := &DialConfig{
  89. UpstreamProxyURL: config.UpstreamProxyURL,
  90. CustomHeaders: config.CustomHeaders,
  91. DeviceBinder: config.deviceBinder,
  92. DnsServerGetter: config.DnsServerGetter,
  93. IPv6Synthesizer: config.IPv6Synthesizer,
  94. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  95. }
  96. controller = &Controller{
  97. config: config,
  98. sessionId: config.SessionID,
  99. runWaitGroup: new(sync.WaitGroup),
  100. // connectedTunnels and failedTunnels buffer sizes are large enough to
  101. // receive full pools of tunnels without blocking. Senders should not block.
  102. connectedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  103. failedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  104. tunnels: make([]*Tunnel, 0),
  105. establishedOnce: false,
  106. startedConnectedReporter: false,
  107. isEstablishing: false,
  108. untunneledDialConfig: untunneledDialConfig,
  109. // TODO: Add a buffer of 1 so we don't miss a signal while receiver is
  110. // starting? Trade-off is potential back-to-back fetch remotes. As-is,
  111. // establish will eventually signal another fetch remote.
  112. signalFetchCommonRemoteServerList: make(chan struct{}),
  113. signalFetchObfuscatedServerLists: make(chan struct{}),
  114. signalDownloadUpgrade: make(chan string),
  115. signalReportConnected: make(chan struct{}),
  116. }
  117. controller.splitTunnelClassifier = NewSplitTunnelClassifier(config, controller)
  118. if config.PacketTunnelTunFileDescriptor > 0 {
  119. // Run a packet tunnel client. The lifetime of the tun.Client is the
  120. // lifetime of the Controller, so it exists across tunnel establishments
  121. // and reestablishments. The PacketTunnelTransport provides a layer
  122. // that presents a continuosuly existing transport to the tun.Client;
  123. // it's set to use new SSH channels after new SSH tunnel establishes.
  124. packetTunnelTransport := NewPacketTunnelTransport()
  125. packetTunnelClient, err := tun.NewClient(&tun.ClientConfig{
  126. Logger: NoticeCommonLogger(),
  127. TunFileDescriptor: config.PacketTunnelTunFileDescriptor,
  128. Transport: packetTunnelTransport,
  129. })
  130. if err != nil {
  131. return nil, common.ContextError(err)
  132. }
  133. controller.packetTunnelClient = packetTunnelClient
  134. controller.packetTunnelTransport = packetTunnelTransport
  135. }
  136. return controller, nil
  137. }
  138. // Run executes the controller. Run exits if a controller
  139. // component fails or the parent context is canceled.
  140. func (controller *Controller) Run(ctx context.Context) {
  141. pprofRun()
  142. // Ensure fresh repetitive notice state for each run, so the
  143. // client will always get an AvailableEgressRegions notice,
  144. // an initial instance of any repetitive error notice, etc.
  145. ResetRepetitiveNotices()
  146. runCtx, stopRunning := context.WithCancel(ctx)
  147. defer stopRunning()
  148. controller.runCtx = runCtx
  149. controller.stopRunning = stopRunning
  150. // Start components
  151. // TODO: IPv6 support
  152. var listenIP string
  153. if controller.config.ListenInterface == "" {
  154. listenIP = "127.0.0.1"
  155. } else if controller.config.ListenInterface == "any" {
  156. listenIP = "0.0.0.0"
  157. } else {
  158. IPv4Address, _, err := common.GetInterfaceIPAddresses(controller.config.ListenInterface)
  159. if err == nil && IPv4Address == nil {
  160. err = fmt.Errorf("no IPv4 address for interface %s", controller.config.ListenInterface)
  161. }
  162. if err != nil {
  163. NoticeError("error getting listener IP: %s", err)
  164. return
  165. }
  166. listenIP = IPv4Address.String()
  167. }
  168. if !controller.config.DisableLocalSocksProxy {
  169. socksProxy, err := NewSocksProxy(controller.config, controller, listenIP)
  170. if err != nil {
  171. NoticeAlert("error initializing local SOCKS proxy: %s", err)
  172. return
  173. }
  174. defer socksProxy.Close()
  175. }
  176. if !controller.config.DisableLocalHTTPProxy {
  177. httpProxy, err := NewHttpProxy(controller.config, controller, listenIP)
  178. if err != nil {
  179. NoticeAlert("error initializing local HTTP proxy: %s", err)
  180. return
  181. }
  182. defer httpProxy.Close()
  183. }
  184. if !controller.config.DisableRemoteServerListFetcher {
  185. if controller.config.RemoteServerListURLs != nil {
  186. controller.runWaitGroup.Add(1)
  187. go controller.remoteServerListFetcher(
  188. "common",
  189. FetchCommonRemoteServerList,
  190. controller.signalFetchCommonRemoteServerList)
  191. }
  192. if controller.config.ObfuscatedServerListRootURLs != nil {
  193. controller.runWaitGroup.Add(1)
  194. go controller.remoteServerListFetcher(
  195. "obfuscated",
  196. FetchObfuscatedServerLists,
  197. controller.signalFetchObfuscatedServerLists)
  198. }
  199. }
  200. if controller.config.UpgradeDownloadURLs != nil {
  201. controller.runWaitGroup.Add(1)
  202. go controller.upgradeDownloader()
  203. }
  204. /// Note: the connected reporter isn't started until a tunnel is
  205. // established
  206. controller.runWaitGroup.Add(1)
  207. go controller.runTunnels()
  208. controller.runWaitGroup.Add(1)
  209. go controller.establishTunnelWatcher()
  210. if controller.packetTunnelClient != nil {
  211. controller.packetTunnelClient.Start()
  212. }
  213. // Wait while running
  214. <-controller.runCtx.Done()
  215. NoticeInfo("controller stopped")
  216. if controller.packetTunnelClient != nil {
  217. controller.packetTunnelClient.Stop()
  218. }
  219. // All workers -- runTunnels, establishment workers, and auxilliary
  220. // workers such as fetch remote server list and untunneled uprade
  221. // download -- operate with the controller run context and will all
  222. // be interrupted when the run context is done.
  223. controller.runWaitGroup.Wait()
  224. controller.splitTunnelClassifier.Shutdown()
  225. NoticeInfo("exiting controller")
  226. NoticeExiting()
  227. }
  228. // SignalComponentFailure notifies the controller that an associated component has failed.
  229. // This will terminate the controller.
  230. func (controller *Controller) SignalComponentFailure() {
  231. NoticeAlert("controller shutdown due to component failure")
  232. controller.stopRunning()
  233. }
  234. // SetDynamicConfig overrides the sponsor ID and authorizations fields of the
  235. // Controller config with the input values. The new values will be used in the
  236. // next tunnel connection.
  237. func (controller *Controller) SetDynamicConfig(sponsorID string, authorizations []string) {
  238. controller.config.SetDynamicConfig(sponsorID, authorizations)
  239. }
  240. // TerminateNextActiveTunnel terminates the active tunnel, which will initiate
  241. // establishment of a new tunnel.
  242. func (controller *Controller) TerminateNextActiveTunnel() {
  243. tunnel := controller.getNextActiveTunnel()
  244. if tunnel != nil {
  245. controller.SignalTunnelFailure(tunnel)
  246. NoticeInfo("terminated tunnel: %s", tunnel.dialParams.ServerEntry.IpAddress)
  247. }
  248. }
  249. // remoteServerListFetcher fetches an out-of-band list of server entries
  250. // for more tunnel candidates. It fetches when signalled, with retries
  251. // on failure.
  252. func (controller *Controller) remoteServerListFetcher(
  253. name string,
  254. fetcher RemoteServerListFetcher,
  255. signal <-chan struct{}) {
  256. defer controller.runWaitGroup.Done()
  257. var lastFetchTime monotime.Time
  258. fetcherLoop:
  259. for {
  260. // Wait for a signal before fetching
  261. select {
  262. case <-signal:
  263. case <-controller.runCtx.Done():
  264. break fetcherLoop
  265. }
  266. // Skip fetch entirely (i.e., send no request at all, even when ETag would save
  267. // on response size) when a recent fetch was successful
  268. stalePeriod := controller.config.clientParameters.Get().Duration(
  269. parameters.FetchRemoteServerListStalePeriod)
  270. if lastFetchTime != 0 &&
  271. lastFetchTime.Add(stalePeriod).After(monotime.Now()) {
  272. continue
  273. }
  274. retryLoop:
  275. for attempt := 0; ; attempt++ {
  276. // Don't attempt to fetch while there is no network connectivity,
  277. // to avoid alert notice noise.
  278. if !WaitForNetworkConnectivity(
  279. controller.runCtx,
  280. controller.config.NetworkConnectivityChecker) {
  281. break fetcherLoop
  282. }
  283. // Pick any active tunnel and make the next fetch attempt. If there's
  284. // no active tunnel, the untunneledDialConfig will be used.
  285. tunnel := controller.getNextActiveTunnel()
  286. err := fetcher(
  287. controller.runCtx,
  288. controller.config,
  289. attempt,
  290. tunnel,
  291. controller.untunneledDialConfig)
  292. if err == nil {
  293. lastFetchTime = monotime.Now()
  294. break retryLoop
  295. }
  296. NoticeAlert("failed to fetch %s remote server list: %s", name, err)
  297. retryPeriod := controller.config.clientParameters.Get().Duration(
  298. parameters.FetchRemoteServerListRetryPeriod)
  299. timer := time.NewTimer(retryPeriod)
  300. select {
  301. case <-timer.C:
  302. case <-controller.runCtx.Done():
  303. timer.Stop()
  304. break fetcherLoop
  305. }
  306. }
  307. }
  308. NoticeInfo("exiting %s remote server list fetcher", name)
  309. }
  310. // establishTunnelWatcher terminates the controller if a tunnel
  311. // has not been established in the configured time period. This
  312. // is regardless of how many tunnels are presently active -- meaning
  313. // that if an active tunnel was established and lost the controller
  314. // is left running (to re-establish).
  315. func (controller *Controller) establishTunnelWatcher() {
  316. defer controller.runWaitGroup.Done()
  317. timeout := controller.config.clientParameters.Get().Duration(
  318. parameters.EstablishTunnelTimeout)
  319. if timeout > 0 {
  320. timer := time.NewTimer(timeout)
  321. defer timer.Stop()
  322. select {
  323. case <-timer.C:
  324. if !controller.hasEstablishedOnce() {
  325. NoticeEstablishTunnelTimeout(timeout)
  326. controller.SignalComponentFailure()
  327. }
  328. case <-controller.runCtx.Done():
  329. }
  330. }
  331. NoticeInfo("exiting establish tunnel watcher")
  332. }
  333. // connectedReporter sends periodic "connected" requests to the Psiphon API.
  334. // These requests are for server-side unique user stats calculation. See the
  335. // comment in DoConnectedRequest for a description of the request mechanism.
  336. // To ensure we don't over- or under-count unique users, only one connected
  337. // request is made across all simultaneous multi-tunnels; and the connected
  338. // request is repeated periodically for very long-lived tunnels.
  339. // The signalReportConnected mechanism is used to trigger another connected
  340. // request immediately after a reconnect.
  341. func (controller *Controller) connectedReporter() {
  342. defer controller.runWaitGroup.Done()
  343. loop:
  344. for {
  345. // Pick any active tunnel and make the next connected request. No error
  346. // is logged if there's no active tunnel, as that's not an unexpected condition.
  347. reported := false
  348. tunnel := controller.getNextActiveTunnel()
  349. if tunnel != nil {
  350. err := tunnel.serverContext.DoConnectedRequest()
  351. if err == nil {
  352. reported = true
  353. } else {
  354. NoticeAlert("failed to make connected request: %s", err)
  355. }
  356. }
  357. // Schedule the next connected request and wait.
  358. // Note: this duration is not a dynamic ClientParameter as
  359. // the daily unique user stats logic specifically requires
  360. // a "connected" request no more or less often than every
  361. // 24 hours.
  362. var duration time.Duration
  363. if reported {
  364. duration = 24 * time.Hour
  365. } else {
  366. duration = controller.config.clientParameters.Get().Duration(
  367. parameters.PsiphonAPIConnectedRequestRetryPeriod)
  368. }
  369. timer := time.NewTimer(duration)
  370. doBreak := false
  371. select {
  372. case <-controller.signalReportConnected:
  373. case <-timer.C:
  374. // Make another connected request
  375. case <-controller.runCtx.Done():
  376. doBreak = true
  377. }
  378. timer.Stop()
  379. if doBreak {
  380. break loop
  381. }
  382. }
  383. NoticeInfo("exiting connected reporter")
  384. }
  385. func (controller *Controller) startOrSignalConnectedReporter() {
  386. // session is nil when DisableApi is set
  387. if controller.config.DisableApi {
  388. return
  389. }
  390. // Start the connected reporter after the first tunnel is established.
  391. // Concurrency note: only the runTunnels goroutine may access startedConnectedReporter.
  392. if !controller.startedConnectedReporter {
  393. controller.startedConnectedReporter = true
  394. controller.runWaitGroup.Add(1)
  395. go controller.connectedReporter()
  396. } else {
  397. select {
  398. case controller.signalReportConnected <- *new(struct{}):
  399. default:
  400. }
  401. }
  402. }
  403. // upgradeDownloader makes periodic attempts to complete a client upgrade
  404. // download. DownloadUpgrade() is resumable, so each attempt has potential for
  405. // getting closer to completion, even in conditions where the download or
  406. // tunnel is repeatedly interrupted.
  407. // An upgrade download is triggered by either a handshake response indicating
  408. // that a new version is available; or after failing to connect, in which case
  409. // it's useful to check, out-of-band, for an upgrade with new circumvention
  410. // capabilities.
  411. // Once the download operation completes successfully, the downloader exits
  412. // and is not run again: either there is not a newer version, or the upgrade
  413. // has been downloaded and is ready to be applied.
  414. // We're assuming that the upgrade will be applied and the entire system
  415. // restarted before another upgrade is to be downloaded.
  416. //
  417. // TODO: refactor upgrade downloader and remote server list fetcher to use
  418. // common code (including the resumable download routines).
  419. //
  420. func (controller *Controller) upgradeDownloader() {
  421. defer controller.runWaitGroup.Done()
  422. var lastDownloadTime monotime.Time
  423. downloadLoop:
  424. for {
  425. // Wait for a signal before downloading
  426. var handshakeVersion string
  427. select {
  428. case handshakeVersion = <-controller.signalDownloadUpgrade:
  429. case <-controller.runCtx.Done():
  430. break downloadLoop
  431. }
  432. stalePeriod := controller.config.clientParameters.Get().Duration(
  433. parameters.FetchUpgradeStalePeriod)
  434. // Unless handshake is explicitly advertizing a new version, skip
  435. // checking entirely when a recent download was successful.
  436. if handshakeVersion == "" &&
  437. lastDownloadTime != 0 &&
  438. lastDownloadTime.Add(stalePeriod).After(monotime.Now()) {
  439. continue
  440. }
  441. retryLoop:
  442. for attempt := 0; ; attempt++ {
  443. // Don't attempt to download while there is no network connectivity,
  444. // to avoid alert notice noise.
  445. if !WaitForNetworkConnectivity(
  446. controller.runCtx,
  447. controller.config.NetworkConnectivityChecker) {
  448. break downloadLoop
  449. }
  450. // Pick any active tunnel and make the next download attempt. If there's
  451. // no active tunnel, the untunneledDialConfig will be used.
  452. tunnel := controller.getNextActiveTunnel()
  453. err := DownloadUpgrade(
  454. controller.runCtx,
  455. controller.config,
  456. attempt,
  457. handshakeVersion,
  458. tunnel,
  459. controller.untunneledDialConfig)
  460. if err == nil {
  461. lastDownloadTime = monotime.Now()
  462. break retryLoop
  463. }
  464. NoticeAlert("failed to download upgrade: %s", err)
  465. timeout := controller.config.clientParameters.Get().Duration(
  466. parameters.FetchUpgradeRetryPeriod)
  467. timer := time.NewTimer(timeout)
  468. select {
  469. case <-timer.C:
  470. case <-controller.runCtx.Done():
  471. timer.Stop()
  472. break downloadLoop
  473. }
  474. }
  475. }
  476. NoticeInfo("exiting upgrade downloader")
  477. }
  478. // runTunnels is the controller tunnel management main loop. It starts and stops
  479. // establishing tunnels based on the target tunnel pool size and the current size
  480. // of the pool. Tunnels are established asynchronously using worker goroutines.
  481. //
  482. // When there are no server entries for the target region/protocol, the
  483. // establishCandidateGenerator will yield no candidates and wait before
  484. // trying again. In the meantime, a remote server entry fetch may supply
  485. // valid candidates.
  486. //
  487. // When a tunnel is established, it's added to the active pool. The tunnel's
  488. // operateTunnel goroutine monitors the tunnel.
  489. //
  490. // When a tunnel fails, it's removed from the pool and the establish process is
  491. // restarted to fill the pool.
  492. func (controller *Controller) runTunnels() {
  493. defer controller.runWaitGroup.Done()
  494. // Start running
  495. controller.startEstablishing()
  496. loop:
  497. for {
  498. select {
  499. case failedTunnel := <-controller.failedTunnels:
  500. NoticeAlert("tunnel failed: %s", failedTunnel.dialParams.ServerEntry.IpAddress)
  501. controller.terminateTunnel(failedTunnel)
  502. // Clear the reference to this tunnel before calling startEstablishing,
  503. // which will invoke a garbage collection.
  504. failedTunnel = nil
  505. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing,
  506. // which reference controller.isEstablishing.
  507. controller.startEstablishing()
  508. case connectedTunnel := <-controller.connectedTunnels:
  509. // Tunnel establishment has two phases: connection and activation.
  510. //
  511. // Connection is run concurrently by the establishTunnelWorkers, to minimize
  512. // delay when it's not yet known which server and protocol will be available
  513. // and unblocked.
  514. //
  515. // Activation is run serially, here, to minimize the overhead of making a
  516. // handshake request and starting the operateTunnel management worker for a
  517. // tunnel which may be discarded.
  518. //
  519. // When the active tunnel will complete establishment, establishment is
  520. // stopped before activation. This interrupts all connecting tunnels and
  521. // garbage collects their memory. The purpose is to minimize memory
  522. // pressure when the handshake request is made. In the unlikely case that the
  523. // handshake fails, establishment is restarted.
  524. //
  525. // Any delays in stopEstablishing will delay the handshake for the last
  526. // active tunnel.
  527. //
  528. // In the typical case of TunnelPoolSize of 1, only a single handshake is
  529. // performed and the homepages notices file, when used, will not be modifed
  530. // after the NoticeTunnels(1) [i.e., connected] until NoticeTunnels(0) [i.e.,
  531. // disconnected]. For TunnelPoolSize > 1, serial handshakes only ensures that
  532. // each set of emitted NoticeHomepages is contiguous.
  533. active, outstanding := controller.numTunnels()
  534. // discardTunnel will be true here when already fully established.
  535. discardTunnel := (outstanding <= 0)
  536. isFirstTunnel := (active == 0)
  537. isLastTunnel := (outstanding == 1)
  538. if !discardTunnel {
  539. if isLastTunnel {
  540. controller.stopEstablishing()
  541. }
  542. err := connectedTunnel.Activate(controller.runCtx, controller)
  543. if err != nil {
  544. NoticeAlert("failed to activate %s: %s",
  545. connectedTunnel.dialParams.ServerEntry.IpAddress, err)
  546. discardTunnel = true
  547. } else {
  548. // It's unlikely that registerTunnel will fail, since only this goroutine
  549. // calls registerTunnel -- and after checking numTunnels; so failure is not
  550. // expected.
  551. if !controller.registerTunnel(connectedTunnel) {
  552. NoticeAlert("failed to register %s: %s",
  553. connectedTunnel.dialParams.ServerEntry.IpAddress, err)
  554. discardTunnel = true
  555. }
  556. }
  557. // May need to replace this tunnel
  558. if isLastTunnel && discardTunnel {
  559. controller.startEstablishing()
  560. }
  561. }
  562. if discardTunnel {
  563. controller.discardTunnel(connectedTunnel)
  564. // Clear the reference to this discarded tunnel and immediately run
  565. // a garbage collection to reclaim its memory.
  566. connectedTunnel = nil
  567. DoGarbageCollection()
  568. // Skip the rest of this case
  569. break
  570. }
  571. NoticeActiveTunnel(
  572. connectedTunnel.dialParams.ServerEntry.IpAddress,
  573. connectedTunnel.dialParams.TunnelProtocol,
  574. connectedTunnel.dialParams.ServerEntry.SupportsSSHAPIRequests())
  575. if isFirstTunnel {
  576. // The split tunnel classifier is started once the first tunnel is
  577. // established. This first tunnel is passed in to be used to make
  578. // the routes data request.
  579. // A long-running controller may run while the host device is present
  580. // in different regions. In this case, we want the split tunnel logic
  581. // to switch to routes for new regions and not classify traffic based
  582. // on routes installed for older regions.
  583. // We assume that when regions change, the host network will also
  584. // change, and so all tunnels will fail and be re-established. Under
  585. // that assumption, the classifier will be re-Start()-ed here when
  586. // the region has changed.
  587. controller.splitTunnelClassifier.Start(connectedTunnel)
  588. // Signal a connected request on each 1st tunnel establishment. For
  589. // multi-tunnels, the session is connected as long as at least one
  590. // tunnel is established.
  591. controller.startOrSignalConnectedReporter()
  592. // If the handshake indicated that a new client version is available,
  593. // trigger an upgrade download.
  594. // Note: serverContext is nil when DisableApi is set
  595. if connectedTunnel.serverContext != nil &&
  596. connectedTunnel.serverContext.clientUpgradeVersion != "" {
  597. handshakeVersion := connectedTunnel.serverContext.clientUpgradeVersion
  598. select {
  599. case controller.signalDownloadUpgrade <- handshakeVersion:
  600. default:
  601. }
  602. }
  603. }
  604. // Set the new tunnel as the transport for the packet tunnel. The packet tunnel
  605. // client remains up when reestablishing, but no packets are relayed while there
  606. // is no connected tunnel. UseTunnel will establish a new packet tunnel SSH
  607. // channel over the new SSH tunnel and configure the packet tunnel client to use
  608. // the new SSH channel as its transport.
  609. //
  610. // Note: as is, this logic is suboptimal for TunnelPoolSize > 1, as this would
  611. // continuously initialize new packet tunnel sessions for each established
  612. // server. For now, config validation requires TunnelPoolSize == 1 when
  613. // the packet tunnel is used.
  614. if controller.packetTunnelTransport != nil {
  615. controller.packetTunnelTransport.UseTunnel(connectedTunnel)
  616. }
  617. // TODO: design issue -- might not be enough server entries with region/caps to ever fill tunnel slots;
  618. // possible solution is establish target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  619. if controller.isFullyEstablished() {
  620. controller.stopEstablishing()
  621. }
  622. case <-controller.runCtx.Done():
  623. break loop
  624. }
  625. }
  626. // Stop running
  627. controller.stopEstablishing()
  628. controller.terminateAllTunnels()
  629. // Drain tunnel channels
  630. close(controller.connectedTunnels)
  631. for tunnel := range controller.connectedTunnels {
  632. controller.discardTunnel(tunnel)
  633. }
  634. close(controller.failedTunnels)
  635. for tunnel := range controller.failedTunnels {
  636. controller.discardTunnel(tunnel)
  637. }
  638. NoticeInfo("exiting run tunnels")
  639. }
  640. // SignalSeededNewSLOK implements the TunnelOwner interface. This function
  641. // is called by Tunnel.operateTunnel when the tunnel has received a new,
  642. // previously unknown SLOK from the server. The Controller triggers an OSL
  643. // fetch, as the new SLOK may be sufficient to access new OSLs.
  644. func (controller *Controller) SignalSeededNewSLOK() {
  645. select {
  646. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  647. default:
  648. }
  649. }
  650. // SignalTunnelFailure implements the TunnelOwner interface. This function
  651. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  652. // has failed. The Controller will signal runTunnels to create a new
  653. // tunnel and/or remove the tunnel from the list of active tunnels.
  654. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  655. // Don't block. Assumes the receiver has a buffer large enough for
  656. // the typical number of operated tunnels. In case there's no room,
  657. // terminate the tunnel (runTunnels won't get a signal in this case,
  658. // but the tunnel will be removed from the list of active tunnels).
  659. select {
  660. case controller.failedTunnels <- tunnel:
  661. default:
  662. controller.terminateTunnel(tunnel)
  663. }
  664. }
  665. // discardTunnel disposes of a successful connection that is no longer required.
  666. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  667. NoticeInfo("discard tunnel: %s", tunnel.dialParams.ServerEntry.IpAddress)
  668. // TODO: not calling PromoteServerEntry, since that would rank the
  669. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  670. // be promoted (since it connects), but with lower rank than all active
  671. // tunnels?
  672. tunnel.Close(true)
  673. }
  674. // registerTunnel adds the connected tunnel to the pool of active tunnels
  675. // which are candidates for port forwarding. Returns true if the pool has an
  676. // empty slot and false if the pool is full (caller should discard the tunnel).
  677. func (controller *Controller) registerTunnel(tunnel *Tunnel) bool {
  678. controller.tunnelMutex.Lock()
  679. defer controller.tunnelMutex.Unlock()
  680. if len(controller.tunnels) >= controller.config.TunnelPoolSize {
  681. return false
  682. }
  683. // Perform a final check just in case we've established
  684. // a duplicate connection.
  685. for _, activeTunnel := range controller.tunnels {
  686. if activeTunnel.dialParams.ServerEntry.IpAddress ==
  687. tunnel.dialParams.ServerEntry.IpAddress {
  688. NoticeAlert("duplicate tunnel: %s", tunnel.dialParams.ServerEntry.IpAddress)
  689. return false
  690. }
  691. }
  692. controller.establishedOnce = true
  693. controller.tunnels = append(controller.tunnels, tunnel)
  694. NoticeTunnels(len(controller.tunnels))
  695. // Promote this successful tunnel to first rank so it's one
  696. // of the first candidates next time establish runs.
  697. // Connecting to a TargetServerEntry does not change the
  698. // ranking.
  699. if controller.config.TargetServerEntry == "" {
  700. PromoteServerEntry(controller.config, tunnel.dialParams.ServerEntry.IpAddress)
  701. }
  702. return true
  703. }
  704. // hasEstablishedOnce indicates if at least one active tunnel has
  705. // been established up to this point. This is regardeless of how many
  706. // tunnels are presently active.
  707. func (controller *Controller) hasEstablishedOnce() bool {
  708. controller.tunnelMutex.Lock()
  709. defer controller.tunnelMutex.Unlock()
  710. return controller.establishedOnce
  711. }
  712. // isFullyEstablished indicates if the pool of active tunnels is full.
  713. func (controller *Controller) isFullyEstablished() bool {
  714. controller.tunnelMutex.Lock()
  715. defer controller.tunnelMutex.Unlock()
  716. return len(controller.tunnels) >= controller.config.TunnelPoolSize
  717. }
  718. // numTunnels returns the number of active and outstanding tunnels.
  719. // Oustanding is the number of tunnels required to fill the pool of
  720. // active tunnels.
  721. func (controller *Controller) numTunnels() (int, int) {
  722. controller.tunnelMutex.Lock()
  723. defer controller.tunnelMutex.Unlock()
  724. active := len(controller.tunnels)
  725. outstanding := controller.config.TunnelPoolSize - len(controller.tunnels)
  726. return active, outstanding
  727. }
  728. // terminateTunnel removes a tunnel from the pool of active tunnels
  729. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  730. // is adjusted as required.
  731. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  732. controller.tunnelMutex.Lock()
  733. defer controller.tunnelMutex.Unlock()
  734. for index, activeTunnel := range controller.tunnels {
  735. if tunnel == activeTunnel {
  736. controller.tunnels = append(
  737. controller.tunnels[:index], controller.tunnels[index+1:]...)
  738. if controller.nextTunnel > index {
  739. controller.nextTunnel--
  740. }
  741. if controller.nextTunnel >= len(controller.tunnels) {
  742. controller.nextTunnel = 0
  743. }
  744. activeTunnel.Close(false)
  745. NoticeTunnels(len(controller.tunnels))
  746. break
  747. }
  748. }
  749. }
  750. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  751. // This is used when shutting down the controller.
  752. func (controller *Controller) terminateAllTunnels() {
  753. controller.tunnelMutex.Lock()
  754. defer controller.tunnelMutex.Unlock()
  755. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  756. // may take a few seconds to send a final status request. We only want
  757. // to wait as long as the single slowest tunnel.
  758. closeWaitGroup := new(sync.WaitGroup)
  759. closeWaitGroup.Add(len(controller.tunnels))
  760. for _, activeTunnel := range controller.tunnels {
  761. tunnel := activeTunnel
  762. go func() {
  763. defer closeWaitGroup.Done()
  764. tunnel.Close(false)
  765. }()
  766. }
  767. closeWaitGroup.Wait()
  768. controller.tunnels = make([]*Tunnel, 0)
  769. controller.nextTunnel = 0
  770. NoticeTunnels(len(controller.tunnels))
  771. }
  772. // getNextActiveTunnel returns the next tunnel from the pool of active
  773. // tunnels. Currently, tunnel selection order is simple round-robin.
  774. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  775. controller.tunnelMutex.Lock()
  776. defer controller.tunnelMutex.Unlock()
  777. for i := len(controller.tunnels); i > 0; i-- {
  778. tunnel = controller.tunnels[controller.nextTunnel]
  779. controller.nextTunnel =
  780. (controller.nextTunnel + 1) % len(controller.tunnels)
  781. return tunnel
  782. }
  783. return nil
  784. }
  785. // isActiveTunnelServerEntry is used to check if there's already
  786. // an existing tunnel to a candidate server.
  787. func (controller *Controller) isActiveTunnelServerEntry(
  788. serverEntry *protocol.ServerEntry) bool {
  789. controller.tunnelMutex.Lock()
  790. defer controller.tunnelMutex.Unlock()
  791. for _, activeTunnel := range controller.tunnels {
  792. if activeTunnel.dialParams.ServerEntry.IpAddress == serverEntry.IpAddress {
  793. return true
  794. }
  795. }
  796. return false
  797. }
  798. // Dial selects an active tunnel and establishes a port forward
  799. // connection through the selected tunnel. Failure to connect is considered
  800. // a port forward failure, for the purpose of monitoring tunnel health.
  801. func (controller *Controller) Dial(
  802. remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error) {
  803. tunnel := controller.getNextActiveTunnel()
  804. if tunnel == nil {
  805. return nil, common.ContextError(errors.New("no active tunnels"))
  806. }
  807. // Perform split tunnel classification when feature is enabled, and if the remote
  808. // address is classified as untunneled, dial directly.
  809. if !alwaysTunnel && controller.config.SplitTunnelDNSServer != "" {
  810. host, _, err := net.SplitHostPort(remoteAddr)
  811. if err != nil {
  812. return nil, common.ContextError(err)
  813. }
  814. // Note: a possible optimization, when split tunnel is active and IsUntunneled performs
  815. // a DNS resolution in order to make its classification, is to reuse that IP address in
  816. // the following Dials so they do not need to make their own resolutions. However, the
  817. // way this is currently implemented ensures that, e.g., DNS geo load balancing occurs
  818. // relative to the outbound network.
  819. if controller.splitTunnelClassifier.IsUntunneled(host) {
  820. return controller.DirectDial(remoteAddr)
  821. }
  822. }
  823. tunneledConn, err := tunnel.Dial(remoteAddr, alwaysTunnel, downstreamConn)
  824. if err != nil {
  825. return nil, common.ContextError(err)
  826. }
  827. return tunneledConn, nil
  828. }
  829. // DirectDial dials an untunneled TCP connection within the controller run context.
  830. func (controller *Controller) DirectDial(remoteAddr string) (conn net.Conn, err error) {
  831. return DialTCP(controller.runCtx, remoteAddr, controller.untunneledDialConfig)
  832. }
  833. // triggerFetches signals RSL, OSL, and upgrade download fetchers to begin, if
  834. // not already running. triggerFetches is called when tunnel establishment
  835. // fails to complete within a deadline and in other cases where local
  836. // circumvention capabilities are lacking and we may require new server
  837. // entries or client versions with new capabilities.
  838. func (controller *Controller) triggerFetches() {
  839. // Trigger a common remote server list fetch, since we may have failed
  840. // to connect with all known servers. Don't block sending signal, since
  841. // this signal may have already been sent.
  842. // Don't wait for fetch remote to succeed, since it may fail and
  843. // enter a retry loop and we're better off trying more known servers.
  844. // TODO: synchronize the fetch response, so it can be incorporated
  845. // into the server entry iterator as soon as available.
  846. select {
  847. case controller.signalFetchCommonRemoteServerList <- *new(struct{}):
  848. default:
  849. }
  850. // Trigger an OSL fetch in parallel. Both fetches are run in parallel
  851. // so that if one out of the common RLS and OSL set is large, it doesn't
  852. // doesn't entirely block fetching the other.
  853. select {
  854. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  855. default:
  856. }
  857. // Trigger an out-of-band upgrade availability check and download.
  858. // Since we may have failed to connect, we may benefit from upgrading
  859. // to a new client version with new circumvention capabilities.
  860. select {
  861. case controller.signalDownloadUpgrade <- "":
  862. default:
  863. }
  864. }
  865. type protocolSelectionConstraints struct {
  866. useUpstreamProxy bool
  867. initialLimitProtocols protocol.TunnelProtocols
  868. initialLimitProtocolsCandidateCount int
  869. limitProtocols protocol.TunnelProtocols
  870. replayCandidateCount int
  871. }
  872. func (p *protocolSelectionConstraints) hasInitialProtocols() bool {
  873. return len(p.initialLimitProtocols) > 0 && p.initialLimitProtocolsCandidateCount > 0
  874. }
  875. func (p *protocolSelectionConstraints) isInitialCandidate(
  876. excludeIntensive bool,
  877. serverEntry *protocol.ServerEntry) bool {
  878. return p.hasInitialProtocols() &&
  879. len(serverEntry.GetSupportedProtocols(p.useUpstreamProxy, p.initialLimitProtocols, excludeIntensive)) > 0
  880. }
  881. func (p *protocolSelectionConstraints) isCandidate(
  882. excludeIntensive bool,
  883. serverEntry *protocol.ServerEntry) bool {
  884. return len(p.limitProtocols) == 0 ||
  885. len(serverEntry.GetSupportedProtocols(p.useUpstreamProxy, p.limitProtocols, excludeIntensive)) > 0
  886. }
  887. func (p *protocolSelectionConstraints) canReplay(
  888. connectTunnelCount int,
  889. excludeIntensive bool,
  890. serverEntry *protocol.ServerEntry,
  891. replayProtocol string) bool {
  892. if connectTunnelCount > p.replayCandidateCount {
  893. return false
  894. }
  895. return common.Contains(
  896. p.supportedProtocols(connectTunnelCount, excludeIntensive, serverEntry),
  897. replayProtocol)
  898. }
  899. func (p *protocolSelectionConstraints) supportedProtocols(
  900. connectTunnelCount int,
  901. excludeIntensive bool,
  902. serverEntry *protocol.ServerEntry) []string {
  903. limitProtocols := p.limitProtocols
  904. if len(p.initialLimitProtocols) > 0 && p.initialLimitProtocolsCandidateCount > connectTunnelCount {
  905. limitProtocols = p.initialLimitProtocols
  906. }
  907. return serverEntry.GetSupportedProtocols(
  908. p.useUpstreamProxy,
  909. limitProtocols,
  910. excludeIntensive)
  911. }
  912. func (p *protocolSelectionConstraints) selectProtocol(
  913. connectTunnelCount int,
  914. excludeIntensive bool,
  915. serverEntry *protocol.ServerEntry) (string, bool) {
  916. candidateProtocols := p.supportedProtocols(connectTunnelCount, excludeIntensive, serverEntry)
  917. if len(candidateProtocols) == 0 {
  918. return "", false
  919. }
  920. // Pick at random from the supported protocols. This ensures that we'll
  921. // eventually try all possible protocols. Depending on network
  922. // configuration, it may be the case that some protocol is only available
  923. // through multi-capability servers, and a simpler ranked preference of
  924. // protocols could lead to that protocol never being selected.
  925. index := prng.Intn(len(candidateProtocols))
  926. return candidateProtocols[index], true
  927. }
  928. type candidateServerEntry struct {
  929. serverEntry *protocol.ServerEntry
  930. isServerAffinityCandidate bool
  931. adjustedEstablishStartTime monotime.Time
  932. }
  933. // startEstablishing creates a pool of worker goroutines which will
  934. // attempt to establish tunnels to candidate servers. The candidates
  935. // are generated by another goroutine.
  936. func (controller *Controller) startEstablishing() {
  937. if controller.isEstablishing {
  938. return
  939. }
  940. NoticeInfo("start establishing")
  941. controller.concurrentEstablishTunnelsMutex.Lock()
  942. controller.establishConnectTunnelCount = 0
  943. controller.concurrentEstablishTunnels = 0
  944. controller.concurrentIntensiveEstablishTunnels = 0
  945. controller.peakConcurrentEstablishTunnels = 0
  946. controller.peakConcurrentIntensiveEstablishTunnels = 0
  947. controller.concurrentEstablishTunnelsMutex.Unlock()
  948. DoGarbageCollection()
  949. emitMemoryMetrics()
  950. // Note: the establish context cancelFunc, controller.stopEstablish,
  951. // is called in controller.stopEstablishing.
  952. controller.isEstablishing = true
  953. controller.establishCtx, controller.stopEstablish = context.WithCancel(controller.runCtx)
  954. controller.establishWaitGroup = new(sync.WaitGroup)
  955. controller.candidateServerEntries = make(chan *candidateServerEntry)
  956. // The server affinity mechanism attempts to favor the previously
  957. // used server when reconnecting. This is beneficial for user
  958. // applications which expect consistency in user IP address (for
  959. // example, a web site which prompts for additional user
  960. // authentication when the IP address changes).
  961. //
  962. // Only the very first server, as determined by
  963. // datastore.PromoteServerEntry(), is the server affinity candidate.
  964. // Concurrent connections attempts to many servers are launched
  965. // without delay, in case the affinity server connection fails.
  966. // While the affinity server connection is outstanding, when any
  967. // other connection is established, there is a short grace period
  968. // delay before delivering the established tunnel; this allows some
  969. // time for the affinity server connection to succeed first.
  970. // When the affinity server connection fails, any other established
  971. // tunnel is registered without delay.
  972. //
  973. // Note: the establishTunnelWorker that receives the affinity
  974. // candidate is solely resonsible for closing
  975. // controller.serverAffinityDoneBroadcast.
  976. controller.serverAffinityDoneBroadcast = make(chan struct{})
  977. controller.establishWaitGroup.Add(1)
  978. go controller.launchEstablishing()
  979. }
  980. func (controller *Controller) launchEstablishing() {
  981. defer controller.establishWaitGroup.Done()
  982. // Before starting the establish tunnel workers, get and apply
  983. // tactics, launching a tactics request if required.
  984. //
  985. // Wait only TacticsWaitPeriod for the tactics request to complete (or
  986. // fail) before proceeding with tunnel establishment, in case the tactics
  987. // request is blocked or takes very long to complete.
  988. //
  989. // An in-flight tactics request uses meek in round tripper mode, which
  990. // uses less resources than meek tunnel relay mode. For this reason, the
  991. // tactics request is not counted in concurrentIntensiveEstablishTunnels.
  992. //
  993. // TODO: HTTP/2 uses significantly more memory, so perhaps
  994. // concurrentIntensiveEstablishTunnels should be counted in that case.
  995. //
  996. // Any in-flight tactics request or pending retry will be
  997. // canceled when establishment is stopped.
  998. if !controller.config.DisableTactics {
  999. timeout := controller.config.clientParameters.Get().Duration(
  1000. parameters.TacticsWaitPeriod)
  1001. tacticsDone := make(chan struct{})
  1002. tacticsWaitPeriod := time.NewTimer(timeout)
  1003. defer tacticsWaitPeriod.Stop()
  1004. controller.establishWaitGroup.Add(1)
  1005. go controller.getTactics(tacticsDone)
  1006. select {
  1007. case <-tacticsDone:
  1008. case <-tacticsWaitPeriod.C:
  1009. }
  1010. tacticsWaitPeriod.Stop()
  1011. if controller.isStopEstablishing() {
  1012. // This check isn't strictly required by avoids the
  1013. // overhead of launching workers if establishment
  1014. // stopped while awaiting a tactics request.
  1015. return
  1016. }
  1017. }
  1018. // LimitTunnelProtocols and ConnectionWorkerPoolSize may be set by
  1019. // tactics.
  1020. // Initial- and LimitTunnelProtocols are set once per establishment, for
  1021. // consistent application of related probabilities (applied by
  1022. // ClientParametersSnapshot.TunnelProtocols). The
  1023. // establishLimitTunnelProtocolsState field must be read-only after this
  1024. // point, allowing concurrent reads by establishment workers.
  1025. p := controller.config.clientParameters.Get()
  1026. controller.protocolSelectionConstraints = &protocolSelectionConstraints{
  1027. useUpstreamProxy: controller.config.UseUpstreamProxy(),
  1028. initialLimitProtocols: p.TunnelProtocols(parameters.InitialLimitTunnelProtocols),
  1029. initialLimitProtocolsCandidateCount: p.Int(parameters.InitialLimitTunnelProtocolsCandidateCount),
  1030. limitProtocols: p.TunnelProtocols(parameters.LimitTunnelProtocols),
  1031. replayCandidateCount: p.Int(parameters.ReplayCandidateCount),
  1032. }
  1033. workerPoolSize := controller.config.clientParameters.Get().Int(
  1034. parameters.ConnectionWorkerPoolSize)
  1035. p = nil
  1036. // If InitialLimitTunnelProtocols is configured but cannot be satisfied,
  1037. // skip the initial phase in this establishment. This avoids spinning,
  1038. // unable to connect, in this case. InitialLimitTunnelProtocols is
  1039. // intended to prioritize certain protocols, but not strictly select them.
  1040. //
  1041. // The candidate count check is made with egress region selection unset.
  1042. // When an egress region is selected, it's the responsibility of the outer
  1043. // client to react to the following ReportAvailableRegions output and
  1044. // clear the user's selected region to prevent spinning, unable to
  1045. // connect. The initial phase is skipped only when
  1046. // InitialLimitTunnelProtocols cannot be satisfied _regardless_ of region
  1047. // selection.
  1048. //
  1049. // We presume that, in practise, most clients will have embedded server
  1050. // entries with capabilities for most protocols; and that clients will
  1051. // often perform RSL checks. So clients should most often have the
  1052. // necessary capabilities to satisfy InitialLimitTunnelProtocols. When
  1053. // this check fails, RSL/OSL/upgrade checks are triggered in order to gain
  1054. // new capabilities.
  1055. //
  1056. // LimitTunnelProtocols remains a hard limit, as using prohibited
  1057. // protocols may have some bad effect, such as a firewall blocking all
  1058. // traffic from a host.
  1059. if controller.protocolSelectionConstraints.initialLimitProtocolsCandidateCount > 0 {
  1060. egressRegion := "" // no egress region
  1061. initialCount, count := CountServerEntriesWithConstraints(
  1062. controller.config.UseUpstreamProxy(),
  1063. egressRegion,
  1064. controller.protocolSelectionConstraints)
  1065. if initialCount == 0 {
  1066. NoticeCandidateServers(
  1067. egressRegion,
  1068. controller.protocolSelectionConstraints,
  1069. initialCount,
  1070. count)
  1071. NoticeAlert("skipping initial limit tunnel protocols")
  1072. controller.protocolSelectionConstraints.initialLimitProtocolsCandidateCount = 0
  1073. // Since we were unable to satisfy the InitialLimitTunnelProtocols
  1074. // tactic, trigger RSL, OSL, and upgrade fetches to potentially
  1075. // gain new capabilities.
  1076. controller.triggerFetches()
  1077. }
  1078. }
  1079. // Report available egress regions. After a fresh install, the outer
  1080. // client may not have a list of regions to display; and
  1081. // LimitTunnelProtocols may reduce the number of available regions.
  1082. //
  1083. // When the outer client receives NoticeAvailableEgressRegions and the
  1084. // configured EgressRegion is not included in the region list, the outer
  1085. // client _should_ stop tunnel-core and prompt the user to change the
  1086. // region selection, as there are insufficient servers/capabilities to
  1087. // establish a tunnel in the selected region.
  1088. //
  1089. // This report is delayed until after tactics are likely to be applied;
  1090. // this avoids a ReportAvailableRegions reporting too many regions,
  1091. // followed shortly by a ReportAvailableRegions reporting fewer regions.
  1092. // That sequence could cause issues in the outer client UI.
  1093. //
  1094. // The reported regions are limited by protocolSelectionConstraints;
  1095. // in the case where an initial limit is in place, only regions available
  1096. // for the initial limit are reported. The initial phase will not complete
  1097. // if EgressRegion is set such that there are no server entries with the
  1098. // necessary protocol capabilities (either locally or from a remote server
  1099. // list fetch).
  1100. ReportAvailableRegions(
  1101. controller.config,
  1102. controller.protocolSelectionConstraints)
  1103. for i := 0; i < workerPoolSize; i++ {
  1104. controller.establishWaitGroup.Add(1)
  1105. go controller.establishTunnelWorker()
  1106. }
  1107. controller.establishWaitGroup.Add(1)
  1108. go controller.establishCandidateGenerator()
  1109. }
  1110. // stopEstablishing signals the establish goroutines to stop and waits
  1111. // for the group to halt.
  1112. func (controller *Controller) stopEstablishing() {
  1113. if !controller.isEstablishing {
  1114. return
  1115. }
  1116. NoticeInfo("stop establishing")
  1117. controller.stopEstablish()
  1118. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  1119. // (as it may be sending to that channel).
  1120. controller.establishWaitGroup.Wait()
  1121. NoticeInfo("stopped establishing")
  1122. controller.isEstablishing = false
  1123. controller.establishCtx = nil
  1124. controller.stopEstablish = nil
  1125. controller.establishWaitGroup = nil
  1126. controller.candidateServerEntries = nil
  1127. controller.serverAffinityDoneBroadcast = nil
  1128. controller.concurrentEstablishTunnelsMutex.Lock()
  1129. peakConcurrent := controller.peakConcurrentEstablishTunnels
  1130. peakConcurrentIntensive := controller.peakConcurrentIntensiveEstablishTunnels
  1131. controller.establishConnectTunnelCount = 0
  1132. controller.concurrentEstablishTunnels = 0
  1133. controller.concurrentIntensiveEstablishTunnels = 0
  1134. controller.peakConcurrentEstablishTunnels = 0
  1135. controller.peakConcurrentIntensiveEstablishTunnels = 0
  1136. controller.concurrentEstablishTunnelsMutex.Unlock()
  1137. NoticeInfo("peak concurrent establish tunnels: %d", peakConcurrent)
  1138. NoticeInfo("peak concurrent resource intensive establish tunnels: %d", peakConcurrentIntensive)
  1139. emitMemoryMetrics()
  1140. DoGarbageCollection()
  1141. }
  1142. func (controller *Controller) getTactics(done chan struct{}) {
  1143. defer controller.establishWaitGroup.Done()
  1144. defer close(done)
  1145. tacticsRecord, err := tactics.UseStoredTactics(
  1146. GetTacticsStorer(),
  1147. controller.config.GetNetworkID())
  1148. if err != nil {
  1149. NoticeAlert("get stored tactics failed: %s", err)
  1150. // The error will be due to a local datastore problem.
  1151. // While we could proceed with the tactics request, this
  1152. // could result in constant tactics requests. So, abort.
  1153. return
  1154. }
  1155. if tacticsRecord == nil {
  1156. iterator, err := NewTacticsServerEntryIterator(
  1157. controller.config)
  1158. if err != nil {
  1159. NoticeAlert("tactics iterator failed: %s", err)
  1160. return
  1161. }
  1162. defer iterator.Close()
  1163. for iteration := 0; ; iteration++ {
  1164. if !WaitForNetworkConnectivity(
  1165. controller.runCtx,
  1166. controller.config.NetworkConnectivityChecker) {
  1167. return
  1168. }
  1169. serverEntry, err := iterator.Next()
  1170. if err != nil {
  1171. NoticeAlert("tactics iterator failed: %s", err)
  1172. return
  1173. }
  1174. if serverEntry == nil {
  1175. if iteration == 0 {
  1176. NoticeAlert("tactics request skipped: no capable servers")
  1177. return
  1178. }
  1179. iterator.Reset()
  1180. continue
  1181. }
  1182. tacticsRecord, err = controller.doFetchTactics(serverEntry)
  1183. if err == nil {
  1184. break
  1185. }
  1186. NoticeAlert("tactics request failed: %s", err)
  1187. // On error, proceed with a retry, as the error is likely
  1188. // due to a network failure.
  1189. //
  1190. // TODO: distinguish network and local errors and abort
  1191. // on local errors.
  1192. p := controller.config.clientParameters.Get()
  1193. timeout := prng.JitterDuration(
  1194. p.Duration(parameters.TacticsRetryPeriod),
  1195. p.Float(parameters.TacticsRetryPeriodJitter))
  1196. p = nil
  1197. tacticsRetryDelay := time.NewTimer(timeout)
  1198. select {
  1199. case <-controller.establishCtx.Done():
  1200. return
  1201. case <-tacticsRetryDelay.C:
  1202. }
  1203. tacticsRetryDelay.Stop()
  1204. }
  1205. }
  1206. if tacticsRecord != nil &&
  1207. prng.FlipWeightedCoin(tacticsRecord.Tactics.Probability) {
  1208. err := controller.config.SetClientParameters(
  1209. tacticsRecord.Tag, true, tacticsRecord.Tactics.Parameters)
  1210. if err != nil {
  1211. NoticeAlert("apply tactics failed: %s", err)
  1212. // The error will be due to invalid tactics values from
  1213. // the server. When ApplyClientParameters fails, all
  1214. // previous tactics values are left in place. Abort
  1215. // without retry since the server is highly unlikely
  1216. // to return different values immediately.
  1217. return
  1218. }
  1219. }
  1220. // Reclaim memory from the completed tactics request as we're likely
  1221. // to be proceeding to the memory-intensive tunnel establishment phase.
  1222. DoGarbageCollection()
  1223. emitMemoryMetrics()
  1224. }
  1225. func (controller *Controller) doFetchTactics(
  1226. serverEntry *protocol.ServerEntry) (*tactics.Record, error) {
  1227. // *TODO: ...
  1228. canReplay := func(serverEntry *protocol.ServerEntry, replayProtocol string) bool {
  1229. return common.Contains(
  1230. serverEntry.GetSupportedTacticsProtocols(), replayProtocol)
  1231. }
  1232. selectProtocol := func(serverEntry *protocol.ServerEntry) (string, bool) {
  1233. tacticsProtocols := serverEntry.GetSupportedTacticsProtocols()
  1234. if len(tacticsProtocols) == 0 {
  1235. return "", false
  1236. }
  1237. index := prng.Intn(len(tacticsProtocols))
  1238. return tacticsProtocols[index], true
  1239. }
  1240. dialParams, err := MakeDialParameters(
  1241. controller.config,
  1242. canReplay,
  1243. selectProtocol,
  1244. serverEntry,
  1245. true)
  1246. if dialParams == nil {
  1247. // MakeDialParameters may return nil, nil when the server entry can't
  1248. // satisfy protocol selection criteria. This case in not expected
  1249. // since NewTacticsServerEntryIterator should only return tactics-
  1250. // capable server entries and selectProtocol will select any tactics
  1251. // protocol.
  1252. err = errors.New("failed to make dial parameters")
  1253. }
  1254. if err != nil {
  1255. return nil, common.ContextError(err)
  1256. }
  1257. NoticeRequestingTactics(dialParams)
  1258. // TacticsTimeout should be a very long timeout, since it's not
  1259. // adjusted by tactics in a new network context, and so clients
  1260. // with very slow connections must be accomodated. This long
  1261. // timeout will not entirely block the beginning of tunnel
  1262. // establishment, which beings after the shorter TacticsWaitPeriod.
  1263. //
  1264. // Using controller.establishCtx will cancel FetchTactics
  1265. // if tunnel establishment completes first.
  1266. timeout := controller.config.clientParameters.Get().Duration(
  1267. parameters.TacticsTimeout)
  1268. ctx, cancelFunc := context.WithTimeout(
  1269. controller.establishCtx,
  1270. timeout)
  1271. defer cancelFunc()
  1272. // DialMeek completes the TCP/TLS handshakes for HTTPS
  1273. // meek protocols but _not_ for HTTP meek protocols.
  1274. //
  1275. // TODO: pre-dial HTTP protocols to conform with speed
  1276. // test RTT spec.
  1277. //
  1278. // TODO: ensure that meek in round trip mode will fail
  1279. // the request when the pre-dial connection is broken,
  1280. // to minimize the possibility of network ID mismatches.
  1281. meekConn, err := DialMeek(
  1282. ctx, dialParams.GetMeekConfig(), dialParams.GetDialConfig())
  1283. if err != nil {
  1284. return nil, common.ContextError(err)
  1285. }
  1286. defer meekConn.Close()
  1287. apiParams := getBaseAPIParameters(
  1288. controller.config,
  1289. controller.sessionId,
  1290. dialParams)
  1291. tacticsRecord, err := tactics.FetchTactics(
  1292. ctx,
  1293. controller.config.clientParameters,
  1294. GetTacticsStorer(),
  1295. controller.config.GetNetworkID,
  1296. apiParams,
  1297. serverEntry.Region,
  1298. dialParams.TunnelProtocol,
  1299. serverEntry.TacticsRequestPublicKey,
  1300. serverEntry.TacticsRequestObfuscatedKey,
  1301. meekConn.RoundTrip)
  1302. if err != nil {
  1303. return nil, common.ContextError(err)
  1304. }
  1305. NoticeRequestedTactics(dialParams)
  1306. return tacticsRecord, nil
  1307. }
  1308. // establishCandidateGenerator populates the candidate queue with server entries
  1309. // from the data store. Server entries are iterated in rank order, so that promoted
  1310. // servers with higher rank are priority candidates.
  1311. func (controller *Controller) establishCandidateGenerator() {
  1312. defer controller.establishWaitGroup.Done()
  1313. defer close(controller.candidateServerEntries)
  1314. // establishStartTime is used to calculate and report the
  1315. // client's tunnel establishment duration.
  1316. //
  1317. // networkWaitDuration is the elapsed time spent waiting
  1318. // for network connectivity. This duration will be excluded
  1319. // from reported tunnel establishment duration.
  1320. establishStartTime := monotime.Now()
  1321. var totalNetworkWaitDuration time.Duration
  1322. applyServerAffinity, iterator, err := NewServerEntryIterator(controller.config)
  1323. if err != nil {
  1324. NoticeAlert("failed to iterate over candidates: %s", err)
  1325. controller.SignalComponentFailure()
  1326. return
  1327. }
  1328. defer iterator.Close()
  1329. // TODO: reconcile server affinity scheme with multi-tunnel mode
  1330. if controller.config.TunnelPoolSize > 1 {
  1331. applyServerAffinity = false
  1332. }
  1333. isServerAffinityCandidate := true
  1334. if !applyServerAffinity {
  1335. isServerAffinityCandidate = false
  1336. close(controller.serverAffinityDoneBroadcast)
  1337. }
  1338. loop:
  1339. // Repeat until stopped
  1340. for {
  1341. // For diagnostics, emits counts of the number of known server
  1342. // entries that satisfy both the egress region and tunnel protocol
  1343. // requirements (excluding excludeIntensive logic).
  1344. // Counts may change during establishment due to remote server
  1345. // list fetches, etc.
  1346. initialCount, count := CountServerEntriesWithConstraints(
  1347. controller.config.UseUpstreamProxy(),
  1348. controller.config.EgressRegion,
  1349. controller.protocolSelectionConstraints)
  1350. NoticeCandidateServers(
  1351. controller.config.EgressRegion,
  1352. controller.protocolSelectionConstraints,
  1353. initialCount,
  1354. count)
  1355. // A "round" consists of a new shuffle of the server entries
  1356. // and attempted connections up to the end of the server entry
  1357. // list, or parameters.EstablishTunnelWorkTime elapsed. Time
  1358. // spent waiting for network connectivity is excluded from
  1359. // round elapsed time.
  1360. //
  1361. // If the first round ends with no connection, remote server
  1362. // list and upgrade checks are launched.
  1363. roundStartTime := monotime.Now()
  1364. var roundNetworkWaitDuration time.Duration
  1365. // Send each iterator server entry to the establish workers
  1366. for {
  1367. networkWaitStartTime := monotime.Now()
  1368. if !WaitForNetworkConnectivity(
  1369. controller.establishCtx,
  1370. controller.config.NetworkConnectivityChecker) {
  1371. break loop
  1372. }
  1373. networkWaitDuration := monotime.Since(networkWaitStartTime)
  1374. roundNetworkWaitDuration += networkWaitDuration
  1375. totalNetworkWaitDuration += networkWaitDuration
  1376. serverEntry, err := iterator.Next()
  1377. if err != nil {
  1378. NoticeAlert("failed to get next candidate: %s", err)
  1379. controller.SignalComponentFailure()
  1380. break loop
  1381. }
  1382. if serverEntry == nil {
  1383. // Completed this iteration
  1384. break
  1385. }
  1386. if controller.config.TargetApiProtocol == protocol.PSIPHON_SSH_API_PROTOCOL &&
  1387. !serverEntry.SupportsSSHAPIRequests() {
  1388. continue
  1389. }
  1390. // adjustedEstablishStartTime is establishStartTime shifted
  1391. // to exclude time spent waiting for network connectivity.
  1392. adjustedEstablishStartTime := establishStartTime.Add(totalNetworkWaitDuration)
  1393. candidate := &candidateServerEntry{
  1394. serverEntry: serverEntry,
  1395. isServerAffinityCandidate: isServerAffinityCandidate,
  1396. adjustedEstablishStartTime: adjustedEstablishStartTime,
  1397. }
  1398. wasServerAffinityCandidate := isServerAffinityCandidate
  1399. // Note: there must be only one server affinity candidate, as it
  1400. // closes the serverAffinityDoneBroadcast channel.
  1401. isServerAffinityCandidate = false
  1402. // TODO: here we could generate multiple candidates from the
  1403. // server entry when there are many MeekFrontingAddresses.
  1404. select {
  1405. case controller.candidateServerEntries <- candidate:
  1406. case <-controller.establishCtx.Done():
  1407. break loop
  1408. }
  1409. workTime := controller.config.clientParameters.Get().Duration(
  1410. parameters.EstablishTunnelWorkTime)
  1411. if roundStartTime.Add(-roundNetworkWaitDuration).Add(workTime).Before(monotime.Now()) {
  1412. // Start over, after a brief pause, with a new shuffle of the server
  1413. // entries, and potentially some newly fetched server entries.
  1414. break
  1415. }
  1416. if wasServerAffinityCandidate {
  1417. // Don't start the next candidate until either the server affinity
  1418. // candidate has completed (success or failure) or is still working
  1419. // and the grace period has elapsed.
  1420. gracePeriod := controller.config.clientParameters.Get().Duration(
  1421. parameters.EstablishTunnelServerAffinityGracePeriod)
  1422. if gracePeriod > 0 {
  1423. timer := time.NewTimer(gracePeriod)
  1424. select {
  1425. case <-timer.C:
  1426. case <-controller.serverAffinityDoneBroadcast:
  1427. case <-controller.establishCtx.Done():
  1428. timer.Stop()
  1429. break loop
  1430. }
  1431. timer.Stop()
  1432. }
  1433. } else {
  1434. // TODO: if candidates are to be skipped, this should be done
  1435. // _before_ the stagger.
  1436. p := controller.config.clientParameters.Get()
  1437. staggerPeriod := p.Duration(parameters.StaggerConnectionWorkersPeriod)
  1438. staggerJitter := p.Float(parameters.StaggerConnectionWorkersJitter)
  1439. p = nil
  1440. if staggerPeriod != 0 {
  1441. // Stagger concurrent connection workers.
  1442. timeout := prng.JitterDuration(staggerPeriod, staggerJitter)
  1443. timer := time.NewTimer(timeout)
  1444. select {
  1445. case <-timer.C:
  1446. case <-controller.establishCtx.Done():
  1447. timer.Stop()
  1448. break loop
  1449. }
  1450. timer.Stop()
  1451. }
  1452. }
  1453. }
  1454. // Free up resources now, but don't reset until after the pause.
  1455. iterator.Close()
  1456. // Trigger RSL, OSL, and upgrade checks after failing to establish a
  1457. // tunnel in the first round.
  1458. controller.triggerFetches()
  1459. // After a complete iteration of candidate servers, pause before iterating again.
  1460. // This helps avoid some busy wait loop conditions, and also allows some time for
  1461. // network conditions to change. Also allows for fetch remote to complete,
  1462. // in typical conditions (it isn't strictly necessary to wait for this, there will
  1463. // be more rounds if required).
  1464. p := controller.config.clientParameters.Get()
  1465. timeout := prng.JitterDuration(
  1466. p.Duration(parameters.EstablishTunnelPausePeriod),
  1467. p.Float(parameters.EstablishTunnelPausePeriodJitter))
  1468. p = nil
  1469. timer := time.NewTimer(timeout)
  1470. select {
  1471. case <-timer.C:
  1472. // Retry iterating
  1473. case <-controller.establishCtx.Done():
  1474. timer.Stop()
  1475. break loop
  1476. }
  1477. timer.Stop()
  1478. iterator.Reset()
  1479. }
  1480. }
  1481. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  1482. // a connection to the tunnel server, and delivers the connected tunnel to a channel.
  1483. func (controller *Controller) establishTunnelWorker() {
  1484. defer controller.establishWaitGroup.Done()
  1485. loop:
  1486. for candidateServerEntry := range controller.candidateServerEntries {
  1487. // Note: don't receive from candidateServerEntries and isStopEstablishing
  1488. // in the same select, since we want to prioritize receiving the stop signal
  1489. if controller.isStopEstablishing() {
  1490. break loop
  1491. }
  1492. // There may already be a tunnel to this candidate. If so, skip it.
  1493. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  1494. continue
  1495. }
  1496. // Select the tunnel protocol. The selection will be made at random
  1497. // from protocols supported by the server entry, optionally limited by
  1498. // LimitTunnelProtocols.
  1499. //
  1500. // When limiting concurrent resource intensive protocol connection
  1501. // workers, and at the limit, do not select resource intensive
  1502. // protocols since otherwise the candidate must be skipped.
  1503. //
  1504. // If at the limit and unabled to select a non-intensive protocol,
  1505. // skip the candidate entirely and move on to the next. Since
  1506. // candidates are shuffled it's likely that the next candidate is not
  1507. // intensive. In this case, a StaggerConnectionWorkersMilliseconds
  1508. // delay may still be incurred.
  1509. limitIntensiveConnectionWorkers := controller.config.clientParameters.Get().Int(
  1510. parameters.LimitIntensiveConnectionWorkers)
  1511. controller.concurrentEstablishTunnelsMutex.Lock()
  1512. excludeIntensive := false
  1513. if limitIntensiveConnectionWorkers > 0 &&
  1514. controller.concurrentIntensiveEstablishTunnels >= limitIntensiveConnectionWorkers {
  1515. excludeIntensive = true
  1516. }
  1517. canReplay := func(serverEntry *protocol.ServerEntry, replayProtocol string) bool {
  1518. return controller.protocolSelectionConstraints.canReplay(
  1519. controller.establishConnectTunnelCount,
  1520. excludeIntensive,
  1521. serverEntry,
  1522. replayProtocol)
  1523. }
  1524. selectProtocol := func(serverEntry *protocol.ServerEntry) (string, bool) {
  1525. return controller.protocolSelectionConstraints.selectProtocol(
  1526. controller.establishConnectTunnelCount,
  1527. excludeIntensive,
  1528. serverEntry)
  1529. }
  1530. // MakeDialParameters may return a replay instance, if the server
  1531. // entry has a previous, recent successful connection and
  1532. // tactics/config has not changed.
  1533. //
  1534. // In the first round of establishing, ServerEntryIterator will move
  1535. // potential replay candidates to the front of the iterator after the
  1536. // random shuffle, which greatly prioritizes previously successful
  1537. // servers for that round.
  1538. //
  1539. // As ServerEntryIterator does not unmarshal and validate replay
  1540. // candidate dial parameters, some potential replay candidates may
  1541. // have expired or otherwise ineligible dial parameters; in this case
  1542. // the candidate proceeds without replay.
  1543. //
  1544. // The ReplayCandidateCount tactic determines how many candidates may
  1545. // use replay. After ReplayCandidateCount candidates on any type,
  1546. // replay or no, replay is skipped. If ReplayCandidateCount exceed the
  1547. // intial round, replay may still be performed but the iterator no
  1548. // longer moves potential replay server entries to the front.
  1549. dialParams, err := MakeDialParameters(
  1550. controller.config,
  1551. canReplay,
  1552. selectProtocol,
  1553. candidateServerEntry.serverEntry,
  1554. false)
  1555. if dialParams == nil || err != nil {
  1556. controller.concurrentEstablishTunnelsMutex.Unlock()
  1557. // dialParams is nil when the server does not support any protocol
  1558. // that remains after applying the LimitTunnelProtocols parameter
  1559. // and the excludeIntensive flag.
  1560. // Silently skip the candidate in this case. Otherwise, emit error.
  1561. if err != nil {
  1562. NoticeInfo("failed to select protocol for %s: %s",
  1563. candidateServerEntry.serverEntry.IpAddress, err)
  1564. }
  1565. // Unblock other candidates immediately when server affinity
  1566. // candidate is skipped.
  1567. if candidateServerEntry.isServerAffinityCandidate {
  1568. close(controller.serverAffinityDoneBroadcast)
  1569. }
  1570. continue
  1571. }
  1572. // Increment establishConnectTunnelCount only after selectProtocol has
  1573. // succeeded to ensure InitialLimitTunnelProtocolsCandidateCount
  1574. // candidates use InitialLimitTunnelProtocols.
  1575. controller.establishConnectTunnelCount += 1
  1576. isIntensive := protocol.TunnelProtocolIsResourceIntensive(dialParams.TunnelProtocol)
  1577. if isIntensive {
  1578. controller.concurrentIntensiveEstablishTunnels += 1
  1579. if controller.concurrentIntensiveEstablishTunnels > controller.peakConcurrentIntensiveEstablishTunnels {
  1580. controller.peakConcurrentIntensiveEstablishTunnels = controller.concurrentIntensiveEstablishTunnels
  1581. }
  1582. }
  1583. controller.concurrentEstablishTunnels += 1
  1584. if controller.concurrentEstablishTunnels > controller.peakConcurrentEstablishTunnels {
  1585. controller.peakConcurrentEstablishTunnels = controller.concurrentEstablishTunnels
  1586. }
  1587. controller.concurrentEstablishTunnelsMutex.Unlock()
  1588. // ConnectTunnel will allocate significant memory, so first attempt to
  1589. // reclaim as much as possible.
  1590. DoGarbageCollection()
  1591. tunnel, err := ConnectTunnel(
  1592. controller.establishCtx,
  1593. controller.config,
  1594. controller.sessionId,
  1595. candidateServerEntry.adjustedEstablishStartTime,
  1596. dialParams)
  1597. controller.concurrentEstablishTunnelsMutex.Lock()
  1598. if isIntensive {
  1599. controller.concurrentIntensiveEstablishTunnels -= 1
  1600. }
  1601. controller.concurrentEstablishTunnels -= 1
  1602. controller.concurrentEstablishTunnelsMutex.Unlock()
  1603. // Periodically emit memory metrics during the establishment cycle.
  1604. if !controller.isStopEstablishing() {
  1605. emitMemoryMetrics()
  1606. }
  1607. // Immediately reclaim memory allocated by the establishment. In the case
  1608. // of failure, first clear the reference to the tunnel. In the case of
  1609. // success, the garbage collection may still be effective as the initial
  1610. // phases of some protocols involve significant memory allocation that
  1611. // could now be reclaimed.
  1612. if err != nil {
  1613. tunnel = nil
  1614. }
  1615. DoGarbageCollection()
  1616. if err != nil {
  1617. // Unblock other candidates immediately when server affinity
  1618. // candidate fails.
  1619. if candidateServerEntry.isServerAffinityCandidate {
  1620. close(controller.serverAffinityDoneBroadcast)
  1621. }
  1622. // Before emitting error, check if establish interrupted, in which
  1623. // case the error is noise.
  1624. if controller.isStopEstablishing() {
  1625. break loop
  1626. }
  1627. NoticeInfo("failed to connect to %s: %s",
  1628. candidateServerEntry.serverEntry.IpAddress, err)
  1629. continue
  1630. }
  1631. // Deliver connected tunnel.
  1632. // Don't block. Assumes the receiver has a buffer large enough for
  1633. // the number of desired tunnels. If there's no room, the tunnel must
  1634. // not be required so it's discarded.
  1635. select {
  1636. case controller.connectedTunnels <- tunnel:
  1637. default:
  1638. controller.discardTunnel(tunnel)
  1639. // Clear the reference to this discarded tunnel and immediately run
  1640. // a garbage collection to reclaim its memory.
  1641. tunnel = nil
  1642. DoGarbageCollection()
  1643. }
  1644. // Unblock other candidates only after delivering when
  1645. // server affinity candidate succeeds.
  1646. if candidateServerEntry.isServerAffinityCandidate {
  1647. close(controller.serverAffinityDoneBroadcast)
  1648. }
  1649. }
  1650. }
  1651. func (controller *Controller) isStopEstablishing() bool {
  1652. select {
  1653. case <-controller.establishCtx.Done():
  1654. return true
  1655. default:
  1656. }
  1657. return false
  1658. }