controller.go 60 KB

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