controller.go 60 KB

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