controller.go 71 KB

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