controller.go 71 KB

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