controller.go 70 KB

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