controller.go 82 KB

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