controller.go 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218
  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. // upstreamProxyErrorCallback will post NoticeUpstreamProxyError when the
  1631. // tunnel dial fails due to an upstream proxy error. As the upstream proxy
  1632. // is user configured, the error message may need to be relayed to the user.
  1633. // As the callback may be invoked after establishment is over (e.g., if an
  1634. // initial dial isn't fully shutdown when ConnectTunnel returns; or a meek
  1635. // underlying TCP connection re-dial) don't access these variables
  1636. // directly.
  1637. callbackCandidateServerEntry := candidateServerEntry
  1638. callbackEstablishCtx := controller.establishCtx
  1639. upstreamProxyErrorCallback := func(err error) {
  1640. // Do not post the notice when overall establishment context is canceled or
  1641. // timed-out: the upstream proxy connection error is likely a result of the
  1642. // cancellation, and not a condition to be fixed by the user. In the case
  1643. // of meek underlying TCP connection re-dials, this condition will always
  1644. // be true; however in this case the initial dial succeeded with the
  1645. // current upstream proxy settings, so any upstream proxy error is
  1646. // transient.
  1647. if callbackEstablishCtx.Err() != nil {
  1648. return
  1649. }
  1650. // Another class of non-fatal upstream proxy error arises from proxies
  1651. // which limit permitted proxied ports. In this case, some tunnels may fail
  1652. // due to dial port, while others may eventually succeed. To avoid this
  1653. // class of errors, delay posting the notice. If the upstream proxy works,
  1654. // _some_ tunnel should connect. If the upstream proxy configuration is
  1655. // broken, the error should persist and eventually get posted.
  1656. p := controller.config.GetParameters().Get()
  1657. workerPoolSize := p.Int(parameters.ConnectionWorkerPoolSize)
  1658. minWaitDuration := p.Duration(parameters.UpstreamProxyErrorMinWaitDuration)
  1659. maxWaitDuration := p.Duration(parameters.UpstreamProxyErrorMaxWaitDuration)
  1660. p.Close()
  1661. controller.concurrentEstablishTunnelsMutex.Lock()
  1662. establishConnectTunnelCount := controller.establishConnectTunnelCount
  1663. controller.concurrentEstablishTunnelsMutex.Unlock()
  1664. // Delay UpstreamProxyErrorMinWaitDuration (excluding time spent waiting
  1665. // for network connectivity) and then until either
  1666. // UpstreamProxyErrorMaxWaitDuration has elapsed or, to post sooner if many
  1667. // candidates are failing, at least workerPoolSize tunnel connection
  1668. // attempts have completed. We infer that at least workerPoolSize
  1669. // candidates have completed by checking that at least 2*workerPoolSize
  1670. // candidates have started.
  1671. elapsedTime := time.Since(
  1672. callbackCandidateServerEntry.adjustedEstablishStartTime)
  1673. if elapsedTime < minWaitDuration ||
  1674. (elapsedTime < maxWaitDuration &&
  1675. establishConnectTunnelCount < 2*workerPoolSize) {
  1676. return
  1677. }
  1678. NoticeUpstreamProxyError(err)
  1679. }
  1680. // Select the tunnel protocol. The selection will be made at random
  1681. // from protocols supported by the server entry, optionally limited by
  1682. // LimitTunnelProtocols.
  1683. //
  1684. // When limiting concurrent resource intensive protocol connection
  1685. // workers, and at the limit, do not select resource intensive
  1686. // protocols since otherwise the candidate must be skipped.
  1687. //
  1688. // If at the limit and unabled to select a non-intensive protocol,
  1689. // skip the candidate entirely and move on to the next. Since
  1690. // candidates are shuffled it's likely that the next candidate is not
  1691. // intensive. In this case, a StaggerConnectionWorkersMilliseconds
  1692. // delay may still be incurred.
  1693. limitIntensiveConnectionWorkers := controller.config.GetParameters().Get().Int(
  1694. parameters.LimitIntensiveConnectionWorkers)
  1695. controller.concurrentEstablishTunnelsMutex.Lock()
  1696. excludeIntensive := false
  1697. if limitIntensiveConnectionWorkers > 0 &&
  1698. controller.concurrentIntensiveEstablishTunnels >= limitIntensiveConnectionWorkers {
  1699. excludeIntensive = true
  1700. }
  1701. canReplay := func(serverEntry *protocol.ServerEntry, replayProtocol string) bool {
  1702. return controller.protocolSelectionConstraints.canReplay(
  1703. controller.establishConnectTunnelCount,
  1704. excludeIntensive,
  1705. serverEntry,
  1706. replayProtocol)
  1707. }
  1708. selectProtocol := func(serverEntry *protocol.ServerEntry) (string, bool) {
  1709. return controller.protocolSelectionConstraints.selectProtocol(
  1710. controller.establishConnectTunnelCount,
  1711. excludeIntensive,
  1712. serverEntry)
  1713. }
  1714. // MakeDialParameters may return a replay instance, if the server
  1715. // entry has a previous, recent successful connection and
  1716. // tactics/config has not changed.
  1717. //
  1718. // In the first round -- and later rounds, with some probability -- of
  1719. // establishing, ServerEntryIterator will move potential replay candidates
  1720. // to the front of the iterator after the random shuffle, which greatly
  1721. // prioritizes previously successful servers for that round.
  1722. //
  1723. // As ServerEntryIterator does not unmarshal and validate replay
  1724. // candidate dial parameters, some potential replay candidates may
  1725. // have expired or otherwise ineligible dial parameters; in this case
  1726. // the candidate proceeds without replay.
  1727. //
  1728. // The ReplayCandidateCount tactic determines how many candidates may use
  1729. // replay. After ReplayCandidateCount candidates of any type, replay or no,
  1730. // replay is skipped. If ReplayCandidateCount exceeds the intial round,
  1731. // replay may still be performed but the iterator may no longer move
  1732. // potential replay server entries to the front. When ReplayCandidateCount
  1733. // is set to -1, unlimited candidates may use replay.
  1734. dialParams, err := MakeDialParameters(
  1735. controller.config,
  1736. upstreamProxyErrorCallback,
  1737. canReplay,
  1738. selectProtocol,
  1739. candidateServerEntry.serverEntry,
  1740. false,
  1741. controller.establishConnectTunnelCount,
  1742. int(atomic.LoadInt32(&controller.establishedTunnelsCount)))
  1743. if dialParams == nil || err != nil {
  1744. controller.concurrentEstablishTunnelsMutex.Unlock()
  1745. // dialParams is nil when the server does not support any protocol
  1746. // that remains after applying the LimitTunnelProtocols parameter
  1747. // and the excludeIntensive flag.
  1748. // Silently skip the candidate in this case. Otherwise, emit error.
  1749. if err != nil {
  1750. NoticeInfo("failed to select protocol for %s: %v",
  1751. candidateServerEntry.serverEntry.GetDiagnosticID(),
  1752. errors.Trace(err))
  1753. }
  1754. // Unblock other candidates immediately when server affinity
  1755. // candidate is skipped.
  1756. if candidateServerEntry.isServerAffinityCandidate {
  1757. close(controller.serverAffinityDoneBroadcast)
  1758. }
  1759. continue
  1760. }
  1761. // Increment establishConnectTunnelCount only after selectProtocol has
  1762. // succeeded to ensure InitialLimitTunnelProtocolsCandidateCount
  1763. // candidates use InitialLimitTunnelProtocols.
  1764. establishConnectTunnelCount := controller.establishConnectTunnelCount
  1765. controller.establishConnectTunnelCount += 1
  1766. isIntensive := protocol.TunnelProtocolIsResourceIntensive(dialParams.TunnelProtocol)
  1767. if isIntensive {
  1768. controller.concurrentIntensiveEstablishTunnels += 1
  1769. if controller.concurrentIntensiveEstablishTunnels > controller.peakConcurrentIntensiveEstablishTunnels {
  1770. controller.peakConcurrentIntensiveEstablishTunnels = controller.concurrentIntensiveEstablishTunnels
  1771. }
  1772. }
  1773. controller.concurrentEstablishTunnels += 1
  1774. if controller.concurrentEstablishTunnels > controller.peakConcurrentEstablishTunnels {
  1775. controller.peakConcurrentEstablishTunnels = controller.concurrentEstablishTunnels
  1776. }
  1777. controller.concurrentEstablishTunnelsMutex.Unlock()
  1778. // Apply stagger only now that we're past MakeDialParameters and
  1779. // protocol selection logic which may have caused the candidate to be
  1780. // skipped. The stagger logic delays dialing, and we don't want to
  1781. // incur that delay that when skipping.
  1782. //
  1783. // Locking staggerMutex serializes staggers, so that multiple workers
  1784. // don't simply sleep in parallel.
  1785. //
  1786. // The stagger is applied when establishConnectTunnelCount > 0 -- that
  1787. // is, for all but the first dial.
  1788. p := controller.config.GetParameters().Get()
  1789. staggerPeriod := p.Duration(parameters.StaggerConnectionWorkersPeriod)
  1790. staggerJitter := p.Float(parameters.StaggerConnectionWorkersJitter)
  1791. p.Close()
  1792. if establishConnectTunnelCount > 0 && staggerPeriod != 0 {
  1793. controller.staggerMutex.Lock()
  1794. timer := time.NewTimer(prng.JitterDuration(staggerPeriod, staggerJitter))
  1795. select {
  1796. case <-timer.C:
  1797. case <-controller.establishCtx.Done():
  1798. }
  1799. timer.Stop()
  1800. controller.staggerMutex.Unlock()
  1801. }
  1802. // ConnectTunnel will allocate significant memory, so first attempt to
  1803. // reclaim as much as possible.
  1804. DoGarbageCollection()
  1805. tunnel, err := ConnectTunnel(
  1806. controller.establishCtx,
  1807. controller.config,
  1808. candidateServerEntry.adjustedEstablishStartTime,
  1809. dialParams)
  1810. controller.concurrentEstablishTunnelsMutex.Lock()
  1811. if isIntensive {
  1812. controller.concurrentIntensiveEstablishTunnels -= 1
  1813. }
  1814. controller.concurrentEstablishTunnels -= 1
  1815. controller.concurrentEstablishTunnelsMutex.Unlock()
  1816. // Periodically emit memory metrics during the establishment cycle.
  1817. if !controller.isStopEstablishing() {
  1818. emitMemoryMetrics()
  1819. }
  1820. // Immediately reclaim memory allocated by the establishment. In the case
  1821. // of failure, first clear the reference to the tunnel. In the case of
  1822. // success, the garbage collection may still be effective as the initial
  1823. // phases of some protocols involve significant memory allocation that
  1824. // could now be reclaimed.
  1825. if err != nil {
  1826. tunnel = nil
  1827. }
  1828. DoGarbageCollection()
  1829. if err != nil {
  1830. // Unblock other candidates immediately when server affinity
  1831. // candidate fails.
  1832. if candidateServerEntry.isServerAffinityCandidate {
  1833. close(controller.serverAffinityDoneBroadcast)
  1834. }
  1835. // Before emitting error, check if establish interrupted, in which
  1836. // case the error is noise.
  1837. if controller.isStopEstablishing() {
  1838. break loop
  1839. }
  1840. NoticeInfo("failed to connect to %s: %v",
  1841. candidateServerEntry.serverEntry.GetDiagnosticID(),
  1842. errors.Trace(err))
  1843. continue
  1844. }
  1845. // Deliver connected tunnel.
  1846. // Don't block. Assumes the receiver has a buffer large enough for
  1847. // the number of desired tunnels. If there's no room, the tunnel must
  1848. // not be required so it's discarded.
  1849. select {
  1850. case controller.connectedTunnels <- tunnel:
  1851. default:
  1852. controller.discardTunnel(tunnel)
  1853. // Clear the reference to this discarded tunnel and immediately run
  1854. // a garbage collection to reclaim its memory.
  1855. tunnel = nil
  1856. DoGarbageCollection()
  1857. }
  1858. // Unblock other candidates only after delivering when
  1859. // server affinity candidate succeeds.
  1860. if candidateServerEntry.isServerAffinityCandidate {
  1861. close(controller.serverAffinityDoneBroadcast)
  1862. }
  1863. }
  1864. }
  1865. func (controller *Controller) isStopEstablishing() bool {
  1866. select {
  1867. case <-controller.establishCtx.Done():
  1868. return true
  1869. default:
  1870. }
  1871. return false
  1872. }