controller.go 71 KB

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