controller.go 78 KB

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