controller.go 80 KB

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