controller.go 80 KB

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