controller.go 77 KB

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