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. "errors"
  27. "fmt"
  28. "math/rand"
  29. "net"
  30. "sync"
  31. "time"
  32. "github.com/Psiphon-Labs/goarista/monotime"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  39. )
  40. // Controller is a tunnel lifecycle coordinator. It manages lists of servers to
  41. // connect to; establishes and monitors tunnels; and runs local proxies which
  42. // route traffic through the tunnels.
  43. type Controller struct {
  44. config *Config
  45. runCtx context.Context
  46. stopRunning context.CancelFunc
  47. runWaitGroup *sync.WaitGroup
  48. connectedTunnels chan *Tunnel
  49. failedTunnels chan *Tunnel
  50. tunnelMutex sync.Mutex
  51. establishedOnce bool
  52. tunnels []*Tunnel
  53. nextTunnel int
  54. startedConnectedReporter bool
  55. isEstablishing bool
  56. protocolSelectionConstraints *protocolSelectionConstraints
  57. concurrentEstablishTunnelsMutex sync.Mutex
  58. establishConnectTunnelCount int
  59. concurrentEstablishTunnels int
  60. concurrentIntensiveEstablishTunnels int
  61. peakConcurrentEstablishTunnels int
  62. peakConcurrentIntensiveEstablishTunnels int
  63. establishCtx context.Context
  64. stopEstablish context.CancelFunc
  65. establishWaitGroup *sync.WaitGroup
  66. candidateServerEntries chan *candidateServerEntry
  67. untunneledDialConfig *DialConfig
  68. splitTunnelClassifier *SplitTunnelClassifier
  69. signalFetchCommonRemoteServerList chan struct{}
  70. signalFetchObfuscatedServerLists chan struct{}
  71. signalDownloadUpgrade chan string
  72. signalReportConnected chan struct{}
  73. signalRestartEstablishing chan struct{}
  74. serverAffinityDoneBroadcast chan struct{}
  75. packetTunnelClient *tun.Client
  76. packetTunnelTransport *PacketTunnelTransport
  77. staggerMutex sync.Mutex
  78. }
  79. // NewController initializes a new controller.
  80. func NewController(config *Config) (controller *Controller, err error) {
  81. if !config.IsCommitted() {
  82. return nil, common.ContextError(errors.New("uncommitted config"))
  83. }
  84. // Needed by regen, at least
  85. rand.Seed(int64(time.Now().Nanosecond()))
  86. // The session ID for the Psiphon server API is used across all
  87. // tunnels established by the controller.
  88. NoticeSessionId(config.SessionID)
  89. untunneledDialConfig := &DialConfig{
  90. UpstreamProxyURL: config.UpstreamProxyURL,
  91. CustomHeaders: config.CustomHeaders,
  92. DeviceBinder: config.deviceBinder,
  93. DnsServerGetter: config.DnsServerGetter,
  94. IPv6Synthesizer: config.IPv6Synthesizer,
  95. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  96. }
  97. controller = &Controller{
  98. config: config,
  99. runWaitGroup: new(sync.WaitGroup),
  100. // connectedTunnels and failedTunnels buffer sizes are large enough to
  101. // receive full pools of tunnels without blocking. Senders should not block.
  102. connectedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  103. failedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  104. tunnels: make([]*Tunnel, 0),
  105. establishedOnce: false,
  106. startedConnectedReporter: false,
  107. isEstablishing: false,
  108. untunneledDialConfig: untunneledDialConfig,
  109. // TODO: Add a buffer of 1 so we don't miss a signal while receiver is
  110. // starting? Trade-off is potential back-to-back fetch remotes. As-is,
  111. // establish will eventually signal another fetch remote.
  112. signalFetchCommonRemoteServerList: make(chan struct{}),
  113. signalFetchObfuscatedServerLists: make(chan struct{}),
  114. signalDownloadUpgrade: make(chan string),
  115. signalReportConnected: make(chan struct{}),
  116. // signalRestartEstablishing has a buffer of 1 to ensure sending the
  117. // signal doesn't block and receiving won't miss a signal.
  118. signalRestartEstablishing: make(chan struct{}, 1),
  119. }
  120. controller.splitTunnelClassifier = NewSplitTunnelClassifier(config, controller)
  121. if config.PacketTunnelTunFileDescriptor > 0 {
  122. // Run a packet tunnel client. The lifetime of the tun.Client is the
  123. // lifetime of the Controller, so it exists across tunnel establishments
  124. // and reestablishments. The PacketTunnelTransport provides a layer
  125. // that presents a continuosuly existing transport to the tun.Client;
  126. // it's set to use new SSH channels after new SSH tunnel establishes.
  127. packetTunnelTransport := NewPacketTunnelTransport()
  128. packetTunnelClient, err := tun.NewClient(&tun.ClientConfig{
  129. Logger: NoticeCommonLogger(),
  130. TunFileDescriptor: config.PacketTunnelTunFileDescriptor,
  131. Transport: packetTunnelTransport,
  132. })
  133. if err != nil {
  134. return nil, common.ContextError(err)
  135. }
  136. controller.packetTunnelClient = packetTunnelClient
  137. controller.packetTunnelTransport = packetTunnelTransport
  138. }
  139. return controller, nil
  140. }
  141. // Run executes the controller. Run exits if a controller
  142. // component fails or the parent context is canceled.
  143. func (controller *Controller) Run(ctx context.Context) {
  144. pprofRun()
  145. // Ensure fresh repetitive notice state for each run, so the
  146. // client will always get an AvailableEgressRegions notice,
  147. // an initial instance of any repetitive error notice, etc.
  148. ResetRepetitiveNotices()
  149. runCtx, stopRunning := context.WithCancel(ctx)
  150. defer stopRunning()
  151. controller.runCtx = runCtx
  152. controller.stopRunning = stopRunning
  153. // Start components
  154. // TODO: IPv6 support
  155. var listenIP string
  156. if controller.config.ListenInterface == "" {
  157. listenIP = "127.0.0.1"
  158. } else if controller.config.ListenInterface == "any" {
  159. listenIP = "0.0.0.0"
  160. } else {
  161. IPv4Address, _, err := common.GetInterfaceIPAddresses(controller.config.ListenInterface)
  162. if err == nil && IPv4Address == nil {
  163. err = fmt.Errorf("no IPv4 address for interface %s", controller.config.ListenInterface)
  164. }
  165. if err != nil {
  166. NoticeError("error getting listener IP: %s", err)
  167. return
  168. }
  169. listenIP = IPv4Address.String()
  170. }
  171. if !controller.config.DisableLocalSocksProxy {
  172. socksProxy, err := NewSocksProxy(controller.config, controller, listenIP)
  173. if err != nil {
  174. NoticeAlert("error initializing local SOCKS proxy: %s", err)
  175. return
  176. }
  177. defer socksProxy.Close()
  178. }
  179. if !controller.config.DisableLocalHTTPProxy {
  180. httpProxy, err := NewHttpProxy(controller.config, controller, listenIP)
  181. if err != nil {
  182. NoticeAlert("error initializing local HTTP proxy: %s", err)
  183. return
  184. }
  185. defer httpProxy.Close()
  186. }
  187. if !controller.config.DisableRemoteServerListFetcher {
  188. if controller.config.RemoteServerListURLs != nil {
  189. controller.runWaitGroup.Add(1)
  190. go controller.remoteServerListFetcher(
  191. "common",
  192. FetchCommonRemoteServerList,
  193. controller.signalFetchCommonRemoteServerList)
  194. }
  195. if controller.config.ObfuscatedServerListRootURLs != nil {
  196. controller.runWaitGroup.Add(1)
  197. go controller.remoteServerListFetcher(
  198. "obfuscated",
  199. FetchObfuscatedServerLists,
  200. controller.signalFetchObfuscatedServerLists)
  201. }
  202. }
  203. if controller.config.UpgradeDownloadURLs != nil {
  204. controller.runWaitGroup.Add(1)
  205. go controller.upgradeDownloader()
  206. }
  207. /// Note: the connected reporter isn't started until a tunnel is
  208. // established
  209. controller.runWaitGroup.Add(1)
  210. go controller.runTunnels()
  211. controller.runWaitGroup.Add(1)
  212. go controller.establishTunnelWatcher()
  213. if controller.packetTunnelClient != nil {
  214. controller.packetTunnelClient.Start()
  215. }
  216. // Wait while running
  217. <-controller.runCtx.Done()
  218. NoticeInfo("controller stopped")
  219. if controller.packetTunnelClient != nil {
  220. controller.packetTunnelClient.Stop()
  221. }
  222. // All workers -- runTunnels, establishment workers, and auxilliary
  223. // workers such as fetch remote server list and untunneled uprade
  224. // download -- operate with the controller run context and will all
  225. // be interrupted when the run context is done.
  226. controller.runWaitGroup.Wait()
  227. controller.splitTunnelClassifier.Shutdown()
  228. NoticeInfo("exiting controller")
  229. NoticeExiting()
  230. }
  231. // SignalComponentFailure notifies the controller that an associated component has failed.
  232. // This will terminate the controller.
  233. func (controller *Controller) SignalComponentFailure() {
  234. NoticeAlert("controller shutdown due to component failure")
  235. controller.stopRunning()
  236. }
  237. // SetDynamicConfig overrides the sponsor ID and authorizations fields of the
  238. // Controller config with the input values. The new values will be used in the
  239. // next tunnel connection.
  240. func (controller *Controller) SetDynamicConfig(sponsorID string, authorizations []string) {
  241. controller.config.SetDynamicConfig(sponsorID, authorizations)
  242. }
  243. // TerminateNextActiveTunnel terminates the active tunnel, which will initiate
  244. // establishment of a new tunnel.
  245. func (controller *Controller) TerminateNextActiveTunnel() {
  246. tunnel := controller.getNextActiveTunnel()
  247. if tunnel != nil {
  248. controller.SignalTunnelFailure(tunnel)
  249. NoticeInfo("terminated tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  250. }
  251. }
  252. // ExportExchangePayload creates a payload for client-to-client server
  253. // connection info exchange. See the comment for psiphon.ExportExchangePayload
  254. // for more details.
  255. func (controller *Controller) ExportExchangePayload() string {
  256. return ExportExchangePayload(controller.config)
  257. }
  258. // ImportExchangePayload imports a payload generated by ExportExchangePayload.
  259. // See the comment for psiphon.ImportExchangePayload for more details about
  260. // the import.
  261. //
  262. // When the import is successful, a signal is set to trigger a restart any
  263. // establishment in progress. This will cause the newly imported server entry
  264. // to be prioritized, which it otherwise would not be in later establishment
  265. // rounds. The establishment process continues after ImportExchangePayload
  266. // returns.
  267. //
  268. // If the client already has a connected tunnel, or a tunnel connection is
  269. // established concurrently with the import, the signal has no effect as the
  270. // overall goal is establish _any_ connection.
  271. func (controller *Controller) ImportExchangePayload(payload string) bool {
  272. // Race condition: if a new tunnel connection is established concurrently
  273. // with the import, either that tunnel's server entry of the imported server
  274. // entry may end up as the affinity server.
  275. ok := ImportExchangePayload(controller.config, payload)
  276. if !ok {
  277. return false
  278. }
  279. select {
  280. case controller.signalRestartEstablishing <- *new(struct{}):
  281. default:
  282. }
  283. return true
  284. }
  285. // remoteServerListFetcher fetches an out-of-band list of server entries
  286. // for more tunnel candidates. It fetches when signalled, with retries
  287. // on failure.
  288. func (controller *Controller) remoteServerListFetcher(
  289. name string,
  290. fetcher RemoteServerListFetcher,
  291. signal <-chan struct{}) {
  292. defer controller.runWaitGroup.Done()
  293. var lastFetchTime monotime.Time
  294. fetcherLoop:
  295. for {
  296. // Wait for a signal before fetching
  297. select {
  298. case <-signal:
  299. case <-controller.runCtx.Done():
  300. break fetcherLoop
  301. }
  302. // Skip fetch entirely (i.e., send no request at all, even when ETag would save
  303. // on response size) when a recent fetch was successful
  304. stalePeriod := controller.config.GetClientParametersSnapshot().Duration(
  305. parameters.FetchRemoteServerListStalePeriod)
  306. if lastFetchTime != 0 &&
  307. lastFetchTime.Add(stalePeriod).After(monotime.Now()) {
  308. continue
  309. }
  310. retryLoop:
  311. for attempt := 0; ; attempt++ {
  312. // Don't attempt to fetch while there is no network connectivity,
  313. // to avoid alert notice noise.
  314. if !WaitForNetworkConnectivity(
  315. controller.runCtx,
  316. controller.config.NetworkConnectivityChecker) {
  317. break fetcherLoop
  318. }
  319. // Pick any active tunnel and make the next fetch attempt. If there's
  320. // no active tunnel, the untunneledDialConfig will be used.
  321. tunnel := controller.getNextActiveTunnel()
  322. err := fetcher(
  323. controller.runCtx,
  324. controller.config,
  325. attempt,
  326. tunnel,
  327. controller.untunneledDialConfig)
  328. if err == nil {
  329. lastFetchTime = monotime.Now()
  330. break retryLoop
  331. }
  332. NoticeAlert("failed to fetch %s remote server list: %s", name, err)
  333. retryPeriod := controller.config.GetClientParametersSnapshot().Duration(
  334. parameters.FetchRemoteServerListRetryPeriod)
  335. timer := time.NewTimer(retryPeriod)
  336. select {
  337. case <-timer.C:
  338. case <-controller.runCtx.Done():
  339. timer.Stop()
  340. break fetcherLoop
  341. }
  342. }
  343. }
  344. NoticeInfo("exiting %s remote server list fetcher", name)
  345. }
  346. // establishTunnelWatcher terminates the controller if a tunnel
  347. // has not been established in the configured time period. This
  348. // is regardless of how many tunnels are presently active -- meaning
  349. // that if an active tunnel was established and lost the controller
  350. // is left running (to re-establish).
  351. func (controller *Controller) establishTunnelWatcher() {
  352. defer controller.runWaitGroup.Done()
  353. timeout := controller.config.GetClientParametersSnapshot().Duration(
  354. parameters.EstablishTunnelTimeout)
  355. if timeout > 0 {
  356. timer := time.NewTimer(timeout)
  357. defer timer.Stop()
  358. select {
  359. case <-timer.C:
  360. if !controller.hasEstablishedOnce() {
  361. NoticeEstablishTunnelTimeout(timeout)
  362. controller.SignalComponentFailure()
  363. }
  364. case <-controller.runCtx.Done():
  365. }
  366. }
  367. NoticeInfo("exiting establish tunnel watcher")
  368. }
  369. // connectedReporter sends periodic "connected" requests to the Psiphon API.
  370. // These requests are for server-side unique user stats calculation. See the
  371. // comment in DoConnectedRequest for a description of the request mechanism.
  372. // To ensure we don't over- or under-count unique users, only one connected
  373. // request is made across all simultaneous multi-tunnels; and the connected
  374. // request is repeated periodically for very long-lived tunnels.
  375. // The signalReportConnected mechanism is used to trigger another connected
  376. // request immediately after a reconnect.
  377. func (controller *Controller) connectedReporter() {
  378. defer controller.runWaitGroup.Done()
  379. loop:
  380. for {
  381. // Pick any active tunnel and make the next connected request. No error
  382. // is logged if there's no active tunnel, as that's not an unexpected condition.
  383. reported := false
  384. tunnel := controller.getNextActiveTunnel()
  385. if tunnel != nil {
  386. err := tunnel.serverContext.DoConnectedRequest()
  387. if err == nil {
  388. reported = true
  389. } else {
  390. NoticeAlert("failed to make connected request: %s", err)
  391. }
  392. }
  393. // Schedule the next connected request and wait.
  394. // Note: this duration is not a dynamic ClientParameter as
  395. // the daily unique user stats logic specifically requires
  396. // a "connected" request no more or less often than every
  397. // 24 hours.
  398. var duration time.Duration
  399. if reported {
  400. duration = 24 * time.Hour
  401. } else {
  402. duration = controller.config.GetClientParametersSnapshot().Duration(
  403. parameters.PsiphonAPIConnectedRequestRetryPeriod)
  404. }
  405. timer := time.NewTimer(duration)
  406. doBreak := false
  407. select {
  408. case <-controller.signalReportConnected:
  409. case <-timer.C:
  410. // Make another connected request
  411. case <-controller.runCtx.Done():
  412. doBreak = true
  413. }
  414. timer.Stop()
  415. if doBreak {
  416. break loop
  417. }
  418. }
  419. NoticeInfo("exiting connected reporter")
  420. }
  421. func (controller *Controller) startOrSignalConnectedReporter() {
  422. // session is nil when DisableApi is set
  423. if controller.config.DisableApi {
  424. return
  425. }
  426. // Start the connected reporter after the first tunnel is established.
  427. // Concurrency note: only the runTunnels goroutine may access startedConnectedReporter.
  428. if !controller.startedConnectedReporter {
  429. controller.startedConnectedReporter = true
  430. controller.runWaitGroup.Add(1)
  431. go controller.connectedReporter()
  432. } else {
  433. select {
  434. case controller.signalReportConnected <- *new(struct{}):
  435. default:
  436. }
  437. }
  438. }
  439. // upgradeDownloader makes periodic attempts to complete a client upgrade
  440. // download. DownloadUpgrade() is resumable, so each attempt has potential for
  441. // getting closer to completion, even in conditions where the download or
  442. // tunnel is repeatedly interrupted.
  443. // An upgrade download is triggered by either a handshake response indicating
  444. // that a new version is available; or after failing to connect, in which case
  445. // it's useful to check, out-of-band, for an upgrade with new circumvention
  446. // capabilities.
  447. // Once the download operation completes successfully, the downloader exits
  448. // and is not run again: either there is not a newer version, or the upgrade
  449. // has been downloaded and is ready to be applied.
  450. // We're assuming that the upgrade will be applied and the entire system
  451. // restarted before another upgrade is to be downloaded.
  452. //
  453. // TODO: refactor upgrade downloader and remote server list fetcher to use
  454. // common code (including the resumable download routines).
  455. //
  456. func (controller *Controller) upgradeDownloader() {
  457. defer controller.runWaitGroup.Done()
  458. var lastDownloadTime monotime.Time
  459. downloadLoop:
  460. for {
  461. // Wait for a signal before downloading
  462. var handshakeVersion string
  463. select {
  464. case handshakeVersion = <-controller.signalDownloadUpgrade:
  465. case <-controller.runCtx.Done():
  466. break downloadLoop
  467. }
  468. stalePeriod := controller.config.GetClientParametersSnapshot().Duration(
  469. parameters.FetchUpgradeStalePeriod)
  470. // Unless handshake is explicitly advertizing a new version, skip
  471. // checking entirely when a recent download was successful.
  472. if handshakeVersion == "" &&
  473. lastDownloadTime != 0 &&
  474. lastDownloadTime.Add(stalePeriod).After(monotime.Now()) {
  475. continue
  476. }
  477. retryLoop:
  478. for attempt := 0; ; attempt++ {
  479. // Don't attempt to download while there is no network connectivity,
  480. // to avoid alert notice noise.
  481. if !WaitForNetworkConnectivity(
  482. controller.runCtx,
  483. controller.config.NetworkConnectivityChecker) {
  484. break downloadLoop
  485. }
  486. // Pick any active tunnel and make the next download attempt. If there's
  487. // no active tunnel, the untunneledDialConfig will be used.
  488. tunnel := controller.getNextActiveTunnel()
  489. err := DownloadUpgrade(
  490. controller.runCtx,
  491. controller.config,
  492. attempt,
  493. handshakeVersion,
  494. tunnel,
  495. controller.untunneledDialConfig)
  496. if err == nil {
  497. lastDownloadTime = monotime.Now()
  498. break retryLoop
  499. }
  500. NoticeAlert("failed to download upgrade: %s", err)
  501. timeout := controller.config.GetClientParametersSnapshot().Duration(
  502. parameters.FetchUpgradeRetryPeriod)
  503. timer := time.NewTimer(timeout)
  504. select {
  505. case <-timer.C:
  506. case <-controller.runCtx.Done():
  507. timer.Stop()
  508. break downloadLoop
  509. }
  510. }
  511. }
  512. NoticeInfo("exiting upgrade downloader")
  513. }
  514. // runTunnels is the controller tunnel management main loop. It starts and stops
  515. // establishing tunnels based on the target tunnel pool size and the current size
  516. // of the pool. Tunnels are established asynchronously using worker goroutines.
  517. //
  518. // When there are no server entries for the target region/protocol, the
  519. // establishCandidateGenerator will yield no candidates and wait before
  520. // trying again. In the meantime, a remote server entry fetch may supply
  521. // valid candidates.
  522. //
  523. // When a tunnel is established, it's added to the active pool. The tunnel's
  524. // operateTunnel goroutine monitors the tunnel.
  525. //
  526. // When a tunnel fails, it's removed from the pool and the establish process is
  527. // restarted to fill the pool.
  528. func (controller *Controller) runTunnels() {
  529. defer controller.runWaitGroup.Done()
  530. // Start running
  531. controller.startEstablishing()
  532. loop:
  533. for {
  534. select {
  535. case <-controller.signalRestartEstablishing:
  536. // signalRestartEstablishing restarts any establishment in progress. One
  537. // use case for this is to prioritize a newly imported, exchanged server
  538. // entry, which will be in the affinity position.
  539. //
  540. // It's possible for another connection to establish concurrent to signalling;
  541. // since the overall goal remains to establish _any_ connection, we accept that
  542. // in some cases the exchanged server entry may not get used.
  543. if controller.isEstablishing {
  544. controller.stopEstablishing()
  545. controller.startEstablishing()
  546. }
  547. case failedTunnel := <-controller.failedTunnels:
  548. NoticeAlert("tunnel failed: %s", failedTunnel.dialParams.ServerEntry.GetDiagnosticID())
  549. controller.terminateTunnel(failedTunnel)
  550. // Clear the reference to this tunnel before calling startEstablishing,
  551. // which will invoke a garbage collection.
  552. failedTunnel = nil
  553. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing,
  554. // which reference controller.isEstablishing.
  555. controller.startEstablishing()
  556. case connectedTunnel := <-controller.connectedTunnels:
  557. // Tunnel establishment has two phases: connection and activation.
  558. //
  559. // Connection is run concurrently by the establishTunnelWorkers, to minimize
  560. // delay when it's not yet known which server and protocol will be available
  561. // and unblocked.
  562. //
  563. // Activation is run serially, here, to minimize the overhead of making a
  564. // handshake request and starting the operateTunnel management worker for a
  565. // tunnel which may be discarded.
  566. //
  567. // When the active tunnel will complete establishment, establishment is
  568. // stopped before activation. This interrupts all connecting tunnels and
  569. // garbage collects their memory. The purpose is to minimize memory
  570. // pressure when the handshake request is made. In the unlikely case that the
  571. // handshake fails, establishment is restarted.
  572. //
  573. // Any delays in stopEstablishing will delay the handshake for the last
  574. // active tunnel.
  575. //
  576. // In the typical case of TunnelPoolSize of 1, only a single handshake is
  577. // performed and the homepages notices file, when used, will not be modifed
  578. // after the NoticeTunnels(1) [i.e., connected] until NoticeTunnels(0) [i.e.,
  579. // disconnected]. For TunnelPoolSize > 1, serial handshakes only ensures that
  580. // each set of emitted NoticeHomepages is contiguous.
  581. active, outstanding := controller.numTunnels()
  582. // discardTunnel will be true here when already fully established.
  583. discardTunnel := (outstanding <= 0)
  584. isFirstTunnel := (active == 0)
  585. isLastTunnel := (outstanding == 1)
  586. if !discardTunnel {
  587. if isLastTunnel {
  588. controller.stopEstablishing()
  589. }
  590. err := connectedTunnel.Activate(controller.runCtx, controller)
  591. if err != nil {
  592. NoticeAlert("failed to activate %s: %s",
  593. connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(), err)
  594. discardTunnel = true
  595. } else {
  596. // It's unlikely that registerTunnel will fail, since only this goroutine
  597. // calls registerTunnel -- and after checking numTunnels; so failure is not
  598. // expected.
  599. if !controller.registerTunnel(connectedTunnel) {
  600. NoticeAlert("failed to register %s: %s",
  601. connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(), err)
  602. discardTunnel = true
  603. }
  604. }
  605. // May need to replace this tunnel
  606. if isLastTunnel && discardTunnel {
  607. controller.startEstablishing()
  608. }
  609. }
  610. if discardTunnel {
  611. controller.discardTunnel(connectedTunnel)
  612. // Clear the reference to this discarded tunnel and immediately run
  613. // a garbage collection to reclaim its memory.
  614. connectedTunnel = nil
  615. DoGarbageCollection()
  616. // Skip the rest of this case
  617. break
  618. }
  619. NoticeActiveTunnel(
  620. connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(),
  621. connectedTunnel.dialParams.TunnelProtocol,
  622. connectedTunnel.dialParams.ServerEntry.SupportsSSHAPIRequests())
  623. if isFirstTunnel {
  624. // The split tunnel classifier is started once the first tunnel is
  625. // established. This first tunnel is passed in to be used to make
  626. // the routes data request.
  627. // A long-running controller may run while the host device is present
  628. // in different regions. In this case, we want the split tunnel logic
  629. // to switch to routes for new regions and not classify traffic based
  630. // on routes installed for older regions.
  631. // We assume that when regions change, the host network will also
  632. // change, and so all tunnels will fail and be re-established. Under
  633. // that assumption, the classifier will be re-Start()-ed here when
  634. // the region has changed.
  635. controller.splitTunnelClassifier.Start(connectedTunnel)
  636. // Signal a connected request on each 1st tunnel establishment. For
  637. // multi-tunnels, the session is connected as long as at least one
  638. // tunnel is established.
  639. controller.startOrSignalConnectedReporter()
  640. // If the handshake indicated that a new client version is available,
  641. // trigger an upgrade download.
  642. // Note: serverContext is nil when DisableApi is set
  643. if connectedTunnel.serverContext != nil &&
  644. connectedTunnel.serverContext.clientUpgradeVersion != "" {
  645. handshakeVersion := connectedTunnel.serverContext.clientUpgradeVersion
  646. select {
  647. case controller.signalDownloadUpgrade <- handshakeVersion:
  648. default:
  649. }
  650. }
  651. }
  652. // Set the new tunnel as the transport for the packet tunnel. The packet tunnel
  653. // client remains up when reestablishing, but no packets are relayed while there
  654. // is no connected tunnel. UseTunnel will establish a new packet tunnel SSH
  655. // channel over the new SSH tunnel and configure the packet tunnel client to use
  656. // the new SSH channel as its transport.
  657. //
  658. // Note: as is, this logic is suboptimal for TunnelPoolSize > 1, as this would
  659. // continuously initialize new packet tunnel sessions for each established
  660. // server. For now, config validation requires TunnelPoolSize == 1 when
  661. // the packet tunnel is used.
  662. if controller.packetTunnelTransport != nil {
  663. controller.packetTunnelTransport.UseTunnel(connectedTunnel)
  664. }
  665. // TODO: design issue -- might not be enough server entries with region/caps to ever fill tunnel slots;
  666. // possible solution is establish target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  667. if controller.isFullyEstablished() {
  668. controller.stopEstablishing()
  669. }
  670. case <-controller.runCtx.Done():
  671. break loop
  672. }
  673. }
  674. // Stop running
  675. controller.stopEstablishing()
  676. controller.terminateAllTunnels()
  677. // Drain tunnel channels
  678. close(controller.connectedTunnels)
  679. for tunnel := range controller.connectedTunnels {
  680. controller.discardTunnel(tunnel)
  681. }
  682. close(controller.failedTunnels)
  683. for tunnel := range controller.failedTunnels {
  684. controller.discardTunnel(tunnel)
  685. }
  686. NoticeInfo("exiting run tunnels")
  687. }
  688. // SignalSeededNewSLOK implements the TunnelOwner interface. This function
  689. // is called by Tunnel.operateTunnel when the tunnel has received a new,
  690. // previously unknown SLOK from the server. The Controller triggers an OSL
  691. // fetch, as the new SLOK may be sufficient to access new OSLs.
  692. func (controller *Controller) SignalSeededNewSLOK() {
  693. select {
  694. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  695. default:
  696. }
  697. }
  698. // SignalTunnelFailure implements the TunnelOwner interface. This function
  699. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  700. // has failed. The Controller will signal runTunnels to create a new
  701. // tunnel and/or remove the tunnel from the list of active tunnels.
  702. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  703. // Don't block. Assumes the receiver has a buffer large enough for
  704. // the typical number of operated tunnels. In case there's no room,
  705. // terminate the tunnel (runTunnels won't get a signal in this case,
  706. // but the tunnel will be removed from the list of active tunnels).
  707. select {
  708. case controller.failedTunnels <- tunnel:
  709. default:
  710. controller.terminateTunnel(tunnel)
  711. }
  712. }
  713. // discardTunnel disposes of a successful connection that is no longer required.
  714. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  715. NoticeInfo("discard tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  716. // TODO: not calling PromoteServerEntry, since that would rank the
  717. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  718. // be promoted (since it connects), but with lower rank than all active
  719. // tunnels?
  720. tunnel.Close(true)
  721. }
  722. // registerTunnel adds the connected tunnel to the pool of active tunnels
  723. // which are candidates for port forwarding. Returns true if the pool has an
  724. // empty slot and false if the pool is full (caller should discard the tunnel).
  725. func (controller *Controller) registerTunnel(tunnel *Tunnel) bool {
  726. controller.tunnelMutex.Lock()
  727. defer controller.tunnelMutex.Unlock()
  728. if len(controller.tunnels) >= controller.config.TunnelPoolSize {
  729. return false
  730. }
  731. // Perform a final check just in case we've established
  732. // a duplicate connection.
  733. for _, activeTunnel := range controller.tunnels {
  734. if activeTunnel.dialParams.ServerEntry.IpAddress ==
  735. tunnel.dialParams.ServerEntry.IpAddress {
  736. NoticeAlert("duplicate tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  737. return false
  738. }
  739. }
  740. controller.establishedOnce = true
  741. controller.tunnels = append(controller.tunnels, tunnel)
  742. NoticeTunnels(len(controller.tunnels))
  743. // Promote this successful tunnel to first rank so it's one
  744. // of the first candidates next time establish runs.
  745. // Connecting to a TargetServerEntry does not change the
  746. // ranking.
  747. if controller.config.TargetServerEntry == "" {
  748. PromoteServerEntry(controller.config, tunnel.dialParams.ServerEntry.IpAddress)
  749. }
  750. return true
  751. }
  752. // hasEstablishedOnce indicates if at least one active tunnel has
  753. // been established up to this point. This is regardeless of how many
  754. // tunnels are presently active.
  755. func (controller *Controller) hasEstablishedOnce() bool {
  756. controller.tunnelMutex.Lock()
  757. defer controller.tunnelMutex.Unlock()
  758. return controller.establishedOnce
  759. }
  760. // isFullyEstablished indicates if the pool of active tunnels is full.
  761. func (controller *Controller) isFullyEstablished() bool {
  762. controller.tunnelMutex.Lock()
  763. defer controller.tunnelMutex.Unlock()
  764. return len(controller.tunnels) >= controller.config.TunnelPoolSize
  765. }
  766. // numTunnels returns the number of active and outstanding tunnels.
  767. // Oustanding is the number of tunnels required to fill the pool of
  768. // active tunnels.
  769. func (controller *Controller) numTunnels() (int, int) {
  770. controller.tunnelMutex.Lock()
  771. defer controller.tunnelMutex.Unlock()
  772. active := len(controller.tunnels)
  773. outstanding := controller.config.TunnelPoolSize - len(controller.tunnels)
  774. return active, outstanding
  775. }
  776. // terminateTunnel removes a tunnel from the pool of active tunnels
  777. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  778. // is adjusted as required.
  779. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  780. controller.tunnelMutex.Lock()
  781. defer controller.tunnelMutex.Unlock()
  782. for index, activeTunnel := range controller.tunnels {
  783. if tunnel == activeTunnel {
  784. controller.tunnels = append(
  785. controller.tunnels[:index], controller.tunnels[index+1:]...)
  786. if controller.nextTunnel > index {
  787. controller.nextTunnel--
  788. }
  789. if controller.nextTunnel >= len(controller.tunnels) {
  790. controller.nextTunnel = 0
  791. }
  792. activeTunnel.Close(false)
  793. NoticeTunnels(len(controller.tunnels))
  794. break
  795. }
  796. }
  797. }
  798. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  799. // This is used when shutting down the controller.
  800. func (controller *Controller) terminateAllTunnels() {
  801. controller.tunnelMutex.Lock()
  802. defer controller.tunnelMutex.Unlock()
  803. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  804. // may take a few seconds to send a final status request. We only want
  805. // to wait as long as the single slowest tunnel.
  806. closeWaitGroup := new(sync.WaitGroup)
  807. closeWaitGroup.Add(len(controller.tunnels))
  808. for _, activeTunnel := range controller.tunnels {
  809. tunnel := activeTunnel
  810. go func() {
  811. defer closeWaitGroup.Done()
  812. tunnel.Close(false)
  813. }()
  814. }
  815. closeWaitGroup.Wait()
  816. controller.tunnels = make([]*Tunnel, 0)
  817. controller.nextTunnel = 0
  818. NoticeTunnels(len(controller.tunnels))
  819. }
  820. // getNextActiveTunnel returns the next tunnel from the pool of active
  821. // tunnels. Currently, tunnel selection order is simple round-robin.
  822. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  823. controller.tunnelMutex.Lock()
  824. defer controller.tunnelMutex.Unlock()
  825. for i := len(controller.tunnels); i > 0; i-- {
  826. tunnel = controller.tunnels[controller.nextTunnel]
  827. controller.nextTunnel =
  828. (controller.nextTunnel + 1) % len(controller.tunnels)
  829. return tunnel
  830. }
  831. return nil
  832. }
  833. // isActiveTunnelServerEntry is used to check if there's already
  834. // an existing tunnel to a candidate server.
  835. func (controller *Controller) isActiveTunnelServerEntry(
  836. serverEntry *protocol.ServerEntry) bool {
  837. controller.tunnelMutex.Lock()
  838. defer controller.tunnelMutex.Unlock()
  839. for _, activeTunnel := range controller.tunnels {
  840. if activeTunnel.dialParams.ServerEntry.IpAddress == serverEntry.IpAddress {
  841. return true
  842. }
  843. }
  844. return false
  845. }
  846. // Dial selects an active tunnel and establishes a port forward
  847. // connection through the selected tunnel. Failure to connect is considered
  848. // a port forward failure, for the purpose of monitoring tunnel health.
  849. func (controller *Controller) Dial(
  850. remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error) {
  851. tunnel := controller.getNextActiveTunnel()
  852. if tunnel == nil {
  853. return nil, common.ContextError(errors.New("no active tunnels"))
  854. }
  855. // Perform split tunnel classification when feature is enabled, and if the remote
  856. // address is classified as untunneled, dial directly.
  857. if !alwaysTunnel && controller.config.SplitTunnelDNSServer != "" {
  858. host, _, err := net.SplitHostPort(remoteAddr)
  859. if err != nil {
  860. return nil, common.ContextError(err)
  861. }
  862. // Note: a possible optimization, when split tunnel is active and IsUntunneled performs
  863. // a DNS resolution in order to make its classification, is to reuse that IP address in
  864. // the following Dials so they do not need to make their own resolutions. However, the
  865. // way this is currently implemented ensures that, e.g., DNS geo load balancing occurs
  866. // relative to the outbound network.
  867. if controller.splitTunnelClassifier.IsUntunneled(host) {
  868. return controller.DirectDial(remoteAddr)
  869. }
  870. }
  871. tunneledConn, err := tunnel.Dial(remoteAddr, alwaysTunnel, downstreamConn)
  872. if err != nil {
  873. return nil, common.ContextError(err)
  874. }
  875. return tunneledConn, nil
  876. }
  877. // DirectDial dials an untunneled TCP connection within the controller run context.
  878. func (controller *Controller) DirectDial(remoteAddr string) (conn net.Conn, err error) {
  879. return DialTCP(controller.runCtx, remoteAddr, controller.untunneledDialConfig)
  880. }
  881. // triggerFetches signals RSL, OSL, and upgrade download fetchers to begin, if
  882. // not already running. triggerFetches is called when tunnel establishment
  883. // fails to complete within a deadline and in other cases where local
  884. // circumvention capabilities are lacking and we may require new server
  885. // entries or client versions with new capabilities.
  886. func (controller *Controller) triggerFetches() {
  887. // Trigger a common remote server list fetch, since we may have failed
  888. // to connect with all known servers. Don't block sending signal, since
  889. // this signal may have already been sent.
  890. // Don't wait for fetch remote to succeed, since it may fail and
  891. // enter a retry loop and we're better off trying more known servers.
  892. // TODO: synchronize the fetch response, so it can be incorporated
  893. // into the server entry iterator as soon as available.
  894. select {
  895. case controller.signalFetchCommonRemoteServerList <- *new(struct{}):
  896. default:
  897. }
  898. // Trigger an OSL fetch in parallel. Both fetches are run in parallel
  899. // so that if one out of the common RLS and OSL set is large, it doesn't
  900. // doesn't entirely block fetching the other.
  901. select {
  902. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  903. default:
  904. }
  905. // Trigger an out-of-band upgrade availability check and download.
  906. // Since we may have failed to connect, we may benefit from upgrading
  907. // to a new client version with new circumvention capabilities.
  908. select {
  909. case controller.signalDownloadUpgrade <- "":
  910. default:
  911. }
  912. }
  913. type protocolSelectionConstraints struct {
  914. useUpstreamProxy bool
  915. initialLimitProtocols protocol.TunnelProtocols
  916. initialLimitProtocolsCandidateCount int
  917. limitProtocols protocol.TunnelProtocols
  918. replayCandidateCount int
  919. }
  920. func (p *protocolSelectionConstraints) hasInitialProtocols() bool {
  921. return len(p.initialLimitProtocols) > 0 && p.initialLimitProtocolsCandidateCount > 0
  922. }
  923. func (p *protocolSelectionConstraints) isInitialCandidate(
  924. excludeIntensive bool,
  925. serverEntry *protocol.ServerEntry) bool {
  926. return p.hasInitialProtocols() &&
  927. len(serverEntry.GetSupportedProtocols(p.useUpstreamProxy, p.initialLimitProtocols, excludeIntensive)) > 0
  928. }
  929. func (p *protocolSelectionConstraints) isCandidate(
  930. excludeIntensive bool,
  931. serverEntry *protocol.ServerEntry) bool {
  932. return len(p.limitProtocols) == 0 ||
  933. len(serverEntry.GetSupportedProtocols(p.useUpstreamProxy, p.limitProtocols, excludeIntensive)) > 0
  934. }
  935. func (p *protocolSelectionConstraints) canReplay(
  936. connectTunnelCount int,
  937. excludeIntensive bool,
  938. serverEntry *protocol.ServerEntry,
  939. replayProtocol string) bool {
  940. if p.replayCandidateCount != -1 && connectTunnelCount > p.replayCandidateCount {
  941. return false
  942. }
  943. return common.Contains(
  944. p.supportedProtocols(connectTunnelCount, excludeIntensive, serverEntry),
  945. replayProtocol)
  946. }
  947. func (p *protocolSelectionConstraints) supportedProtocols(
  948. connectTunnelCount int,
  949. excludeIntensive bool,
  950. serverEntry *protocol.ServerEntry) []string {
  951. limitProtocols := p.limitProtocols
  952. if len(p.initialLimitProtocols) > 0 && p.initialLimitProtocolsCandidateCount > connectTunnelCount {
  953. limitProtocols = p.initialLimitProtocols
  954. }
  955. return serverEntry.GetSupportedProtocols(
  956. p.useUpstreamProxy,
  957. limitProtocols,
  958. excludeIntensive)
  959. }
  960. func (p *protocolSelectionConstraints) selectProtocol(
  961. connectTunnelCount int,
  962. excludeIntensive bool,
  963. serverEntry *protocol.ServerEntry) (string, bool) {
  964. candidateProtocols := p.supportedProtocols(connectTunnelCount, excludeIntensive, serverEntry)
  965. if len(candidateProtocols) == 0 {
  966. return "", false
  967. }
  968. // Pick at random from the supported protocols. This ensures that we'll
  969. // eventually try all possible protocols. Depending on network
  970. // configuration, it may be the case that some protocol is only available
  971. // through multi-capability servers, and a simpler ranked preference of
  972. // protocols could lead to that protocol never being selected.
  973. index := prng.Intn(len(candidateProtocols))
  974. return candidateProtocols[index], true
  975. }
  976. type candidateServerEntry struct {
  977. serverEntry *protocol.ServerEntry
  978. isServerAffinityCandidate bool
  979. adjustedEstablishStartTime monotime.Time
  980. }
  981. // startEstablishing creates a pool of worker goroutines which will
  982. // attempt to establish tunnels to candidate servers. The candidates
  983. // are generated by another goroutine.
  984. func (controller *Controller) startEstablishing() {
  985. if controller.isEstablishing {
  986. return
  987. }
  988. NoticeInfo("start establishing")
  989. controller.concurrentEstablishTunnelsMutex.Lock()
  990. controller.establishConnectTunnelCount = 0
  991. controller.concurrentEstablishTunnels = 0
  992. controller.concurrentIntensiveEstablishTunnels = 0
  993. controller.peakConcurrentEstablishTunnels = 0
  994. controller.peakConcurrentIntensiveEstablishTunnels = 0
  995. controller.concurrentEstablishTunnelsMutex.Unlock()
  996. DoGarbageCollection()
  997. emitMemoryMetrics()
  998. // Note: the establish context cancelFunc, controller.stopEstablish,
  999. // is called in controller.stopEstablishing.
  1000. controller.isEstablishing = true
  1001. controller.establishCtx, controller.stopEstablish = context.WithCancel(controller.runCtx)
  1002. controller.establishWaitGroup = new(sync.WaitGroup)
  1003. controller.candidateServerEntries = make(chan *candidateServerEntry)
  1004. // The server affinity mechanism attempts to favor the previously
  1005. // used server when reconnecting. This is beneficial for user
  1006. // applications which expect consistency in user IP address (for
  1007. // example, a web site which prompts for additional user
  1008. // authentication when the IP address changes).
  1009. //
  1010. // Only the very first server, as determined by
  1011. // datastore.PromoteServerEntry(), is the server affinity candidate.
  1012. // Concurrent connections attempts to many servers are launched
  1013. // without delay, in case the affinity server connection fails.
  1014. // While the affinity server connection is outstanding, when any
  1015. // other connection is established, there is a short grace period
  1016. // delay before delivering the established tunnel; this allows some
  1017. // time for the affinity server connection to succeed first.
  1018. // When the affinity server connection fails, any other established
  1019. // tunnel is registered without delay.
  1020. //
  1021. // Note: the establishTunnelWorker that receives the affinity
  1022. // candidate is solely resonsible for closing
  1023. // controller.serverAffinityDoneBroadcast.
  1024. controller.serverAffinityDoneBroadcast = make(chan struct{})
  1025. controller.establishWaitGroup.Add(1)
  1026. go controller.launchEstablishing()
  1027. }
  1028. func (controller *Controller) launchEstablishing() {
  1029. defer controller.establishWaitGroup.Done()
  1030. // Before starting the establish tunnel workers, get and apply
  1031. // tactics, launching a tactics request if required.
  1032. //
  1033. // Wait only TacticsWaitPeriod for the tactics request to complete (or
  1034. // fail) before proceeding with tunnel establishment, in case the tactics
  1035. // request is blocked or takes very long to complete.
  1036. //
  1037. // An in-flight tactics request uses meek in round tripper mode, which
  1038. // uses less resources than meek tunnel relay mode. For this reason, the
  1039. // tactics request is not counted in concurrentIntensiveEstablishTunnels.
  1040. //
  1041. // TODO: HTTP/2 uses significantly more memory, so perhaps
  1042. // concurrentIntensiveEstablishTunnels should be counted in that case.
  1043. //
  1044. // Any in-flight tactics request or pending retry will be
  1045. // canceled when establishment is stopped.
  1046. if !controller.config.DisableTactics {
  1047. timeout := controller.config.GetClientParametersSnapshot().Duration(
  1048. parameters.TacticsWaitPeriod)
  1049. tacticsDone := make(chan struct{})
  1050. tacticsWaitPeriod := time.NewTimer(timeout)
  1051. defer tacticsWaitPeriod.Stop()
  1052. controller.establishWaitGroup.Add(1)
  1053. go controller.getTactics(tacticsDone)
  1054. select {
  1055. case <-tacticsDone:
  1056. case <-tacticsWaitPeriod.C:
  1057. }
  1058. tacticsWaitPeriod.Stop()
  1059. if controller.isStopEstablishing() {
  1060. // This check isn't strictly required by avoids the
  1061. // overhead of launching workers if establishment
  1062. // stopped while awaiting a tactics request.
  1063. return
  1064. }
  1065. }
  1066. // LimitTunnelProtocols and ConnectionWorkerPoolSize may be set by
  1067. // tactics.
  1068. // Initial- and LimitTunnelProtocols are set once per establishment, for
  1069. // consistent application of related probabilities (applied by
  1070. // ClientParametersSnapshot.TunnelProtocols). The
  1071. // establishLimitTunnelProtocolsState field must be read-only after this
  1072. // point, allowing concurrent reads by establishment workers.
  1073. p := controller.config.GetClientParametersSnapshot()
  1074. controller.protocolSelectionConstraints = &protocolSelectionConstraints{
  1075. useUpstreamProxy: controller.config.UseUpstreamProxy(),
  1076. initialLimitProtocols: p.TunnelProtocols(parameters.InitialLimitTunnelProtocols),
  1077. initialLimitProtocolsCandidateCount: p.Int(parameters.InitialLimitTunnelProtocolsCandidateCount),
  1078. limitProtocols: p.TunnelProtocols(parameters.LimitTunnelProtocols),
  1079. replayCandidateCount: p.Int(parameters.ReplayCandidateCount),
  1080. }
  1081. workerPoolSize := controller.config.GetClientParametersSnapshot().Int(
  1082. parameters.ConnectionWorkerPoolSize)
  1083. // When TargetServerEntry is used, override any worker pool size config or
  1084. // tactic parameter and use a pool size of 1. The typical use case for
  1085. // TargetServerEntry is to test a specific server with a single connection
  1086. // attempt. Furthermore, too many concurrent attempts to connect to the
  1087. // same server will trigger rate limiting.
  1088. if controller.config.TargetServerEntry != "" {
  1089. workerPoolSize = 1
  1090. }
  1091. p = nil
  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.GetClientParametersSnapshot()
  1258. timeout := prng.JitterDuration(
  1259. p.Duration(parameters.TacticsRetryPeriod),
  1260. p.Float(parameters.TacticsRetryPeriodJitter))
  1261. p = nil
  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 = errors.New("failed to make dial parameters")
  1318. }
  1319. if err != nil {
  1320. return nil, common.ContextError(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.GetClientParametersSnapshot().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, common.ContextError(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, common.ContextError(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.GetClientParametersSnapshot().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.GetClientParametersSnapshot().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.GetClientParametersSnapshot()
  1508. timeout := prng.JitterDuration(
  1509. p.Duration(parameters.EstablishTunnelPausePeriod),
  1510. p.Float(parameters.EstablishTunnelPausePeriodJitter))
  1511. p = nil
  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.GetClientParametersSnapshot().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.GetClientParametersSnapshot()
  1645. staggerPeriod := p.Duration(parameters.StaggerConnectionWorkersPeriod)
  1646. staggerJitter := p.Float(parameters.StaggerConnectionWorkersJitter)
  1647. p = nil
  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. }