controller.go 68 KB

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