controller.go 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001
  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. "fmt"
  27. "math/rand"
  28. "net"
  29. "sync"
  30. "sync/atomic"
  31. "time"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  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/tun"
  38. )
  39. // Controller is a tunnel lifecycle coordinator. It manages lists of servers to
  40. // connect to; establishes and monitors tunnels; and runs local proxies which
  41. // route traffic through the tunnels.
  42. type Controller struct {
  43. config *Config
  44. runCtx context.Context
  45. stopRunning context.CancelFunc
  46. runWaitGroup *sync.WaitGroup
  47. connectedTunnels chan *Tunnel
  48. failedTunnels chan *Tunnel
  49. tunnelMutex sync.Mutex
  50. establishedOnce bool
  51. tunnelPoolSize int
  52. tunnels []*Tunnel
  53. nextTunnel int
  54. isEstablishing bool
  55. protocolSelectionConstraints *protocolSelectionConstraints
  56. concurrentEstablishTunnelsMutex sync.Mutex
  57. establishConnectTunnelCount int
  58. concurrentEstablishTunnels int
  59. concurrentIntensiveEstablishTunnels int
  60. peakConcurrentEstablishTunnels int
  61. peakConcurrentIntensiveEstablishTunnels int
  62. establishCtx context.Context
  63. stopEstablish context.CancelFunc
  64. establishWaitGroup *sync.WaitGroup
  65. establishedTunnelsCount int32
  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, errors.TraceNew("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, MAX_TUNNEL_POOL_SIZE),
  103. failedTunnels: make(chan *Tunnel, MAX_TUNNEL_POOL_SIZE),
  104. tunnelPoolSize: TUNNEL_POOL_SIZE,
  105. tunnels: make([]*Tunnel, 0),
  106. establishedOnce: 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, errors.Trace(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", errors.Trace(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. NoticeWarning("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. NoticeWarning("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. controller.runWaitGroup.Add(1)
  208. go controller.connectedReporter()
  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. NoticeWarning("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 <- 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 time.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.GetParameters().Get().Duration(
  305. parameters.FetchRemoteServerListStalePeriod)
  306. if !lastFetchTime.IsZero() &&
  307. lastFetchTime.Add(stalePeriod).After(time.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 = time.Now()
  330. break retryLoop
  331. }
  332. NoticeWarning("failed to fetch %s remote server list: %s", name, err)
  333. retryPeriod := controller.config.GetParameters().Get().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.GetParameters().Get().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. //
  373. // To correctly count daily unique users, only one connected request is made
  374. // across all simultaneous multi-tunnels; and the connected request is
  375. // repeated every 24h.
  376. //
  377. // The signalReportConnected mechanism is used to trigger a connected request
  378. // immediately after a reconnect. While strictly only one connected request
  379. // per 24h is required in order to count daily unique users, the connected
  380. // request also delivers the establishment duration metric (which includes
  381. // time elapsed performing the handshake request) and additional fragmentation
  382. // metrics; these metrics are measured for each tunnel.
  383. func (controller *Controller) connectedReporter() {
  384. defer controller.runWaitGroup.Done()
  385. // session is nil when DisableApi is set
  386. if controller.config.DisableApi {
  387. return
  388. }
  389. loop:
  390. for {
  391. select {
  392. case <-controller.signalReportConnected:
  393. // Make the initial connected request
  394. case <-controller.runCtx.Done():
  395. break loop
  396. }
  397. // Pick any active tunnel and make the next connected request. No error is
  398. // logged if there's no active tunnel, as that's not an unexpected
  399. // condition.
  400. reported := false
  401. tunnel := controller.getNextActiveTunnel()
  402. if tunnel != nil {
  403. err := tunnel.serverContext.DoConnectedRequest()
  404. if err == nil {
  405. reported = true
  406. } else {
  407. NoticeWarning("failed to make connected request: %s", err)
  408. }
  409. }
  410. // Schedule the next connected request and wait. This duration is not a
  411. // dynamic ClientParameter as the daily unique user stats logic specifically
  412. // requires a "connected" request no more or less often than every 24h.
  413. var duration time.Duration
  414. if reported {
  415. duration = 24 * time.Hour
  416. } else {
  417. duration = controller.config.GetParameters().Get().Duration(
  418. parameters.PsiphonAPIConnectedRequestRetryPeriod)
  419. }
  420. timer := time.NewTimer(duration)
  421. doBreak := false
  422. select {
  423. case <-controller.signalReportConnected:
  424. case <-timer.C:
  425. // Make another connected request
  426. case <-controller.runCtx.Done():
  427. doBreak = true
  428. }
  429. timer.Stop()
  430. if doBreak {
  431. break loop
  432. }
  433. }
  434. NoticeInfo("exiting connected reporter")
  435. }
  436. func (controller *Controller) signalConnectedReporter() {
  437. // session is nil when DisableApi is set
  438. if controller.config.DisableApi {
  439. return
  440. }
  441. select {
  442. case controller.signalReportConnected <- struct{}{}:
  443. default:
  444. }
  445. }
  446. // upgradeDownloader makes periodic attempts to complete a client upgrade
  447. // download. DownloadUpgrade() is resumable, so each attempt has potential for
  448. // getting closer to completion, even in conditions where the download or
  449. // tunnel is repeatedly interrupted.
  450. // An upgrade download is triggered by either a handshake response indicating
  451. // that a new version is available; or after failing to connect, in which case
  452. // it's useful to check, out-of-band, for an upgrade with new circumvention
  453. // capabilities.
  454. // Once the download operation completes successfully, the downloader exits
  455. // and is not run again: either there is not a newer version, or the upgrade
  456. // has been downloaded and is ready to be applied.
  457. // We're assuming that the upgrade will be applied and the entire system
  458. // restarted before another upgrade is to be downloaded.
  459. //
  460. // TODO: refactor upgrade downloader and remote server list fetcher to use
  461. // common code (including the resumable download routines).
  462. //
  463. func (controller *Controller) upgradeDownloader() {
  464. defer controller.runWaitGroup.Done()
  465. var lastDownloadTime time.Time
  466. downloadLoop:
  467. for {
  468. // Wait for a signal before downloading
  469. var handshakeVersion string
  470. select {
  471. case handshakeVersion = <-controller.signalDownloadUpgrade:
  472. case <-controller.runCtx.Done():
  473. break downloadLoop
  474. }
  475. stalePeriod := controller.config.GetParameters().Get().Duration(
  476. parameters.FetchUpgradeStalePeriod)
  477. // Unless handshake is explicitly advertizing a new version, skip
  478. // checking entirely when a recent download was successful.
  479. if handshakeVersion == "" &&
  480. !lastDownloadTime.IsZero() &&
  481. lastDownloadTime.Add(stalePeriod).After(time.Now()) {
  482. continue
  483. }
  484. retryLoop:
  485. for attempt := 0; ; attempt++ {
  486. // Don't attempt to download while there is no network connectivity,
  487. // to avoid alert notice noise.
  488. if !WaitForNetworkConnectivity(
  489. controller.runCtx,
  490. controller.config.NetworkConnectivityChecker) {
  491. break downloadLoop
  492. }
  493. // Pick any active tunnel and make the next download attempt. If there's
  494. // no active tunnel, the untunneledDialConfig will be used.
  495. tunnel := controller.getNextActiveTunnel()
  496. err := DownloadUpgrade(
  497. controller.runCtx,
  498. controller.config,
  499. attempt,
  500. handshakeVersion,
  501. tunnel,
  502. controller.untunneledDialConfig)
  503. if err == nil {
  504. lastDownloadTime = time.Now()
  505. break retryLoop
  506. }
  507. NoticeWarning("failed to download upgrade: %s", err)
  508. timeout := controller.config.GetParameters().Get().Duration(
  509. parameters.FetchUpgradeRetryPeriod)
  510. timer := time.NewTimer(timeout)
  511. select {
  512. case <-timer.C:
  513. case <-controller.runCtx.Done():
  514. timer.Stop()
  515. break downloadLoop
  516. }
  517. }
  518. }
  519. NoticeInfo("exiting upgrade downloader")
  520. }
  521. // runTunnels is the controller tunnel management main loop. It starts and stops
  522. // establishing tunnels based on the target tunnel pool size and the current size
  523. // of the pool. Tunnels are established asynchronously using worker goroutines.
  524. //
  525. // When there are no server entries for the target region/protocol, the
  526. // establishCandidateGenerator will yield no candidates and wait before
  527. // trying again. In the meantime, a remote server entry fetch may supply
  528. // valid candidates.
  529. //
  530. // When a tunnel is established, it's added to the active pool. The tunnel's
  531. // operateTunnel goroutine monitors the tunnel.
  532. //
  533. // When a tunnel fails, it's removed from the pool and the establish process is
  534. // restarted to fill the pool.
  535. func (controller *Controller) runTunnels() {
  536. defer controller.runWaitGroup.Done()
  537. // Start running
  538. controller.startEstablishing()
  539. loop:
  540. for {
  541. select {
  542. case <-controller.signalRestartEstablishing:
  543. // signalRestartEstablishing restarts any establishment in progress. One
  544. // use case for this is to prioritize a newly imported, exchanged server
  545. // entry, which will be in the affinity position.
  546. //
  547. // It's possible for another connection to establish concurrent to signalling;
  548. // since the overall goal remains to establish _any_ connection, we accept that
  549. // in some cases the exchanged server entry may not get used.
  550. if controller.isEstablishing {
  551. controller.stopEstablishing()
  552. controller.startEstablishing()
  553. }
  554. case failedTunnel := <-controller.failedTunnels:
  555. NoticeWarning("tunnel failed: %s", failedTunnel.dialParams.ServerEntry.GetDiagnosticID())
  556. controller.terminateTunnel(failedTunnel)
  557. // Clear the reference to this tunnel before calling startEstablishing,
  558. // which will invoke a garbage collection.
  559. failedTunnel = nil
  560. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing,
  561. // which reference controller.isEstablishing.
  562. controller.startEstablishing()
  563. case connectedTunnel := <-controller.connectedTunnels:
  564. // Tunnel establishment has two phases: connection and activation.
  565. //
  566. // Connection is run concurrently by the establishTunnelWorkers, to minimize
  567. // delay when it's not yet known which server and protocol will be available
  568. // and unblocked.
  569. //
  570. // Activation is run serially, here, to minimize the overhead of making a
  571. // handshake request and starting the operateTunnel management worker for a
  572. // tunnel which may be discarded.
  573. //
  574. // When the active tunnel will complete establishment, establishment is
  575. // stopped before activation. This interrupts all connecting tunnels and
  576. // garbage collects their memory. The purpose is to minimize memory
  577. // pressure when the handshake request is made. In the unlikely case that the
  578. // handshake fails, establishment is restarted.
  579. //
  580. // Any delays in stopEstablishing will delay the handshake for the last
  581. // active tunnel.
  582. //
  583. // In the typical case of tunnelPoolSize of 1, only a single handshake is
  584. // performed and the homepages notices file, when used, will not be modifed
  585. // after the NoticeTunnels(1) [i.e., connected] until NoticeTunnels(0) [i.e.,
  586. // disconnected]. For tunnelPoolSize > 1, serial handshakes only ensures that
  587. // each set of emitted NoticeHomepages is contiguous.
  588. active, outstanding := controller.numTunnels()
  589. // discardTunnel will be true here when already fully established.
  590. discardTunnel := (outstanding <= 0)
  591. isFirstTunnel := (active == 0)
  592. isLastTunnel := (outstanding == 1)
  593. if !discardTunnel {
  594. if isLastTunnel {
  595. controller.stopEstablishing()
  596. }
  597. err := connectedTunnel.Activate(controller.runCtx, controller)
  598. if err != nil {
  599. NoticeWarning("failed to activate %s: %s",
  600. connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(), err)
  601. discardTunnel = true
  602. } else {
  603. // It's unlikely that registerTunnel will fail, since only this goroutine
  604. // calls registerTunnel -- and after checking numTunnels; so failure is not
  605. // expected.
  606. if !controller.registerTunnel(connectedTunnel) {
  607. NoticeWarning("failed to register %s: %s",
  608. connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(), err)
  609. discardTunnel = true
  610. }
  611. }
  612. // May need to replace this tunnel
  613. if isLastTunnel && discardTunnel {
  614. controller.startEstablishing()
  615. }
  616. }
  617. if discardTunnel {
  618. controller.discardTunnel(connectedTunnel)
  619. // Clear the reference to this discarded tunnel and immediately run
  620. // a garbage collection to reclaim its memory.
  621. connectedTunnel = nil
  622. DoGarbageCollection()
  623. // Skip the rest of this case
  624. break
  625. }
  626. atomic.AddInt32(&controller.establishedTunnelsCount, 1)
  627. NoticeActiveTunnel(
  628. connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(),
  629. connectedTunnel.dialParams.TunnelProtocol,
  630. connectedTunnel.dialParams.ServerEntry.SupportsSSHAPIRequests())
  631. if isFirstTunnel {
  632. // The split tunnel classifier is started once the first tunnel is
  633. // established. This first tunnel is passed in to be used to make
  634. // the routes data request.
  635. // A long-running controller may run while the host device is present
  636. // in different regions. In this case, we want the split tunnel logic
  637. // to switch to routes for new regions and not classify traffic based
  638. // on routes installed for older regions.
  639. // We assume that when regions change, the host network will also
  640. // change, and so all tunnels will fail and be re-established. Under
  641. // that assumption, the classifier will be re-Start()-ed here when
  642. // the region has changed.
  643. controller.splitTunnelClassifier.Start(connectedTunnel)
  644. // Signal a connected request on each 1st tunnel establishment. For
  645. // multi-tunnels, the session is connected as long as at least one
  646. // tunnel is established.
  647. controller.signalConnectedReporter()
  648. // If the handshake indicated that a new client version is available,
  649. // trigger an upgrade download.
  650. // Note: serverContext is nil when DisableApi is set
  651. if connectedTunnel.serverContext != nil &&
  652. connectedTunnel.serverContext.clientUpgradeVersion != "" {
  653. handshakeVersion := connectedTunnel.serverContext.clientUpgradeVersion
  654. select {
  655. case controller.signalDownloadUpgrade <- handshakeVersion:
  656. default:
  657. }
  658. }
  659. }
  660. // Set the new tunnel as the transport for the packet tunnel. The packet tunnel
  661. // client remains up when reestablishing, but no packets are relayed while there
  662. // is no connected tunnel. UseTunnel will establish a new packet tunnel SSH
  663. // channel over the new SSH tunnel and configure the packet tunnel client to use
  664. // the new SSH channel as its transport.
  665. //
  666. // Note: as is, this logic is suboptimal for tunnelPoolSize > 1, as this would
  667. // continuously initialize new packet tunnel sessions for each established
  668. // server. For now, config validation requires tunnelPoolSize == 1 when
  669. // the packet tunnel is used.
  670. if controller.packetTunnelTransport != nil {
  671. controller.packetTunnelTransport.UseTunnel(connectedTunnel)
  672. }
  673. if controller.isFullyEstablished() {
  674. controller.stopEstablishing()
  675. }
  676. case <-controller.runCtx.Done():
  677. break loop
  678. }
  679. }
  680. // Stop running
  681. controller.stopEstablishing()
  682. controller.terminateAllTunnels()
  683. // Drain tunnel channels
  684. close(controller.connectedTunnels)
  685. for tunnel := range controller.connectedTunnels {
  686. controller.discardTunnel(tunnel)
  687. }
  688. close(controller.failedTunnels)
  689. for tunnel := range controller.failedTunnels {
  690. controller.discardTunnel(tunnel)
  691. }
  692. NoticeInfo("exiting run tunnels")
  693. }
  694. // SignalSeededNewSLOK implements the TunnelOwner interface. This function
  695. // is called by Tunnel.operateTunnel when the tunnel has received a new,
  696. // previously unknown SLOK from the server. The Controller triggers an OSL
  697. // fetch, as the new SLOK may be sufficient to access new OSLs.
  698. func (controller *Controller) SignalSeededNewSLOK() {
  699. select {
  700. case controller.signalFetchObfuscatedServerLists <- struct{}{}:
  701. default:
  702. }
  703. }
  704. // SignalTunnelFailure implements the TunnelOwner interface. This function
  705. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  706. // has failed. The Controller will signal runTunnels to create a new
  707. // tunnel and/or remove the tunnel from the list of active tunnels.
  708. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  709. // Don't block. Assumes the receiver has a buffer large enough for
  710. // the typical number of operated tunnels. In case there's no room,
  711. // terminate the tunnel (runTunnels won't get a signal in this case,
  712. // but the tunnel will be removed from the list of active tunnels).
  713. select {
  714. case controller.failedTunnels <- tunnel:
  715. default:
  716. controller.terminateTunnel(tunnel)
  717. }
  718. }
  719. // discardTunnel disposes of a successful connection that is no longer required.
  720. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  721. NoticeInfo("discard tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  722. // TODO: not calling PromoteServerEntry, since that would rank the
  723. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  724. // be promoted (since it connects), but with lower rank than all active
  725. // tunnels?
  726. tunnel.Close(true)
  727. }
  728. // registerTunnel adds the connected tunnel to the pool of active tunnels
  729. // which are candidates for port forwarding. Returns true if the pool has an
  730. // empty slot and false if the pool is full (caller should discard the tunnel).
  731. func (controller *Controller) registerTunnel(tunnel *Tunnel) bool {
  732. controller.tunnelMutex.Lock()
  733. defer controller.tunnelMutex.Unlock()
  734. if len(controller.tunnels) >= controller.tunnelPoolSize {
  735. return false
  736. }
  737. // Perform a final check just in case we've established
  738. // a duplicate connection.
  739. for _, activeTunnel := range controller.tunnels {
  740. if activeTunnel.dialParams.ServerEntry.IpAddress ==
  741. tunnel.dialParams.ServerEntry.IpAddress {
  742. NoticeWarning("duplicate tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  743. return false
  744. }
  745. }
  746. controller.establishedOnce = true
  747. controller.tunnels = append(controller.tunnels, tunnel)
  748. NoticeTunnels(len(controller.tunnels))
  749. // Promote this successful tunnel to first rank so it's one
  750. // of the first candidates next time establish runs.
  751. // Connecting to a TargetServerEntry does not change the
  752. // ranking.
  753. if controller.config.TargetServerEntry == "" {
  754. PromoteServerEntry(controller.config, tunnel.dialParams.ServerEntry.IpAddress)
  755. }
  756. return true
  757. }
  758. // hasEstablishedOnce indicates if at least one active tunnel has
  759. // been established up to this point. This is regardeless of how many
  760. // tunnels are presently active.
  761. func (controller *Controller) hasEstablishedOnce() bool {
  762. controller.tunnelMutex.Lock()
  763. defer controller.tunnelMutex.Unlock()
  764. return controller.establishedOnce
  765. }
  766. // isFullyEstablished indicates if the pool of active tunnels is full.
  767. func (controller *Controller) isFullyEstablished() bool {
  768. controller.tunnelMutex.Lock()
  769. defer controller.tunnelMutex.Unlock()
  770. return len(controller.tunnels) >= controller.tunnelPoolSize
  771. }
  772. // numTunnels returns the number of active and outstanding tunnels.
  773. // Oustanding is the number of tunnels required to fill the pool of
  774. // active tunnels.
  775. func (controller *Controller) numTunnels() (int, int) {
  776. controller.tunnelMutex.Lock()
  777. defer controller.tunnelMutex.Unlock()
  778. active := len(controller.tunnels)
  779. outstanding := controller.tunnelPoolSize - len(controller.tunnels)
  780. return active, outstanding
  781. }
  782. // terminateTunnel removes a tunnel from the pool of active tunnels
  783. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  784. // is adjusted as required.
  785. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  786. controller.tunnelMutex.Lock()
  787. defer controller.tunnelMutex.Unlock()
  788. for index, activeTunnel := range controller.tunnels {
  789. if tunnel == activeTunnel {
  790. controller.tunnels = append(
  791. controller.tunnels[:index], controller.tunnels[index+1:]...)
  792. if controller.nextTunnel > index {
  793. controller.nextTunnel--
  794. }
  795. if controller.nextTunnel >= len(controller.tunnels) {
  796. controller.nextTunnel = 0
  797. }
  798. activeTunnel.Close(false)
  799. NoticeTunnels(len(controller.tunnels))
  800. break
  801. }
  802. }
  803. }
  804. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  805. // This is used when shutting down the controller.
  806. func (controller *Controller) terminateAllTunnels() {
  807. controller.tunnelMutex.Lock()
  808. defer controller.tunnelMutex.Unlock()
  809. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  810. // may take a few seconds to send a final status request. We only want
  811. // to wait as long as the single slowest tunnel.
  812. closeWaitGroup := new(sync.WaitGroup)
  813. closeWaitGroup.Add(len(controller.tunnels))
  814. for _, activeTunnel := range controller.tunnels {
  815. tunnel := activeTunnel
  816. go func() {
  817. defer closeWaitGroup.Done()
  818. tunnel.Close(false)
  819. }()
  820. }
  821. closeWaitGroup.Wait()
  822. controller.tunnels = make([]*Tunnel, 0)
  823. controller.nextTunnel = 0
  824. NoticeTunnels(len(controller.tunnels))
  825. }
  826. // getNextActiveTunnel returns the next tunnel from the pool of active
  827. // tunnels. Currently, tunnel selection order is simple round-robin.
  828. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  829. controller.tunnelMutex.Lock()
  830. defer controller.tunnelMutex.Unlock()
  831. if len(controller.tunnels) == 0 {
  832. return nil
  833. }
  834. tunnel = controller.tunnels[controller.nextTunnel]
  835. controller.nextTunnel =
  836. (controller.nextTunnel + 1) % len(controller.tunnels)
  837. return tunnel
  838. }
  839. // isActiveTunnelServerEntry is used to check if there's already
  840. // an existing tunnel to a candidate server.
  841. func (controller *Controller) isActiveTunnelServerEntry(
  842. serverEntry *protocol.ServerEntry) bool {
  843. controller.tunnelMutex.Lock()
  844. defer controller.tunnelMutex.Unlock()
  845. for _, activeTunnel := range controller.tunnels {
  846. if activeTunnel.dialParams.ServerEntry.IpAddress == serverEntry.IpAddress {
  847. return true
  848. }
  849. }
  850. return false
  851. }
  852. func (controller *Controller) setTunnelPoolSize(tunnelPoolSize int) {
  853. controller.tunnelMutex.Lock()
  854. defer controller.tunnelMutex.Unlock()
  855. if tunnelPoolSize < 1 {
  856. tunnelPoolSize = 1
  857. }
  858. if tunnelPoolSize > MAX_TUNNEL_POOL_SIZE {
  859. tunnelPoolSize = MAX_TUNNEL_POOL_SIZE
  860. }
  861. controller.tunnelPoolSize = tunnelPoolSize
  862. }
  863. func (controller *Controller) getTunnelPoolSize() int {
  864. controller.tunnelMutex.Lock()
  865. defer controller.tunnelMutex.Unlock()
  866. return controller.tunnelPoolSize
  867. }
  868. // Dial selects an active tunnel and establishes a port forward
  869. // connection through the selected tunnel. Failure to connect is considered
  870. // a port forward failure, for the purpose of monitoring tunnel health.
  871. func (controller *Controller) Dial(
  872. remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error) {
  873. tunnel := controller.getNextActiveTunnel()
  874. if tunnel == nil {
  875. return nil, errors.TraceNew("no active tunnels")
  876. }
  877. // Perform split tunnel classification when feature is enabled, and if the remote
  878. // address is classified as untunneled, dial directly.
  879. if !alwaysTunnel && controller.config.SplitTunnelDNSServer != "" {
  880. host, _, err := net.SplitHostPort(remoteAddr)
  881. if err != nil {
  882. return nil, errors.Trace(err)
  883. }
  884. // Note: a possible optimization, when split tunnel is active and IsUntunneled performs
  885. // a DNS resolution in order to make its classification, is to reuse that IP address in
  886. // the following Dials so they do not need to make their own resolutions. However, the
  887. // way this is currently implemented ensures that, e.g., DNS geo load balancing occurs
  888. // relative to the outbound network.
  889. if controller.splitTunnelClassifier.IsUntunneled(host) {
  890. return controller.DirectDial(remoteAddr)
  891. }
  892. }
  893. tunneledConn, err := tunnel.Dial(remoteAddr, alwaysTunnel, downstreamConn)
  894. if err != nil {
  895. return nil, errors.Trace(err)
  896. }
  897. return tunneledConn, nil
  898. }
  899. // DirectDial dials an untunneled TCP connection within the controller run context.
  900. func (controller *Controller) DirectDial(remoteAddr string) (conn net.Conn, err error) {
  901. return DialTCP(controller.runCtx, remoteAddr, controller.untunneledDialConfig)
  902. }
  903. // triggerFetches signals RSL, OSL, and upgrade download fetchers to begin, if
  904. // not already running. triggerFetches is called when tunnel establishment
  905. // fails to complete within a deadline and in other cases where local
  906. // circumvention capabilities are lacking and we may require new server
  907. // entries or client versions with new capabilities.
  908. func (controller *Controller) triggerFetches() {
  909. // Trigger a common remote server list fetch, since we may have failed
  910. // to connect with all known servers. Don't block sending signal, since
  911. // this signal may have already been sent.
  912. // Don't wait for fetch remote to succeed, since it may fail and
  913. // enter a retry loop and we're better off trying more known servers.
  914. // TODO: synchronize the fetch response, so it can be incorporated
  915. // into the server entry iterator as soon as available.
  916. select {
  917. case controller.signalFetchCommonRemoteServerList <- struct{}{}:
  918. default:
  919. }
  920. // Trigger an OSL fetch in parallel. Both fetches are run in parallel
  921. // so that if one out of the common RLS and OSL set is large, it doesn't
  922. // doesn't entirely block fetching the other.
  923. select {
  924. case controller.signalFetchObfuscatedServerLists <- struct{}{}:
  925. default:
  926. }
  927. // Trigger an out-of-band upgrade availability check and download.
  928. // Since we may have failed to connect, we may benefit from upgrading
  929. // to a new client version with new circumvention capabilities.
  930. select {
  931. case controller.signalDownloadUpgrade <- "":
  932. default:
  933. }
  934. }
  935. type protocolSelectionConstraints struct {
  936. useUpstreamProxy bool
  937. initialLimitProtocols protocol.TunnelProtocols
  938. initialLimitProtocolsCandidateCount int
  939. limitProtocols protocol.TunnelProtocols
  940. replayCandidateCount int
  941. }
  942. func (p *protocolSelectionConstraints) hasInitialProtocols() bool {
  943. return len(p.initialLimitProtocols) > 0 && p.initialLimitProtocolsCandidateCount > 0
  944. }
  945. func (p *protocolSelectionConstraints) isInitialCandidate(
  946. excludeIntensive bool,
  947. serverEntry *protocol.ServerEntry) bool {
  948. return p.hasInitialProtocols() &&
  949. len(serverEntry.GetSupportedProtocols(
  950. conditionallyEnabledComponents{},
  951. p.useUpstreamProxy,
  952. p.initialLimitProtocols,
  953. excludeIntensive)) > 0
  954. }
  955. func (p *protocolSelectionConstraints) isCandidate(
  956. excludeIntensive bool,
  957. serverEntry *protocol.ServerEntry) bool {
  958. return len(p.limitProtocols) == 0 ||
  959. len(serverEntry.GetSupportedProtocols(
  960. conditionallyEnabledComponents{},
  961. p.useUpstreamProxy,
  962. p.limitProtocols,
  963. excludeIntensive)) > 0
  964. }
  965. func (p *protocolSelectionConstraints) canReplay(
  966. connectTunnelCount int,
  967. excludeIntensive bool,
  968. serverEntry *protocol.ServerEntry,
  969. replayProtocol string) bool {
  970. if p.replayCandidateCount != -1 && connectTunnelCount > p.replayCandidateCount {
  971. return false
  972. }
  973. return common.Contains(
  974. p.supportedProtocols(connectTunnelCount, excludeIntensive, serverEntry),
  975. replayProtocol)
  976. }
  977. func (p *protocolSelectionConstraints) supportedProtocols(
  978. connectTunnelCount int,
  979. excludeIntensive bool,
  980. serverEntry *protocol.ServerEntry) []string {
  981. limitProtocols := p.limitProtocols
  982. if len(p.initialLimitProtocols) > 0 && p.initialLimitProtocolsCandidateCount > connectTunnelCount {
  983. limitProtocols = p.initialLimitProtocols
  984. }
  985. return serverEntry.GetSupportedProtocols(
  986. conditionallyEnabledComponents{},
  987. p.useUpstreamProxy,
  988. limitProtocols,
  989. excludeIntensive)
  990. }
  991. func (p *protocolSelectionConstraints) selectProtocol(
  992. connectTunnelCount int,
  993. excludeIntensive bool,
  994. serverEntry *protocol.ServerEntry) (string, bool) {
  995. candidateProtocols := p.supportedProtocols(connectTunnelCount, excludeIntensive, serverEntry)
  996. if len(candidateProtocols) == 0 {
  997. return "", false
  998. }
  999. // Pick at random from the supported protocols. This ensures that we'll
  1000. // eventually try all possible protocols. Depending on network
  1001. // configuration, it may be the case that some protocol is only available
  1002. // through multi-capability servers, and a simpler ranked preference of
  1003. // protocols could lead to that protocol never being selected.
  1004. index := prng.Intn(len(candidateProtocols))
  1005. return candidateProtocols[index], true
  1006. }
  1007. type candidateServerEntry struct {
  1008. serverEntry *protocol.ServerEntry
  1009. isServerAffinityCandidate bool
  1010. adjustedEstablishStartTime time.Time
  1011. }
  1012. // startEstablishing creates a pool of worker goroutines which will
  1013. // attempt to establish tunnels to candidate servers. The candidates
  1014. // are generated by another goroutine.
  1015. func (controller *Controller) startEstablishing() {
  1016. if controller.isEstablishing {
  1017. return
  1018. }
  1019. NoticeInfo("start establishing")
  1020. controller.concurrentEstablishTunnelsMutex.Lock()
  1021. controller.establishConnectTunnelCount = 0
  1022. controller.concurrentEstablishTunnels = 0
  1023. controller.concurrentIntensiveEstablishTunnels = 0
  1024. controller.peakConcurrentEstablishTunnels = 0
  1025. controller.peakConcurrentIntensiveEstablishTunnels = 0
  1026. controller.concurrentEstablishTunnelsMutex.Unlock()
  1027. DoGarbageCollection()
  1028. emitMemoryMetrics()
  1029. // Note: the establish context cancelFunc, controller.stopEstablish,
  1030. // is called in controller.stopEstablishing.
  1031. controller.isEstablishing = true
  1032. controller.establishCtx, controller.stopEstablish = context.WithCancel(controller.runCtx)
  1033. controller.establishWaitGroup = new(sync.WaitGroup)
  1034. controller.candidateServerEntries = make(chan *candidateServerEntry)
  1035. // The server affinity mechanism attempts to favor the previously
  1036. // used server when reconnecting. This is beneficial for user
  1037. // applications which expect consistency in user IP address (for
  1038. // example, a web site which prompts for additional user
  1039. // authentication when the IP address changes).
  1040. //
  1041. // Only the very first server, as determined by
  1042. // datastore.PromoteServerEntry(), is the server affinity candidate.
  1043. // Concurrent connections attempts to many servers are launched
  1044. // without delay, in case the affinity server connection fails.
  1045. // While the affinity server connection is outstanding, when any
  1046. // other connection is established, there is a short grace period
  1047. // delay before delivering the established tunnel; this allows some
  1048. // time for the affinity server connection to succeed first.
  1049. // When the affinity server connection fails, any other established
  1050. // tunnel is registered without delay.
  1051. //
  1052. // Note: the establishTunnelWorker that receives the affinity
  1053. // candidate is solely resonsible for closing
  1054. // controller.serverAffinityDoneBroadcast.
  1055. controller.serverAffinityDoneBroadcast = make(chan struct{})
  1056. controller.establishWaitGroup.Add(1)
  1057. go controller.launchEstablishing()
  1058. }
  1059. func (controller *Controller) launchEstablishing() {
  1060. defer controller.establishWaitGroup.Done()
  1061. // Before starting the establish tunnel workers, get and apply
  1062. // tactics, launching a tactics request if required.
  1063. //
  1064. // Wait only TacticsWaitPeriod for the tactics request to complete (or
  1065. // fail) before proceeding with tunnel establishment, in case the tactics
  1066. // request is blocked or takes very long to complete.
  1067. //
  1068. // An in-flight tactics request uses meek in round tripper mode, which
  1069. // uses less resources than meek tunnel relay mode. For this reason, the
  1070. // tactics request is not counted in concurrentIntensiveEstablishTunnels.
  1071. //
  1072. // TODO: HTTP/2 uses significantly more memory, so perhaps
  1073. // concurrentIntensiveEstablishTunnels should be counted in that case.
  1074. //
  1075. // Any in-flight tactics request or pending retry will be
  1076. // canceled when establishment is stopped.
  1077. if !controller.config.DisableTactics {
  1078. timeout := controller.config.GetParameters().Get().Duration(
  1079. parameters.TacticsWaitPeriod)
  1080. tacticsDone := make(chan struct{})
  1081. tacticsWaitPeriod := time.NewTimer(timeout)
  1082. defer tacticsWaitPeriod.Stop()
  1083. controller.establishWaitGroup.Add(1)
  1084. go func() {
  1085. defer controller.establishWaitGroup.Done()
  1086. defer close(tacticsDone)
  1087. GetTactics(controller.establishCtx, controller.config)
  1088. }()
  1089. select {
  1090. case <-tacticsDone:
  1091. case <-tacticsWaitPeriod.C:
  1092. }
  1093. tacticsWaitPeriod.Stop()
  1094. if controller.isStopEstablishing() {
  1095. // This check isn't strictly required but avoids the overhead of launching
  1096. // workers if establishment stopped while awaiting a tactics request.
  1097. return
  1098. }
  1099. }
  1100. // LimitTunnelProtocols and ConnectionWorkerPoolSize may be set by
  1101. // tactics.
  1102. // Initial- and LimitTunnelProtocols are set once per establishment, for
  1103. // consistent application of related probabilities (applied by
  1104. // ParametersAccessor.TunnelProtocols). The
  1105. // establishLimitTunnelProtocolsState field must be read-only after this
  1106. // point, allowing concurrent reads by establishment workers.
  1107. p := controller.config.GetParameters().Get()
  1108. controller.protocolSelectionConstraints = &protocolSelectionConstraints{
  1109. useUpstreamProxy: controller.config.UseUpstreamProxy(),
  1110. initialLimitProtocols: p.TunnelProtocols(parameters.InitialLimitTunnelProtocols),
  1111. initialLimitProtocolsCandidateCount: p.Int(parameters.InitialLimitTunnelProtocolsCandidateCount),
  1112. limitProtocols: p.TunnelProtocols(parameters.LimitTunnelProtocols),
  1113. replayCandidateCount: p.Int(parameters.ReplayCandidateCount),
  1114. }
  1115. workerPoolSize := p.Int(parameters.ConnectionWorkerPoolSize)
  1116. // When TargetServerEntry is used, override any worker pool size config or
  1117. // tactic parameter and use a pool size of 1. The typical use case for
  1118. // TargetServerEntry is to test a specific server with a single connection
  1119. // attempt. Furthermore, too many concurrent attempts to connect to the
  1120. // same server will trigger rate limiting.
  1121. if controller.config.TargetServerEntry != "" {
  1122. workerPoolSize = 1
  1123. }
  1124. // TunnelPoolSize may be set by tactics, subject to local constraints. A pool
  1125. // size of one is forced in packet tunnel mode or when using a
  1126. // TargetServerEntry. The tunnel pool size is reduced when there are
  1127. // insufficent known server entries, within the set region and protocol
  1128. // constraints, to satisfy the target.
  1129. //
  1130. // Limitations, to simplify concurrent access to shared state: a ceiling of
  1131. // MAX_TUNNEL_POOL_SIZE is enforced by setTunnelPoolSize; the tunnel pool
  1132. // size target is not re-adjusted after an API handshake, even though the
  1133. // handshake response may deliver new tactics, or prune server entries which
  1134. // were potential candidates; nor is the target re-adjusted after fetching
  1135. // new server entries during this establishment.
  1136. tunnelPoolSize := p.Int(parameters.TunnelPoolSize)
  1137. if controller.config.PacketTunnelTunFileDescriptor > 0 ||
  1138. controller.config.TargetServerEntry != "" {
  1139. tunnelPoolSize = 1
  1140. }
  1141. if tunnelPoolSize > 1 {
  1142. // Initial count is ignored as count candidates will eventually become
  1143. // available.
  1144. _, count := CountServerEntriesWithConstraints(
  1145. controller.config.UseUpstreamProxy(),
  1146. controller.config.EgressRegion,
  1147. controller.protocolSelectionConstraints)
  1148. if count < tunnelPoolSize {
  1149. if count < 1 {
  1150. count = 1
  1151. }
  1152. tunnelPoolSize = count
  1153. }
  1154. }
  1155. controller.setTunnelPoolSize(tunnelPoolSize)
  1156. p.Close()
  1157. // If InitialLimitTunnelProtocols is configured but cannot be satisfied,
  1158. // skip the initial phase in this establishment. This avoids spinning,
  1159. // unable to connect, in this case. InitialLimitTunnelProtocols is
  1160. // intended to prioritize certain protocols, but not strictly select them.
  1161. //
  1162. // The candidate count check is made with egress region selection unset.
  1163. // When an egress region is selected, it's the responsibility of the outer
  1164. // client to react to the following ReportAvailableRegions output and
  1165. // clear the user's selected region to prevent spinning, unable to
  1166. // connect. The initial phase is skipped only when
  1167. // InitialLimitTunnelProtocols cannot be satisfied _regardless_ of region
  1168. // selection.
  1169. //
  1170. // We presume that, in practise, most clients will have embedded server
  1171. // entries with capabilities for most protocols; and that clients will
  1172. // often perform RSL checks. So clients should most often have the
  1173. // necessary capabilities to satisfy InitialLimitTunnelProtocols. When
  1174. // this check fails, RSL/OSL/upgrade checks are triggered in order to gain
  1175. // new capabilities.
  1176. //
  1177. // LimitTunnelProtocols remains a hard limit, as using prohibited
  1178. // protocols may have some bad effect, such as a firewall blocking all
  1179. // traffic from a host.
  1180. if controller.protocolSelectionConstraints.initialLimitProtocolsCandidateCount > 0 {
  1181. egressRegion := "" // no egress region
  1182. initialCount, count := CountServerEntriesWithConstraints(
  1183. controller.config.UseUpstreamProxy(),
  1184. egressRegion,
  1185. controller.protocolSelectionConstraints)
  1186. if initialCount == 0 {
  1187. NoticeCandidateServers(
  1188. egressRegion,
  1189. controller.protocolSelectionConstraints,
  1190. initialCount,
  1191. count)
  1192. NoticeWarning("skipping initial limit tunnel protocols")
  1193. controller.protocolSelectionConstraints.initialLimitProtocolsCandidateCount = 0
  1194. // Since we were unable to satisfy the InitialLimitTunnelProtocols
  1195. // tactic, trigger RSL, OSL, and upgrade fetches to potentially
  1196. // gain new capabilities.
  1197. controller.triggerFetches()
  1198. }
  1199. }
  1200. // Report available egress regions. After a fresh install, the outer
  1201. // client may not have a list of regions to display; and
  1202. // LimitTunnelProtocols may reduce the number of available regions.
  1203. //
  1204. // When the outer client receives NoticeAvailableEgressRegions and the
  1205. // configured EgressRegion is not included in the region list, the outer
  1206. // client _should_ stop tunnel-core and prompt the user to change the
  1207. // region selection, as there are insufficient servers/capabilities to
  1208. // establish a tunnel in the selected region.
  1209. //
  1210. // This report is delayed until after tactics are likely to be applied;
  1211. // this avoids a ReportAvailableRegions reporting too many regions,
  1212. // followed shortly by a ReportAvailableRegions reporting fewer regions.
  1213. // That sequence could cause issues in the outer client UI.
  1214. //
  1215. // The reported regions are limited by protocolSelectionConstraints;
  1216. // in the case where an initial limit is in place, only regions available
  1217. // for the initial limit are reported. The initial phase will not complete
  1218. // if EgressRegion is set such that there are no server entries with the
  1219. // necessary protocol capabilities (either locally or from a remote server
  1220. // list fetch).
  1221. ReportAvailableRegions(
  1222. controller.config,
  1223. controller.protocolSelectionConstraints)
  1224. for i := 0; i < workerPoolSize; i++ {
  1225. controller.establishWaitGroup.Add(1)
  1226. go controller.establishTunnelWorker()
  1227. }
  1228. controller.establishWaitGroup.Add(1)
  1229. go controller.establishCandidateGenerator()
  1230. }
  1231. // stopEstablishing signals the establish goroutines to stop and waits
  1232. // for the group to halt.
  1233. func (controller *Controller) stopEstablishing() {
  1234. if !controller.isEstablishing {
  1235. return
  1236. }
  1237. NoticeInfo("stop establishing")
  1238. controller.stopEstablish()
  1239. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  1240. // (as it may be sending to that channel).
  1241. controller.establishWaitGroup.Wait()
  1242. NoticeInfo("stopped establishing")
  1243. controller.isEstablishing = false
  1244. controller.establishCtx = nil
  1245. controller.stopEstablish = nil
  1246. controller.establishWaitGroup = nil
  1247. controller.candidateServerEntries = nil
  1248. controller.serverAffinityDoneBroadcast = nil
  1249. controller.concurrentEstablishTunnelsMutex.Lock()
  1250. peakConcurrent := controller.peakConcurrentEstablishTunnels
  1251. peakConcurrentIntensive := controller.peakConcurrentIntensiveEstablishTunnels
  1252. controller.establishConnectTunnelCount = 0
  1253. controller.concurrentEstablishTunnels = 0
  1254. controller.concurrentIntensiveEstablishTunnels = 0
  1255. controller.peakConcurrentEstablishTunnels = 0
  1256. controller.peakConcurrentIntensiveEstablishTunnels = 0
  1257. controller.concurrentEstablishTunnelsMutex.Unlock()
  1258. NoticeInfo("peak concurrent establish tunnels: %d", peakConcurrent)
  1259. NoticeInfo("peak concurrent resource intensive establish tunnels: %d", peakConcurrentIntensive)
  1260. emitMemoryMetrics()
  1261. DoGarbageCollection()
  1262. }
  1263. // establishCandidateGenerator populates the candidate queue with server entries
  1264. // from the data store. Server entries are iterated in rank order, so that promoted
  1265. // servers with higher rank are priority candidates.
  1266. func (controller *Controller) establishCandidateGenerator() {
  1267. defer controller.establishWaitGroup.Done()
  1268. defer close(controller.candidateServerEntries)
  1269. // establishStartTime is used to calculate and report the
  1270. // client's tunnel establishment duration.
  1271. //
  1272. // networkWaitDuration is the elapsed time spent waiting
  1273. // for network connectivity. This duration will be excluded
  1274. // from reported tunnel establishment duration.
  1275. establishStartTime := time.Now()
  1276. var totalNetworkWaitDuration time.Duration
  1277. applyServerAffinity, iterator, err := NewServerEntryIterator(controller.config)
  1278. if err != nil {
  1279. NoticeWarning("failed to iterate over candidates: %s", err)
  1280. controller.SignalComponentFailure()
  1281. return
  1282. }
  1283. defer iterator.Close()
  1284. // TODO: reconcile server affinity scheme with multi-tunnel mode
  1285. if controller.getTunnelPoolSize() > 1 {
  1286. applyServerAffinity = false
  1287. }
  1288. isServerAffinityCandidate := true
  1289. if !applyServerAffinity {
  1290. isServerAffinityCandidate = false
  1291. close(controller.serverAffinityDoneBroadcast)
  1292. }
  1293. loop:
  1294. // Repeat until stopped
  1295. for {
  1296. // For diagnostics, emits counts of the number of known server
  1297. // entries that satisfy both the egress region and tunnel protocol
  1298. // requirements (excluding excludeIntensive logic).
  1299. // Counts may change during establishment due to remote server
  1300. // list fetches, etc.
  1301. initialCount, count := CountServerEntriesWithConstraints(
  1302. controller.config.UseUpstreamProxy(),
  1303. controller.config.EgressRegion,
  1304. controller.protocolSelectionConstraints)
  1305. NoticeCandidateServers(
  1306. controller.config.EgressRegion,
  1307. controller.protocolSelectionConstraints,
  1308. initialCount,
  1309. count)
  1310. // A "round" consists of a new shuffle of the server entries and attempted
  1311. // connections up to the end of the server entry iterator, or
  1312. // parameters.EstablishTunnelWorkTime elapsed. Time spent waiting for
  1313. // network connectivity is excluded from round elapsed time.
  1314. //
  1315. // After a round, if parameters.EstablishTunnelWorkTime has elapsed in total
  1316. // with no tunnel established, remote server list and upgrade checks are
  1317. // triggered.
  1318. //
  1319. // A complete server entry iteration does not trigger fetches since it's
  1320. // possible to have fewer than parameters.ConnectionWorkerPoolSize
  1321. // candidates, in which case rounds end instantly due to the complete server
  1322. // entry iteration. An exception is made for an empty server entry iterator;
  1323. // in that case fetches may be triggered immediately.
  1324. roundStartTime := time.Now()
  1325. var roundNetworkWaitDuration time.Duration
  1326. workTime := controller.config.GetParameters().Get().Duration(
  1327. parameters.EstablishTunnelWorkTime)
  1328. candidateServerEntryCount := 0
  1329. // Send each iterator server entry to the establish workers
  1330. for {
  1331. networkWaitStartTime := time.Now()
  1332. if !WaitForNetworkConnectivity(
  1333. controller.establishCtx,
  1334. controller.config.NetworkConnectivityChecker) {
  1335. break loop
  1336. }
  1337. networkWaitDuration := time.Since(networkWaitStartTime)
  1338. roundNetworkWaitDuration += networkWaitDuration
  1339. totalNetworkWaitDuration += networkWaitDuration
  1340. serverEntry, err := iterator.Next()
  1341. if err != nil {
  1342. NoticeWarning("failed to get next candidate: %s", err)
  1343. controller.SignalComponentFailure()
  1344. break loop
  1345. }
  1346. if serverEntry == nil {
  1347. // Completed this iteration
  1348. NoticeInfo("completed server entry iteration")
  1349. break
  1350. }
  1351. if controller.config.TargetApiProtocol == protocol.PSIPHON_SSH_API_PROTOCOL &&
  1352. !serverEntry.SupportsSSHAPIRequests() {
  1353. continue
  1354. }
  1355. candidateServerEntryCount += 1
  1356. // adjustedEstablishStartTime is establishStartTime shifted
  1357. // to exclude time spent waiting for network connectivity.
  1358. adjustedEstablishStartTime := establishStartTime.Add(totalNetworkWaitDuration)
  1359. candidate := &candidateServerEntry{
  1360. serverEntry: serverEntry,
  1361. isServerAffinityCandidate: isServerAffinityCandidate,
  1362. adjustedEstablishStartTime: adjustedEstablishStartTime,
  1363. }
  1364. wasServerAffinityCandidate := isServerAffinityCandidate
  1365. // Note: there must be only one server affinity candidate, as it
  1366. // closes the serverAffinityDoneBroadcast channel.
  1367. isServerAffinityCandidate = false
  1368. // TODO: here we could generate multiple candidates from the
  1369. // server entry when there are many MeekFrontingAddresses.
  1370. select {
  1371. case controller.candidateServerEntries <- candidate:
  1372. case <-controller.establishCtx.Done():
  1373. break loop
  1374. }
  1375. if time.Since(roundStartTime)-roundNetworkWaitDuration > workTime {
  1376. // Start over, after a brief pause, with a new shuffle of the server
  1377. // entries, and potentially some newly fetched server entries.
  1378. break
  1379. }
  1380. if wasServerAffinityCandidate {
  1381. // Don't start the next candidate until either the server affinity
  1382. // candidate has completed (success or failure) or is still working
  1383. // and the grace period has elapsed.
  1384. gracePeriod := controller.config.GetParameters().Get().Duration(
  1385. parameters.EstablishTunnelServerAffinityGracePeriod)
  1386. if gracePeriod > 0 {
  1387. timer := time.NewTimer(gracePeriod)
  1388. select {
  1389. case <-timer.C:
  1390. case <-controller.serverAffinityDoneBroadcast:
  1391. case <-controller.establishCtx.Done():
  1392. timer.Stop()
  1393. break loop
  1394. }
  1395. timer.Stop()
  1396. }
  1397. }
  1398. }
  1399. // Free up resources now, but don't reset until after the pause.
  1400. iterator.Close()
  1401. // Trigger RSL, OSL, and upgrade checks after failing to establish a
  1402. // tunnel within parameters.EstablishTunnelWorkTime, or if there are
  1403. // no server entries present.
  1404. //
  1405. // While the trigger is made after each round,
  1406. // parameter.FetchRemoteServerListStalePeriod will limit the actual
  1407. // frequency of fetches. Continuing to trigger allows for very long running
  1408. // establishments to perhaps eventually succeed.
  1409. //
  1410. // No fetches are triggered when TargetServerEntry is specified. In that
  1411. // case, we're only trying to connect to a specific server entry.
  1412. if (candidateServerEntryCount == 0 ||
  1413. time.Since(establishStartTime)-totalNetworkWaitDuration > workTime) &&
  1414. controller.config.TargetServerEntry == "" {
  1415. controller.triggerFetches()
  1416. }
  1417. // After a complete iteration of candidate servers, pause before iterating again.
  1418. // This helps avoid some busy wait loop conditions, and also allows some time for
  1419. // network conditions to change. Also allows for fetch remote to complete,
  1420. // in typical conditions (it isn't strictly necessary to wait for this, there will
  1421. // be more rounds if required).
  1422. p := controller.config.GetParameters().Get()
  1423. timeout := prng.JitterDuration(
  1424. p.Duration(parameters.EstablishTunnelPausePeriod),
  1425. p.Float(parameters.EstablishTunnelPausePeriodJitter))
  1426. p.Close()
  1427. timer := time.NewTimer(timeout)
  1428. select {
  1429. case <-timer.C:
  1430. // Retry iterating
  1431. case <-controller.establishCtx.Done():
  1432. timer.Stop()
  1433. break loop
  1434. }
  1435. timer.Stop()
  1436. iterator.Reset()
  1437. }
  1438. }
  1439. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  1440. // a connection to the tunnel server, and delivers the connected tunnel to a channel.
  1441. func (controller *Controller) establishTunnelWorker() {
  1442. defer controller.establishWaitGroup.Done()
  1443. loop:
  1444. for candidateServerEntry := range controller.candidateServerEntries {
  1445. // Note: don't receive from candidateServerEntries and isStopEstablishing
  1446. // in the same select, since we want to prioritize receiving the stop signal
  1447. if controller.isStopEstablishing() {
  1448. break loop
  1449. }
  1450. // There may already be a tunnel to this candidate. If so, skip it.
  1451. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  1452. continue
  1453. }
  1454. // upstreamProxyErrorCallback will post NoticeUpstreamProxyError when the
  1455. // tunnel dial fails due to an upstream proxy error. As the upstream proxy
  1456. // is user configured, the error message may need to be relayed to the user.
  1457. // As the callback may be invoked after establishment is over (e.g., if an
  1458. // initial dial isn't fully shutdown when ConnectTunnel returns; or a meek
  1459. // underlying TCP connection re-dial) don't access these variables
  1460. // directly.
  1461. callbackCandidateServerEntry := candidateServerEntry
  1462. callbackEstablishCtx := controller.establishCtx
  1463. upstreamProxyErrorCallback := func(err error) {
  1464. // Do not post the notice when overall establishment context is canceled or
  1465. // timed-out: the upstream proxy connection error is likely a result of the
  1466. // cancellation, and not a condition to be fixed by the user. In the case
  1467. // of meek underlying TCP connection re-dials, this condition will always
  1468. // be true; however in this case the initial dial succeeded with the
  1469. // current upstream proxy settings, so any upstream proxy error is
  1470. // transient.
  1471. if callbackEstablishCtx.Err() != nil {
  1472. return
  1473. }
  1474. // Another class of non-fatal upstream proxy error arises from proxies
  1475. // which limit permitted proxied ports. In this case, some tunnels may fail
  1476. // due to dial port, while others may eventually succeed. To avoid this
  1477. // class of errors, delay posting the notice. If the upstream proxy works,
  1478. // _some_ tunnel should connect. If the upstream proxy configuration is
  1479. // broken, the error should persist and eventually get posted.
  1480. p := controller.config.GetParameters().Get()
  1481. workerPoolSize := p.Int(parameters.ConnectionWorkerPoolSize)
  1482. minWaitDuration := p.Duration(parameters.UpstreamProxyErrorMinWaitDuration)
  1483. maxWaitDuration := p.Duration(parameters.UpstreamProxyErrorMaxWaitDuration)
  1484. p.Close()
  1485. controller.concurrentEstablishTunnelsMutex.Lock()
  1486. establishConnectTunnelCount := controller.establishConnectTunnelCount
  1487. controller.concurrentEstablishTunnelsMutex.Unlock()
  1488. // Delay UpstreamProxyErrorMinWaitDuration (excluding time spent waiting
  1489. // for network connectivity) and then until either
  1490. // UpstreamProxyErrorMaxWaitDuration has elapsed or, to post sooner if many
  1491. // candidates are failing, at least workerPoolSize tunnel connection
  1492. // attempts have completed. We infer that at least workerPoolSize
  1493. // candidates have completed by checking that at least 2*workerPoolSize
  1494. // candidates have started.
  1495. elapsedTime := time.Since(
  1496. callbackCandidateServerEntry.adjustedEstablishStartTime)
  1497. if elapsedTime < minWaitDuration ||
  1498. (elapsedTime < maxWaitDuration &&
  1499. establishConnectTunnelCount < 2*workerPoolSize) {
  1500. return
  1501. }
  1502. NoticeUpstreamProxyError(err)
  1503. }
  1504. // Select the tunnel protocol. The selection will be made at random
  1505. // from protocols supported by the server entry, optionally limited by
  1506. // LimitTunnelProtocols.
  1507. //
  1508. // When limiting concurrent resource intensive protocol connection
  1509. // workers, and at the limit, do not select resource intensive
  1510. // protocols since otherwise the candidate must be skipped.
  1511. //
  1512. // If at the limit and unabled to select a non-intensive protocol,
  1513. // skip the candidate entirely and move on to the next. Since
  1514. // candidates are shuffled it's likely that the next candidate is not
  1515. // intensive. In this case, a StaggerConnectionWorkersMilliseconds
  1516. // delay may still be incurred.
  1517. limitIntensiveConnectionWorkers := controller.config.GetParameters().Get().Int(
  1518. parameters.LimitIntensiveConnectionWorkers)
  1519. controller.concurrentEstablishTunnelsMutex.Lock()
  1520. excludeIntensive := false
  1521. if limitIntensiveConnectionWorkers > 0 &&
  1522. controller.concurrentIntensiveEstablishTunnels >= limitIntensiveConnectionWorkers {
  1523. excludeIntensive = true
  1524. }
  1525. canReplay := func(serverEntry *protocol.ServerEntry, replayProtocol string) bool {
  1526. return controller.protocolSelectionConstraints.canReplay(
  1527. controller.establishConnectTunnelCount,
  1528. excludeIntensive,
  1529. serverEntry,
  1530. replayProtocol)
  1531. }
  1532. selectProtocol := func(serverEntry *protocol.ServerEntry) (string, bool) {
  1533. return controller.protocolSelectionConstraints.selectProtocol(
  1534. controller.establishConnectTunnelCount,
  1535. excludeIntensive,
  1536. serverEntry)
  1537. }
  1538. // MakeDialParameters may return a replay instance, if the server
  1539. // entry has a previous, recent successful connection and
  1540. // tactics/config has not changed.
  1541. //
  1542. // In the first round -- and later rounds, with some probability -- of
  1543. // establishing, ServerEntryIterator will move potential replay candidates
  1544. // to the front of the iterator after the random shuffle, which greatly
  1545. // prioritizes previously successful servers for that round.
  1546. //
  1547. // As ServerEntryIterator does not unmarshal and validate replay
  1548. // candidate dial parameters, some potential replay candidates may
  1549. // have expired or otherwise ineligible dial parameters; in this case
  1550. // the candidate proceeds without replay.
  1551. //
  1552. // The ReplayCandidateCount tactic determines how many candidates may use
  1553. // replay. After ReplayCandidateCount candidates of any type, replay or no,
  1554. // replay is skipped. If ReplayCandidateCount exceeds the intial round,
  1555. // replay may still be performed but the iterator may no longer move
  1556. // potential replay server entries to the front. When ReplayCandidateCount
  1557. // is set to -1, unlimited candidates may use replay.
  1558. dialParams, err := MakeDialParameters(
  1559. controller.config,
  1560. upstreamProxyErrorCallback,
  1561. canReplay,
  1562. selectProtocol,
  1563. candidateServerEntry.serverEntry,
  1564. false,
  1565. controller.establishConnectTunnelCount,
  1566. int(atomic.LoadInt32(&controller.establishedTunnelsCount)))
  1567. if dialParams == nil || err != nil {
  1568. controller.concurrentEstablishTunnelsMutex.Unlock()
  1569. // dialParams is nil when the server does not support any protocol
  1570. // that remains after applying the LimitTunnelProtocols parameter
  1571. // and the excludeIntensive flag.
  1572. // Silently skip the candidate in this case. Otherwise, emit error.
  1573. if err != nil {
  1574. NoticeInfo("failed to select protocol for %s: %s",
  1575. candidateServerEntry.serverEntry.GetDiagnosticID(), err)
  1576. }
  1577. // Unblock other candidates immediately when server affinity
  1578. // candidate is skipped.
  1579. if candidateServerEntry.isServerAffinityCandidate {
  1580. close(controller.serverAffinityDoneBroadcast)
  1581. }
  1582. continue
  1583. }
  1584. // Increment establishConnectTunnelCount only after selectProtocol has
  1585. // succeeded to ensure InitialLimitTunnelProtocolsCandidateCount
  1586. // candidates use InitialLimitTunnelProtocols.
  1587. establishConnectTunnelCount := controller.establishConnectTunnelCount
  1588. controller.establishConnectTunnelCount += 1
  1589. isIntensive := protocol.TunnelProtocolIsResourceIntensive(dialParams.TunnelProtocol)
  1590. if isIntensive {
  1591. controller.concurrentIntensiveEstablishTunnels += 1
  1592. if controller.concurrentIntensiveEstablishTunnels > controller.peakConcurrentIntensiveEstablishTunnels {
  1593. controller.peakConcurrentIntensiveEstablishTunnels = controller.concurrentIntensiveEstablishTunnels
  1594. }
  1595. }
  1596. controller.concurrentEstablishTunnels += 1
  1597. if controller.concurrentEstablishTunnels > controller.peakConcurrentEstablishTunnels {
  1598. controller.peakConcurrentEstablishTunnels = controller.concurrentEstablishTunnels
  1599. }
  1600. controller.concurrentEstablishTunnelsMutex.Unlock()
  1601. // Apply stagger only now that we're past MakeDialParameters and
  1602. // protocol selection logic which may have caused the candidate to be
  1603. // skipped. The stagger logic delays dialing, and we don't want to
  1604. // incur that delay that when skipping.
  1605. //
  1606. // Locking staggerMutex serializes staggers, so that multiple workers
  1607. // don't simply sleep in parallel.
  1608. //
  1609. // The stagger is applied when establishConnectTunnelCount > 0 -- that
  1610. // is, for all but the first dial.
  1611. p := controller.config.GetParameters().Get()
  1612. staggerPeriod := p.Duration(parameters.StaggerConnectionWorkersPeriod)
  1613. staggerJitter := p.Float(parameters.StaggerConnectionWorkersJitter)
  1614. p.Close()
  1615. if establishConnectTunnelCount > 0 && staggerPeriod != 0 {
  1616. controller.staggerMutex.Lock()
  1617. timer := time.NewTimer(prng.JitterDuration(staggerPeriod, staggerJitter))
  1618. select {
  1619. case <-timer.C:
  1620. case <-controller.establishCtx.Done():
  1621. }
  1622. timer.Stop()
  1623. controller.staggerMutex.Unlock()
  1624. }
  1625. // ConnectTunnel will allocate significant memory, so first attempt to
  1626. // reclaim as much as possible.
  1627. DoGarbageCollection()
  1628. tunnel, err := ConnectTunnel(
  1629. controller.establishCtx,
  1630. controller.config,
  1631. candidateServerEntry.adjustedEstablishStartTime,
  1632. dialParams)
  1633. controller.concurrentEstablishTunnelsMutex.Lock()
  1634. if isIntensive {
  1635. controller.concurrentIntensiveEstablishTunnels -= 1
  1636. }
  1637. controller.concurrentEstablishTunnels -= 1
  1638. controller.concurrentEstablishTunnelsMutex.Unlock()
  1639. // Periodically emit memory metrics during the establishment cycle.
  1640. if !controller.isStopEstablishing() {
  1641. emitMemoryMetrics()
  1642. }
  1643. // Immediately reclaim memory allocated by the establishment. In the case
  1644. // of failure, first clear the reference to the tunnel. In the case of
  1645. // success, the garbage collection may still be effective as the initial
  1646. // phases of some protocols involve significant memory allocation that
  1647. // could now be reclaimed.
  1648. if err != nil {
  1649. tunnel = nil
  1650. }
  1651. DoGarbageCollection()
  1652. if err != nil {
  1653. // Unblock other candidates immediately when server affinity
  1654. // candidate fails.
  1655. if candidateServerEntry.isServerAffinityCandidate {
  1656. close(controller.serverAffinityDoneBroadcast)
  1657. }
  1658. // Before emitting error, check if establish interrupted, in which
  1659. // case the error is noise.
  1660. if controller.isStopEstablishing() {
  1661. break loop
  1662. }
  1663. NoticeInfo("failed to connect to %s: %s",
  1664. candidateServerEntry.serverEntry.GetDiagnosticID(), err)
  1665. continue
  1666. }
  1667. // Deliver connected tunnel.
  1668. // Don't block. Assumes the receiver has a buffer large enough for
  1669. // the number of desired tunnels. If there's no room, the tunnel must
  1670. // not be required so it's discarded.
  1671. select {
  1672. case controller.connectedTunnels <- tunnel:
  1673. default:
  1674. controller.discardTunnel(tunnel)
  1675. // Clear the reference to this discarded tunnel and immediately run
  1676. // a garbage collection to reclaim its memory.
  1677. tunnel = nil
  1678. DoGarbageCollection()
  1679. }
  1680. // Unblock other candidates only after delivering when
  1681. // server affinity candidate succeeds.
  1682. if candidateServerEntry.isServerAffinityCandidate {
  1683. close(controller.serverAffinityDoneBroadcast)
  1684. }
  1685. }
  1686. }
  1687. func (controller *Controller) isStopEstablishing() bool {
  1688. select {
  1689. case <-controller.establishCtx.Done():
  1690. return true
  1691. default:
  1692. }
  1693. return false
  1694. }