controller.go 70 KB

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