controller.go 81 KB

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