controller.go 70 KB

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