controller.go 80 KB

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