controller.go 82 KB

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