controller.go 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  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. "errors"
  26. "fmt"
  27. "math/rand"
  28. "net"
  29. "sync"
  30. "time"
  31. "github.com/Psiphon-Inc/goarista/monotime"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  35. )
  36. // Controller is a tunnel lifecycle coordinator. It manages lists of servers to
  37. // connect to; establishes and monitors tunnels; and runs local proxies which
  38. // route traffic through the tunnels.
  39. type Controller struct {
  40. config *Config
  41. sessionId string
  42. componentFailureSignal chan struct{}
  43. shutdownBroadcast chan struct{}
  44. runWaitGroup *sync.WaitGroup
  45. connectedTunnels chan *Tunnel
  46. failedTunnels chan *Tunnel
  47. tunnelMutex sync.Mutex
  48. establishedOnce bool
  49. tunnels []*Tunnel
  50. nextTunnel int
  51. startedConnectedReporter bool
  52. isEstablishing bool
  53. concurrentEstablishTunnelsMutex sync.Mutex
  54. concurrentEstablishTunnels int
  55. concurrentMeekEstablishTunnels int
  56. peakConcurrentEstablishTunnels int
  57. peakConcurrentMeekEstablishTunnels int
  58. establishWaitGroup *sync.WaitGroup
  59. stopEstablishingBroadcast chan struct{}
  60. candidateServerEntries chan *candidateServerEntry
  61. establishPendingConns *common.Conns
  62. untunneledPendingConns *common.Conns
  63. untunneledDialConfig *DialConfig
  64. splitTunnelClassifier *SplitTunnelClassifier
  65. signalFetchCommonRemoteServerList chan struct{}
  66. signalFetchObfuscatedServerLists chan struct{}
  67. signalDownloadUpgrade chan string
  68. impairedProtocolClassification map[string]int
  69. signalReportConnected chan struct{}
  70. serverAffinityDoneBroadcast chan struct{}
  71. newClientVerificationPayload chan string
  72. packetTunnelClient *tun.Client
  73. packetTunnelTransport *PacketTunnelTransport
  74. }
  75. type candidateServerEntry struct {
  76. serverEntry *protocol.ServerEntry
  77. isServerAffinityCandidate bool
  78. adjustedEstablishStartTime monotime.Time
  79. }
  80. // NewController initializes a new controller.
  81. func NewController(config *Config) (controller *Controller, err error) {
  82. // Needed by regen, at least
  83. rand.Seed(int64(time.Now().Nanosecond()))
  84. // The session ID for the Psiphon server API is used across all
  85. // tunnels established by the controller.
  86. NoticeSessionId(config.SessionID)
  87. // untunneledPendingConns may be used to interrupt the fetch remote server list
  88. // request and other untunneled connection establishments. BindToDevice may be
  89. // used to exclude these requests and connection from VPN routing.
  90. // TODO: fetch remote server list and untunneled upgrade download should remove
  91. // their completed conns from untunneledPendingConns.
  92. untunneledPendingConns := new(common.Conns)
  93. untunneledDialConfig := &DialConfig{
  94. UpstreamProxyUrl: config.UpstreamProxyUrl,
  95. CustomHeaders: config.CustomHeaders,
  96. PendingConns: untunneledPendingConns,
  97. DeviceBinder: config.DeviceBinder,
  98. DnsServerGetter: config.DnsServerGetter,
  99. IPv6Synthesizer: config.IPv6Synthesizer,
  100. UseIndistinguishableTLS: config.UseIndistinguishableTLS,
  101. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  102. DeviceRegion: config.DeviceRegion,
  103. }
  104. controller = &Controller{
  105. config: config,
  106. sessionId: config.SessionID,
  107. // componentFailureSignal receives a signal from a component (including socks and
  108. // http local proxies) if they unexpectedly fail. Senders should not block.
  109. // Buffer allows at least one stop signal to be sent before there is a receiver.
  110. componentFailureSignal: make(chan struct{}, 1),
  111. shutdownBroadcast: make(chan struct{}),
  112. runWaitGroup: new(sync.WaitGroup),
  113. // connectedTunnels and failedTunnels buffer sizes are large enough to
  114. // receive full pools of tunnels without blocking. Senders should not block.
  115. connectedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  116. failedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  117. tunnels: make([]*Tunnel, 0),
  118. establishedOnce: false,
  119. startedConnectedReporter: false,
  120. isEstablishing: false,
  121. establishPendingConns: new(common.Conns),
  122. untunneledPendingConns: untunneledPendingConns,
  123. untunneledDialConfig: untunneledDialConfig,
  124. impairedProtocolClassification: make(map[string]int),
  125. // TODO: Add a buffer of 1 so we don't miss a signal while receiver is
  126. // starting? Trade-off is potential back-to-back fetch remotes. As-is,
  127. // establish will eventually signal another fetch remote.
  128. signalFetchCommonRemoteServerList: make(chan struct{}),
  129. signalFetchObfuscatedServerLists: make(chan struct{}),
  130. signalDownloadUpgrade: make(chan string),
  131. signalReportConnected: make(chan struct{}),
  132. // Buffer allows SetClientVerificationPayloadForActiveTunnels to submit one
  133. // new payload without blocking or dropping it.
  134. newClientVerificationPayload: make(chan string, 1),
  135. }
  136. controller.splitTunnelClassifier = NewSplitTunnelClassifier(config, controller)
  137. if config.PacketTunnelTunFileDescriptor > 0 {
  138. // Run a packet tunnel client. The lifetime of the tun.Client is the
  139. // lifetime of the Controller, so it exists across tunnel establishments
  140. // and reestablishments. The PacketTunnelTransport provides a layer
  141. // that presents a continuosuly existing transport to the tun.Client;
  142. // it's set to use new SSH channels after new SSH tunnel establishes.
  143. packetTunnelTransport := NewPacketTunnelTransport()
  144. packetTunnelClient, err := tun.NewClient(&tun.ClientConfig{
  145. Logger: NoticeCommonLogger(),
  146. TunFileDescriptor: config.PacketTunnelTunFileDescriptor,
  147. Transport: packetTunnelTransport,
  148. })
  149. if err != nil {
  150. return nil, common.ContextError(err)
  151. }
  152. controller.packetTunnelClient = packetTunnelClient
  153. controller.packetTunnelTransport = packetTunnelTransport
  154. }
  155. return controller, nil
  156. }
  157. // Run executes the controller. It launches components and then monitors
  158. // for a shutdown signal; after receiving the signal it shuts down the
  159. // controller.
  160. // The components include:
  161. // - the periodic remote server list fetcher
  162. // - the connected reporter
  163. // - the tunnel manager
  164. // - a local SOCKS proxy that port forwards through the pool of tunnels
  165. // - a local HTTP proxy that port forwards through the pool of tunnels
  166. func (controller *Controller) Run(shutdownBroadcast <-chan struct{}) {
  167. ReportAvailableRegions()
  168. // Start components
  169. // TODO: IPv6 support
  170. var listenIP string
  171. if controller.config.ListenInterface == "" {
  172. listenIP = "127.0.0.1"
  173. } else if controller.config.ListenInterface == "any" {
  174. listenIP = "0.0.0.0"
  175. } else {
  176. IPv4Address, _, err := common.GetInterfaceIPAddresses(controller.config.ListenInterface)
  177. if err == nil && IPv4Address == nil {
  178. err = fmt.Errorf("no IPv4 address for interface %s", controller.config.ListenInterface)
  179. }
  180. if err != nil {
  181. NoticeError("error getting listener IP: %s", err)
  182. return
  183. }
  184. listenIP = IPv4Address.String()
  185. }
  186. if !controller.config.DisableLocalSocksProxy {
  187. socksProxy, err := NewSocksProxy(controller.config, controller, listenIP)
  188. if err != nil {
  189. NoticeAlert("error initializing local SOCKS proxy: %s", err)
  190. return
  191. }
  192. defer socksProxy.Close()
  193. }
  194. if !controller.config.DisableLocalHTTPProxy {
  195. httpProxy, err := NewHttpProxy(
  196. controller.config, controller.untunneledDialConfig, controller, listenIP)
  197. if err != nil {
  198. NoticeAlert("error initializing local HTTP proxy: %s", err)
  199. return
  200. }
  201. defer httpProxy.Close()
  202. }
  203. if !controller.config.DisableRemoteServerListFetcher {
  204. retryPeriod := time.Duration(
  205. *controller.config.FetchRemoteServerListRetryPeriodSeconds) * time.Second
  206. if controller.config.RemoteServerListURLs != nil {
  207. controller.runWaitGroup.Add(1)
  208. go controller.remoteServerListFetcher(
  209. "common",
  210. FetchCommonRemoteServerList,
  211. controller.signalFetchCommonRemoteServerList,
  212. retryPeriod,
  213. FETCH_REMOTE_SERVER_LIST_STALE_PERIOD)
  214. }
  215. if controller.config.ObfuscatedServerListRootURLs != nil {
  216. controller.runWaitGroup.Add(1)
  217. go controller.remoteServerListFetcher(
  218. "obfuscated",
  219. FetchObfuscatedServerLists,
  220. controller.signalFetchObfuscatedServerLists,
  221. retryPeriod,
  222. FETCH_REMOTE_SERVER_LIST_STALE_PERIOD)
  223. }
  224. }
  225. if controller.config.UpgradeDownloadURLs != nil {
  226. controller.runWaitGroup.Add(1)
  227. go controller.upgradeDownloader()
  228. }
  229. /// Note: the connected reporter isn't started until a tunnel is
  230. // established
  231. controller.runWaitGroup.Add(1)
  232. go controller.runTunnels()
  233. if *controller.config.EstablishTunnelTimeoutSeconds != 0 {
  234. controller.runWaitGroup.Add(1)
  235. go controller.establishTunnelWatcher()
  236. }
  237. if controller.packetTunnelClient != nil {
  238. controller.packetTunnelClient.Start()
  239. }
  240. // Wait while running
  241. select {
  242. case <-shutdownBroadcast:
  243. NoticeInfo("controller shutdown by request")
  244. case <-controller.componentFailureSignal:
  245. NoticeAlert("controller shutdown due to component failure")
  246. }
  247. close(controller.shutdownBroadcast)
  248. if controller.packetTunnelClient != nil {
  249. controller.packetTunnelClient.Stop()
  250. }
  251. // Interrupts and stops establish workers blocking on
  252. // tunnel establishment network operations.
  253. controller.establishPendingConns.CloseAll()
  254. // Interrupts and stops workers blocking on untunneled
  255. // network operations. This includes fetch remote server
  256. // list and untunneled uprade download.
  257. // Note: this doesn't interrupt the final, untunneled status
  258. // requests started in operateTunnel after shutdownBroadcast.
  259. // This is by design -- we want to give these requests a short
  260. // timer period to succeed and deliver stats. These particular
  261. // requests opt out of untunneledPendingConns and use the
  262. // PSIPHON_API_SHUTDOWN_SERVER_TIMEOUT timeout (see
  263. // doUntunneledStatusRequest).
  264. controller.untunneledPendingConns.CloseAll()
  265. // Now with all workers signaled to stop and with all
  266. // blocking network operations interrupted, wait for
  267. // all workers to terminate.
  268. controller.runWaitGroup.Wait()
  269. controller.splitTunnelClassifier.Shutdown()
  270. NoticeInfo("exiting controller")
  271. NoticeExiting()
  272. }
  273. // SignalComponentFailure notifies the controller that an associated component has failed.
  274. // This will terminate the controller.
  275. func (controller *Controller) SignalComponentFailure() {
  276. select {
  277. case controller.componentFailureSignal <- *new(struct{}):
  278. default:
  279. }
  280. }
  281. // SetClientVerificationPayloadForActiveTunnels sets the client verification
  282. // payload that is to be sent in client verification requests to all established
  283. // tunnels.
  284. //
  285. // Client verification is used to verify that the client is a
  286. // valid Psiphon client, which will determine how the server treats
  287. // the client traffic. The proof-of-validity is platform-specific
  288. // and the payload is opaque to this function but assumed to be JSON.
  289. //
  290. // Since, in some cases, verification payload cannot be determined until
  291. // after tunnel-core starts, the payload cannot be simply specified in
  292. // the Config.
  293. //
  294. // SetClientVerificationPayloadForActiveTunnels will not block enqueuing a new verification
  295. // payload. One new payload can be enqueued, after which additional payloads
  296. // will be dropped if a payload is still enqueued.
  297. func (controller *Controller) SetClientVerificationPayloadForActiveTunnels(clientVerificationPayload string) {
  298. select {
  299. case controller.newClientVerificationPayload <- clientVerificationPayload:
  300. default:
  301. }
  302. }
  303. // remoteServerListFetcher fetches an out-of-band list of server entries
  304. // for more tunnel candidates. It fetches when signalled, with retries
  305. // on failure.
  306. func (controller *Controller) remoteServerListFetcher(
  307. name string,
  308. fetcher RemoteServerListFetcher,
  309. signal <-chan struct{},
  310. retryPeriod, stalePeriod time.Duration) {
  311. defer controller.runWaitGroup.Done()
  312. var lastFetchTime monotime.Time
  313. fetcherLoop:
  314. for {
  315. // Wait for a signal before fetching
  316. select {
  317. case <-signal:
  318. case <-controller.shutdownBroadcast:
  319. break fetcherLoop
  320. }
  321. // Skip fetch entirely (i.e., send no request at all, even when ETag would save
  322. // on response size) when a recent fetch was successful
  323. if lastFetchTime != 0 &&
  324. lastFetchTime.Add(stalePeriod).After(monotime.Now()) {
  325. continue
  326. }
  327. retryLoop:
  328. for attempt := 0; ; attempt++ {
  329. // Don't attempt to fetch while there is no network connectivity,
  330. // to avoid alert notice noise.
  331. if !WaitForNetworkConnectivity(
  332. controller.config.NetworkConnectivityChecker,
  333. controller.shutdownBroadcast) {
  334. break fetcherLoop
  335. }
  336. // Pick any active tunnel and make the next fetch attempt. If there's
  337. // no active tunnel, the untunneledDialConfig will be used.
  338. tunnel := controller.getNextActiveTunnel()
  339. err := fetcher(
  340. controller.config,
  341. attempt,
  342. tunnel,
  343. controller.untunneledDialConfig)
  344. if err == nil {
  345. lastFetchTime = monotime.Now()
  346. break retryLoop
  347. }
  348. NoticeAlert("failed to fetch %s remote server list: %s", name, err)
  349. timeout := time.After(retryPeriod)
  350. select {
  351. case <-timeout:
  352. case <-controller.shutdownBroadcast:
  353. break fetcherLoop
  354. }
  355. }
  356. }
  357. NoticeInfo("exiting %s remote server list fetcher", name)
  358. }
  359. // establishTunnelWatcher terminates the controller if a tunnel
  360. // has not been established in the configured time period. This
  361. // is regardless of how many tunnels are presently active -- meaning
  362. // that if an active tunnel was established and lost the controller
  363. // is left running (to re-establish).
  364. func (controller *Controller) establishTunnelWatcher() {
  365. defer controller.runWaitGroup.Done()
  366. timeout := time.After(
  367. time.Duration(*controller.config.EstablishTunnelTimeoutSeconds) * time.Second)
  368. select {
  369. case <-timeout:
  370. if !controller.hasEstablishedOnce() {
  371. NoticeAlert("failed to establish tunnel before timeout")
  372. controller.SignalComponentFailure()
  373. }
  374. case <-controller.shutdownBroadcast:
  375. }
  376. NoticeInfo("exiting establish tunnel watcher")
  377. }
  378. // connectedReporter sends periodic "connected" requests to the Psiphon API.
  379. // These requests are for server-side unique user stats calculation. See the
  380. // comment in DoConnectedRequest for a description of the request mechanism.
  381. // To ensure we don't over- or under-count unique users, only one connected
  382. // request is made across all simultaneous multi-tunnels; and the connected
  383. // request is repeated periodically for very long-lived tunnels.
  384. // The signalReportConnected mechanism is used to trigger another connected
  385. // request immediately after a reconnect.
  386. func (controller *Controller) connectedReporter() {
  387. defer controller.runWaitGroup.Done()
  388. loop:
  389. for {
  390. // Pick any active tunnel and make the next connected request. No error
  391. // is logged if there's no active tunnel, as that's not an unexpected condition.
  392. reported := false
  393. tunnel := controller.getNextActiveTunnel()
  394. if tunnel != nil {
  395. err := tunnel.serverContext.DoConnectedRequest()
  396. if err == nil {
  397. reported = true
  398. } else {
  399. NoticeAlert("failed to make connected request: %s", err)
  400. }
  401. }
  402. // Schedule the next connected request and wait.
  403. var duration time.Duration
  404. if reported {
  405. duration = PSIPHON_API_CONNECTED_REQUEST_PERIOD
  406. } else {
  407. duration = PSIPHON_API_CONNECTED_REQUEST_RETRY_PERIOD
  408. }
  409. timeout := time.After(duration)
  410. select {
  411. case <-controller.signalReportConnected:
  412. case <-timeout:
  413. // Make another connected request
  414. case <-controller.shutdownBroadcast:
  415. break loop
  416. }
  417. }
  418. NoticeInfo("exiting connected reporter")
  419. }
  420. func (controller *Controller) startOrSignalConnectedReporter() {
  421. // session is nil when DisableApi is set
  422. if controller.config.DisableApi {
  423. return
  424. }
  425. // Start the connected reporter after the first tunnel is established.
  426. // Concurrency note: only the runTunnels goroutine may access startedConnectedReporter.
  427. if !controller.startedConnectedReporter {
  428. controller.startedConnectedReporter = true
  429. controller.runWaitGroup.Add(1)
  430. go controller.connectedReporter()
  431. } else {
  432. select {
  433. case controller.signalReportConnected <- *new(struct{}):
  434. default:
  435. }
  436. }
  437. }
  438. // upgradeDownloader makes periodic attempts to complete a client upgrade
  439. // download. DownloadUpgrade() is resumable, so each attempt has potential for
  440. // getting closer to completion, even in conditions where the download or
  441. // tunnel is repeatedly interrupted.
  442. // An upgrade download is triggered by either a handshake response indicating
  443. // that a new version is available; or after failing to connect, in which case
  444. // it's useful to check, out-of-band, for an upgrade with new circumvention
  445. // capabilities.
  446. // Once the download operation completes successfully, the downloader exits
  447. // and is not run again: either there is not a newer version, or the upgrade
  448. // has been downloaded and is ready to be applied.
  449. // We're assuming that the upgrade will be applied and the entire system
  450. // restarted before another upgrade is to be downloaded.
  451. //
  452. // TODO: refactor upgrade downloader and remote server list fetcher to use
  453. // common code (including the resumable download routines).
  454. //
  455. func (controller *Controller) upgradeDownloader() {
  456. defer controller.runWaitGroup.Done()
  457. var lastDownloadTime monotime.Time
  458. downloadLoop:
  459. for {
  460. // Wait for a signal before downloading
  461. var handshakeVersion string
  462. select {
  463. case handshakeVersion = <-controller.signalDownloadUpgrade:
  464. case <-controller.shutdownBroadcast:
  465. break downloadLoop
  466. }
  467. // Unless handshake is explicitly advertizing a new version, skip
  468. // checking entirely when a recent download was successful.
  469. if handshakeVersion == "" &&
  470. lastDownloadTime != 0 &&
  471. lastDownloadTime.Add(DOWNLOAD_UPGRADE_STALE_PERIOD).After(monotime.Now()) {
  472. continue
  473. }
  474. retryLoop:
  475. for attempt := 0; ; attempt++ {
  476. // Don't attempt to download while there is no network connectivity,
  477. // to avoid alert notice noise.
  478. if !WaitForNetworkConnectivity(
  479. controller.config.NetworkConnectivityChecker,
  480. controller.shutdownBroadcast) {
  481. break downloadLoop
  482. }
  483. // Pick any active tunnel and make the next download attempt. If there's
  484. // no active tunnel, the untunneledDialConfig will be used.
  485. tunnel := controller.getNextActiveTunnel()
  486. err := DownloadUpgrade(
  487. controller.config,
  488. attempt,
  489. handshakeVersion,
  490. tunnel,
  491. controller.untunneledDialConfig)
  492. if err == nil {
  493. lastDownloadTime = monotime.Now()
  494. break retryLoop
  495. }
  496. NoticeAlert("failed to download upgrade: %s", err)
  497. timeout := time.After(
  498. time.Duration(*controller.config.DownloadUpgradeRetryPeriodSeconds) * time.Second)
  499. select {
  500. case <-timeout:
  501. case <-controller.shutdownBroadcast:
  502. break downloadLoop
  503. }
  504. }
  505. }
  506. NoticeInfo("exiting upgrade downloader")
  507. }
  508. // runTunnels is the controller tunnel management main loop. It starts and stops
  509. // establishing tunnels based on the target tunnel pool size and the current size
  510. // of the pool. Tunnels are established asynchronously using worker goroutines.
  511. //
  512. // When there are no server entries for the target region/protocol, the
  513. // establishCandidateGenerator will yield no candidates and wait before
  514. // trying again. In the meantime, a remote server entry fetch may supply
  515. // valid candidates.
  516. //
  517. // When a tunnel is established, it's added to the active pool. The tunnel's
  518. // operateTunnel goroutine monitors the tunnel.
  519. //
  520. // When a tunnel fails, it's removed from the pool and the establish process is
  521. // restarted to fill the pool.
  522. func (controller *Controller) runTunnels() {
  523. defer controller.runWaitGroup.Done()
  524. var clientVerificationPayload string
  525. // Start running
  526. controller.startEstablishing()
  527. loop:
  528. for {
  529. select {
  530. case failedTunnel := <-controller.failedTunnels:
  531. NoticeAlert("tunnel failed: %s", failedTunnel.serverEntry.IpAddress)
  532. controller.terminateTunnel(failedTunnel)
  533. // Note: we make this extra check to ensure the shutdown signal takes priority
  534. // and that we do not start establishing. Critically, startEstablishing() calls
  535. // establishPendingConns.Reset() which clears the closed flag in
  536. // establishPendingConns; this causes the pendingConns.Add() within
  537. // interruptibleTCPDial to succeed instead of aborting, and the result
  538. // is that it's possible for establish goroutines to run all the way through
  539. // NewServerContext before being discarded... delaying shutdown.
  540. select {
  541. case <-controller.shutdownBroadcast:
  542. break loop
  543. default:
  544. }
  545. controller.classifyImpairedProtocol(failedTunnel)
  546. // Clear the reference to this tunnel before calling startEstablishing,
  547. // which will invoke a garbage collection.
  548. failedTunnel = nil
  549. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing,
  550. // which reference controller.isEstablishing.
  551. controller.startEstablishing()
  552. case connectedTunnel := <-controller.connectedTunnels:
  553. if controller.isImpairedProtocol(connectedTunnel.protocol) {
  554. // Protocol was classified as impaired while this tunnel established.
  555. // This is most likely to occur with TunnelPoolSize > 0. We log the
  556. // event but take no action. Discarding the tunnel would break the
  557. // impaired logic unless we did that (a) only if there are other
  558. // unimpaired protocols; (b) only during the first iteration of the
  559. // ESTABLISH_TUNNEL_WORK_TIME loop. By not discarding here, a true
  560. // impaired protocol may require an extra reconnect.
  561. NoticeAlert("connected tunnel with impaired protocol: %s", connectedTunnel.protocol)
  562. }
  563. // Tunnel establishment has two phases: connection and activation.
  564. //
  565. // Connection is run concurrently by the establishTunnelWorkers, to minimize
  566. // delay when it's not yet known which server and protocol will be available
  567. // and unblocked.
  568. //
  569. // Activation is run serially, here, to minimize the overhead of making a
  570. // handshake request and starting the operateTunnel management worker for a
  571. // tunnel which may be discarded.
  572. //
  573. // When the active tunnel will complete establishment, establishment is
  574. // stopped before activation. This interrupts all connecting tunnels and
  575. // garbage collects their memory. The purpose is to minimize memory
  576. // pressure when the handshake request is made. In the unlikely case that the
  577. // handshake fails, establishment is restarted.
  578. //
  579. // Any delays in stopEstablishing will delay the handshake for the last
  580. // active tunnel.
  581. //
  582. // In the typical case of TunnelPoolSize of 1, only a single handshake is
  583. // performed and the homepages notices file, when used, will not be modifed
  584. // after the NoticeTunnels(1) [i.e., connected] until NoticeTunnels(0) [i.e.,
  585. // disconnected]. For TunnelPoolSize > 1, serial handshakes only ensures that
  586. // each set of emitted NoticeHomepages is contiguous.
  587. active, outstanding := controller.numTunnels()
  588. discardTunnel := (outstanding <= 0)
  589. isFirstTunnel := (active == 0)
  590. isLastTunnel := (outstanding == 1)
  591. if !discardTunnel {
  592. if isLastTunnel {
  593. controller.stopEstablishing()
  594. }
  595. // Call connectedTunnel.Activate in a goroutine, as it blocks on a network
  596. // operation and would block shutdown. If the shutdown signal is received,
  597. // discard the tunnel, which will interrupt the handshake request that may
  598. // be blocking Activate.
  599. activatedTunnelResult := make(chan error)
  600. go func() {
  601. activatedTunnelResult <- connectedTunnel.Activate(controller)
  602. }()
  603. var err error
  604. select {
  605. case err = <-activatedTunnelResult:
  606. case <-controller.shutdownBroadcast:
  607. controller.discardTunnel(connectedTunnel)
  608. // Await the interrupted goroutine.
  609. <-activatedTunnelResult
  610. break loop
  611. }
  612. if err != nil {
  613. NoticeAlert("failed to activate %s: %s", connectedTunnel.serverEntry.IpAddress, err)
  614. discardTunnel = true
  615. } else {
  616. // It's unlikely that registerTunnel will fail, since only this goroutine
  617. // calls registerTunnel -- and after checking numTunnels; so failure is not
  618. // expected.
  619. if !controller.registerTunnel(connectedTunnel) {
  620. NoticeAlert("failed to register %s: %s", connectedTunnel.serverEntry.IpAddress)
  621. discardTunnel = true
  622. }
  623. }
  624. // May need to replace this tunnel
  625. if isLastTunnel && discardTunnel {
  626. controller.startEstablishing()
  627. }
  628. }
  629. if discardTunnel {
  630. // Already fully established, so discard.
  631. controller.discardTunnel(connectedTunnel)
  632. // Clear the reference to this discarded tunnel and immediately run
  633. // a garbage collection to reclaim its memory.
  634. connectedTunnel = nil
  635. aggressiveGarbageCollection()
  636. // Skip the rest of this case
  637. break
  638. }
  639. NoticeActiveTunnel(
  640. connectedTunnel.serverEntry.IpAddress,
  641. connectedTunnel.protocol,
  642. connectedTunnel.serverEntry.SupportsSSHAPIRequests())
  643. if isFirstTunnel {
  644. // The split tunnel classifier is started once the first tunnel is
  645. // established. This first tunnel is passed in to be used to make
  646. // the routes data request.
  647. // A long-running controller may run while the host device is present
  648. // in different regions. In this case, we want the split tunnel logic
  649. // to switch to routes for new regions and not classify traffic based
  650. // on routes installed for older regions.
  651. // We assume that when regions change, the host network will also
  652. // change, and so all tunnels will fail and be re-established. Under
  653. // that assumption, the classifier will be re-Start()-ed here when
  654. // the region has changed.
  655. controller.splitTunnelClassifier.Start(connectedTunnel)
  656. // Signal a connected request on each 1st tunnel establishment. For
  657. // multi-tunnels, the session is connected as long as at least one
  658. // tunnel is established.
  659. controller.startOrSignalConnectedReporter()
  660. // If the handshake indicated that a new client version is available,
  661. // trigger an upgrade download.
  662. // Note: serverContext is nil when DisableApi is set
  663. if connectedTunnel.serverContext != nil &&
  664. connectedTunnel.serverContext.clientUpgradeVersion != "" {
  665. handshakeVersion := connectedTunnel.serverContext.clientUpgradeVersion
  666. select {
  667. case controller.signalDownloadUpgrade <- handshakeVersion:
  668. default:
  669. }
  670. }
  671. }
  672. // Set the new tunnel as the transport for the packet tunnel. The packet tunnel
  673. // client remains up when reestablishing, but no packets are relayed while there
  674. // is no connected tunnel. UseTunnel will establish a new packet tunnel SSH
  675. // channel over the new SSH tunnel and configure the packet tunnel client to use
  676. // the new SSH channel as its transport.
  677. //
  678. // Note: as is, this logic is suboptimal for TunnelPoolSize > 1, as this would
  679. // continuously initialize new packet tunnel sessions for each established
  680. // server. For now, config validation requires TunnelPoolSize == 1 when
  681. // the packet tunnel is used.
  682. if controller.packetTunnelTransport != nil {
  683. controller.packetTunnelTransport.UseTunnel(connectedTunnel)
  684. }
  685. // TODO: design issue -- might not be enough server entries with region/caps to ever fill tunnel slots;
  686. // possible solution is establish target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  687. if controller.isFullyEstablished() {
  688. controller.stopEstablishing()
  689. }
  690. case clientVerificationPayload = <-controller.newClientVerificationPayload:
  691. controller.setClientVerificationPayloadForActiveTunnels(clientVerificationPayload)
  692. case <-controller.shutdownBroadcast:
  693. break loop
  694. }
  695. }
  696. // Stop running
  697. controller.stopEstablishing()
  698. controller.terminateAllTunnels()
  699. // Drain tunnel channels
  700. close(controller.connectedTunnels)
  701. for tunnel := range controller.connectedTunnels {
  702. controller.discardTunnel(tunnel)
  703. }
  704. close(controller.failedTunnels)
  705. for tunnel := range controller.failedTunnels {
  706. controller.discardTunnel(tunnel)
  707. }
  708. NoticeInfo("exiting run tunnels")
  709. }
  710. // TerminateNextActiveTunnel is a support routine for
  711. // test code that must terminate the active tunnel and
  712. // restart establishing. This function is not guaranteed
  713. // to be safe for use in other cases.
  714. func (controller *Controller) TerminateNextActiveTunnel() {
  715. tunnel := controller.getNextActiveTunnel()
  716. if tunnel != nil {
  717. controller.SignalTunnelFailure(tunnel)
  718. NoticeInfo("terminated tunnel: %s", tunnel.serverEntry.IpAddress)
  719. }
  720. }
  721. // classifyImpairedProtocol tracks "impaired" protocol classifications for failed
  722. // tunnels. A protocol is classified as impaired if a tunnel using that protocol
  723. // fails, repeatedly, shortly after the start of the connection. During tunnel
  724. // establishment, impaired protocols are briefly skipped.
  725. //
  726. // One purpose of this measure is to defend against an attack where the adversary,
  727. // for example, tags an OSSH TCP connection as an "unidentified" protocol; allows
  728. // it to connect; but then kills the underlying TCP connection after a short time.
  729. // Since OSSH has less latency than other protocols that may bypass an "unidentified"
  730. // filter, these other protocols might never be selected for use.
  731. //
  732. // Concurrency note: only the runTunnels() goroutine may call classifyImpairedProtocol
  733. func (controller *Controller) classifyImpairedProtocol(failedTunnel *Tunnel) {
  734. if failedTunnel.establishedTime.Add(IMPAIRED_PROTOCOL_CLASSIFICATION_DURATION).After(monotime.Now()) {
  735. controller.impairedProtocolClassification[failedTunnel.protocol] += 1
  736. } else {
  737. controller.impairedProtocolClassification[failedTunnel.protocol] = 0
  738. }
  739. // Reset classification once all known protocols are classified as impaired, as
  740. // there is now no way to proceed with only unimpaired protocols. The network
  741. // situation (or attack) resulting in classification may not be protocol-specific.
  742. //
  743. // Note: with controller.config.TunnelProtocol set, this will always reset once
  744. // that protocol has reached IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD.
  745. if CountNonImpairedProtocols(
  746. controller.config.EgressRegion,
  747. controller.config.TunnelProtocol,
  748. controller.getImpairedProtocols()) == 0 {
  749. controller.impairedProtocolClassification = make(map[string]int)
  750. }
  751. }
  752. // getImpairedProtocols returns a list of protocols that have sufficient
  753. // classifications to be considered impaired protocols.
  754. //
  755. // Concurrency note: only the runTunnels() goroutine may call getImpairedProtocols
  756. func (controller *Controller) getImpairedProtocols() []string {
  757. NoticeImpairedProtocolClassification(controller.impairedProtocolClassification)
  758. impairedProtocols := make([]string, 0)
  759. for protocol, count := range controller.impairedProtocolClassification {
  760. if count >= IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD {
  761. impairedProtocols = append(impairedProtocols, protocol)
  762. }
  763. }
  764. return impairedProtocols
  765. }
  766. // isImpairedProtocol checks if the specified protocol is classified as impaired.
  767. //
  768. // Concurrency note: only the runTunnels() goroutine may call isImpairedProtocol
  769. func (controller *Controller) isImpairedProtocol(protocol string) bool {
  770. count, ok := controller.impairedProtocolClassification[protocol]
  771. return ok && count >= IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD
  772. }
  773. // SignalSeededNewSLOK implements the TunnelOwner interface. This function
  774. // is called by Tunnel.operateTunnel when the tunnel has received a new,
  775. // previously unknown SLOK from the server. The Controller triggers an OSL
  776. // fetch, as the new SLOK may be sufficient to access new OSLs.
  777. func (controller *Controller) SignalSeededNewSLOK() {
  778. select {
  779. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  780. default:
  781. }
  782. }
  783. // SignalTunnelFailure implements the TunnelOwner interface. This function
  784. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  785. // has failed. The Controller will signal runTunnels to create a new
  786. // tunnel and/or remove the tunnel from the list of active tunnels.
  787. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  788. // Don't block. Assumes the receiver has a buffer large enough for
  789. // the typical number of operated tunnels. In case there's no room,
  790. // terminate the tunnel (runTunnels won't get a signal in this case,
  791. // but the tunnel will be removed from the list of active tunnels).
  792. select {
  793. case controller.failedTunnels <- tunnel:
  794. default:
  795. controller.terminateTunnel(tunnel)
  796. }
  797. }
  798. // discardTunnel disposes of a successful connection that is no longer required.
  799. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  800. NoticeInfo("discard tunnel: %s", tunnel.serverEntry.IpAddress)
  801. // TODO: not calling PromoteServerEntry, since that would rank the
  802. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  803. // be promoted (since it connects), but with lower rank than all active
  804. // tunnels?
  805. tunnel.Close(true)
  806. }
  807. // registerTunnel adds the connected tunnel to the pool of active tunnels
  808. // which are candidates for port forwarding. Returns true if the pool has an
  809. // empty slot and false if the pool is full (caller should discard the tunnel).
  810. func (controller *Controller) registerTunnel(tunnel *Tunnel) bool {
  811. controller.tunnelMutex.Lock()
  812. defer controller.tunnelMutex.Unlock()
  813. if len(controller.tunnels) >= controller.config.TunnelPoolSize {
  814. return false
  815. }
  816. // Perform a final check just in case we've established
  817. // a duplicate connection.
  818. for _, activeTunnel := range controller.tunnels {
  819. if activeTunnel.serverEntry.IpAddress == tunnel.serverEntry.IpAddress {
  820. NoticeAlert("duplicate tunnel: %s", tunnel.serverEntry.IpAddress)
  821. return false
  822. }
  823. }
  824. controller.establishedOnce = true
  825. controller.tunnels = append(controller.tunnels, tunnel)
  826. NoticeTunnels(len(controller.tunnels))
  827. // Promote this successful tunnel to first rank so it's one
  828. // of the first candidates next time establish runs.
  829. // Connecting to a TargetServerEntry does not change the
  830. // ranking.
  831. if controller.config.TargetServerEntry == "" {
  832. PromoteServerEntry(tunnel.serverEntry.IpAddress)
  833. }
  834. return true
  835. }
  836. // hasEstablishedOnce indicates if at least one active tunnel has
  837. // been established up to this point. This is regardeless of how many
  838. // tunnels are presently active.
  839. func (controller *Controller) hasEstablishedOnce() bool {
  840. controller.tunnelMutex.Lock()
  841. defer controller.tunnelMutex.Unlock()
  842. return controller.establishedOnce
  843. }
  844. // isFullyEstablished indicates if the pool of active tunnels is full.
  845. func (controller *Controller) isFullyEstablished() bool {
  846. controller.tunnelMutex.Lock()
  847. defer controller.tunnelMutex.Unlock()
  848. return len(controller.tunnels) >= controller.config.TunnelPoolSize
  849. }
  850. // numTunnels returns the number of active and outstanding tunnels.
  851. // Oustanding is the number of tunnels required to fill the pool of
  852. // active tunnels.
  853. func (controller *Controller) numTunnels() (int, int) {
  854. controller.tunnelMutex.Lock()
  855. defer controller.tunnelMutex.Unlock()
  856. active := len(controller.tunnels)
  857. outstanding := controller.config.TunnelPoolSize - len(controller.tunnels)
  858. return active, outstanding
  859. }
  860. // terminateTunnel removes a tunnel from the pool of active tunnels
  861. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  862. // is adjusted as required.
  863. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  864. controller.tunnelMutex.Lock()
  865. defer controller.tunnelMutex.Unlock()
  866. for index, activeTunnel := range controller.tunnels {
  867. if tunnel == activeTunnel {
  868. controller.tunnels = append(
  869. controller.tunnels[:index], controller.tunnels[index+1:]...)
  870. if controller.nextTunnel > index {
  871. controller.nextTunnel--
  872. }
  873. if controller.nextTunnel >= len(controller.tunnels) {
  874. controller.nextTunnel = 0
  875. }
  876. activeTunnel.Close(false)
  877. NoticeTunnels(len(controller.tunnels))
  878. break
  879. }
  880. }
  881. }
  882. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  883. // This is used when shutting down the controller.
  884. func (controller *Controller) terminateAllTunnels() {
  885. controller.tunnelMutex.Lock()
  886. defer controller.tunnelMutex.Unlock()
  887. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  888. // may take a few seconds to send a final status request. We only want
  889. // to wait as long as the single slowest tunnel.
  890. closeWaitGroup := new(sync.WaitGroup)
  891. closeWaitGroup.Add(len(controller.tunnels))
  892. for _, activeTunnel := range controller.tunnels {
  893. tunnel := activeTunnel
  894. go func() {
  895. defer closeWaitGroup.Done()
  896. tunnel.Close(false)
  897. }()
  898. }
  899. closeWaitGroup.Wait()
  900. controller.tunnels = make([]*Tunnel, 0)
  901. controller.nextTunnel = 0
  902. NoticeTunnels(len(controller.tunnels))
  903. }
  904. // getNextActiveTunnel returns the next tunnel from the pool of active
  905. // tunnels. Currently, tunnel selection order is simple round-robin.
  906. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  907. controller.tunnelMutex.Lock()
  908. defer controller.tunnelMutex.Unlock()
  909. for i := len(controller.tunnels); i > 0; i-- {
  910. tunnel = controller.tunnels[controller.nextTunnel]
  911. controller.nextTunnel =
  912. (controller.nextTunnel + 1) % len(controller.tunnels)
  913. return tunnel
  914. }
  915. return nil
  916. }
  917. // isActiveTunnelServerEntry is used to check if there's already
  918. // an existing tunnel to a candidate server.
  919. func (controller *Controller) isActiveTunnelServerEntry(
  920. serverEntry *protocol.ServerEntry) bool {
  921. controller.tunnelMutex.Lock()
  922. defer controller.tunnelMutex.Unlock()
  923. for _, activeTunnel := range controller.tunnels {
  924. if activeTunnel.serverEntry.IpAddress == serverEntry.IpAddress {
  925. return true
  926. }
  927. }
  928. return false
  929. }
  930. // setClientVerificationPayloadForActiveTunnels triggers the client verification
  931. // request for all active tunnels.
  932. func (controller *Controller) setClientVerificationPayloadForActiveTunnels(
  933. clientVerificationPayload string) {
  934. controller.tunnelMutex.Lock()
  935. defer controller.tunnelMutex.Unlock()
  936. for _, activeTunnel := range controller.tunnels {
  937. activeTunnel.SetClientVerificationPayload(clientVerificationPayload)
  938. }
  939. }
  940. // Dial selects an active tunnel and establishes a port forward
  941. // connection through the selected tunnel. Failure to connect is considered
  942. // a port forward failure, for the purpose of monitoring tunnel health.
  943. func (controller *Controller) Dial(
  944. remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error) {
  945. tunnel := controller.getNextActiveTunnel()
  946. if tunnel == nil {
  947. return nil, common.ContextError(errors.New("no active tunnels"))
  948. }
  949. // Perform split tunnel classification when feature is enabled, and if the remote
  950. // address is classified as untunneled, dial directly.
  951. if !alwaysTunnel && controller.config.SplitTunnelDnsServer != "" {
  952. host, _, err := net.SplitHostPort(remoteAddr)
  953. if err != nil {
  954. return nil, common.ContextError(err)
  955. }
  956. // Note: a possible optimization, when split tunnel is active and IsUntunneled performs
  957. // a DNS resolution in order to make its classification, is to reuse that IP address in
  958. // the following Dials so they do not need to make their own resolutions. However, the
  959. // way this is currently implemented ensures that, e.g., DNS geo load balancing occurs
  960. // relative to the outbound network.
  961. if controller.splitTunnelClassifier.IsUntunneled(host) {
  962. // TODO: track downstreamConn and close it when the DialTCP conn closes, as with tunnel.Dial conns?
  963. return DialTCP(remoteAddr, controller.untunneledDialConfig)
  964. }
  965. }
  966. tunneledConn, err := tunnel.Dial(remoteAddr, alwaysTunnel, downstreamConn)
  967. if err != nil {
  968. return nil, common.ContextError(err)
  969. }
  970. return tunneledConn, nil
  971. }
  972. // startEstablishing creates a pool of worker goroutines which will
  973. // attempt to establish tunnels to candidate servers. The candidates
  974. // are generated by another goroutine.
  975. func (controller *Controller) startEstablishing() {
  976. if controller.isEstablishing {
  977. return
  978. }
  979. NoticeInfo("start establishing")
  980. controller.concurrentEstablishTunnelsMutex.Lock()
  981. controller.concurrentEstablishTunnels = 0
  982. controller.concurrentMeekEstablishTunnels = 0
  983. controller.peakConcurrentEstablishTunnels = 0
  984. controller.peakConcurrentMeekEstablishTunnels = 0
  985. controller.concurrentEstablishTunnelsMutex.Unlock()
  986. aggressiveGarbageCollection()
  987. emitMemoryMetrics()
  988. controller.isEstablishing = true
  989. controller.establishWaitGroup = new(sync.WaitGroup)
  990. controller.stopEstablishingBroadcast = make(chan struct{})
  991. controller.candidateServerEntries = make(chan *candidateServerEntry)
  992. controller.establishPendingConns.Reset()
  993. // The server affinity mechanism attempts to favor the previously
  994. // used server when reconnecting. This is beneficial for user
  995. // applications which expect consistency in user IP address (for
  996. // example, a web site which prompts for additional user
  997. // authentication when the IP address changes).
  998. //
  999. // Only the very first server, as determined by
  1000. // datastore.PromoteServerEntry(), is the server affinity candidate.
  1001. // Concurrent connections attempts to many servers are launched
  1002. // without delay, in case the affinity server connection fails.
  1003. // While the affinity server connection is outstanding, when any
  1004. // other connection is established, there is a short grace period
  1005. // delay before delivering the established tunnel; this allows some
  1006. // time for the affinity server connection to succeed first.
  1007. // When the affinity server connection fails, any other established
  1008. // tunnel is registered without delay.
  1009. //
  1010. // Note: the establishTunnelWorker that receives the affinity
  1011. // candidate is solely resonsible for closing
  1012. // controller.serverAffinityDoneBroadcast.
  1013. //
  1014. // Note: if config.EgressRegion or config.TunnelProtocol has changed
  1015. // since the top server was promoted, the first server may not actually
  1016. // be the last connected server.
  1017. // TODO: should not favor the first server in this case
  1018. controller.serverAffinityDoneBroadcast = make(chan struct{})
  1019. for i := 0; i < controller.config.ConnectionWorkerPoolSize; i++ {
  1020. controller.establishWaitGroup.Add(1)
  1021. go controller.establishTunnelWorker()
  1022. }
  1023. controller.establishWaitGroup.Add(1)
  1024. go controller.establishCandidateGenerator(
  1025. controller.getImpairedProtocols())
  1026. }
  1027. // stopEstablishing signals the establish goroutines to stop and waits
  1028. // for the group to halt. pendingConns is used to interrupt any worker
  1029. // blocked on a socket connect.
  1030. func (controller *Controller) stopEstablishing() {
  1031. if !controller.isEstablishing {
  1032. return
  1033. }
  1034. NoticeInfo("stop establishing")
  1035. close(controller.stopEstablishingBroadcast)
  1036. // Note: interruptibleTCPClose doesn't really interrupt socket connects
  1037. // and may leave goroutines running for a time after the Wait call.
  1038. controller.establishPendingConns.CloseAll()
  1039. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  1040. // (as it may be sending to that channel).
  1041. controller.establishWaitGroup.Wait()
  1042. NoticeInfo("stopped establishing")
  1043. controller.isEstablishing = false
  1044. controller.establishWaitGroup = nil
  1045. controller.stopEstablishingBroadcast = nil
  1046. controller.candidateServerEntries = nil
  1047. controller.serverAffinityDoneBroadcast = nil
  1048. controller.concurrentEstablishTunnelsMutex.Lock()
  1049. peakConcurrent := controller.peakConcurrentEstablishTunnels
  1050. peakConcurrentMeek := controller.peakConcurrentMeekEstablishTunnels
  1051. controller.concurrentEstablishTunnels = 0
  1052. controller.concurrentMeekEstablishTunnels = 0
  1053. controller.peakConcurrentEstablishTunnels = 0
  1054. controller.peakConcurrentMeekEstablishTunnels = 0
  1055. controller.concurrentEstablishTunnelsMutex.Unlock()
  1056. NoticeInfo("peak concurrent establish tunnels: %d", peakConcurrent)
  1057. NoticeInfo("peak concurrent meek establish tunnels: %d", peakConcurrentMeek)
  1058. emitMemoryMetrics()
  1059. standardGarbageCollection()
  1060. }
  1061. // establishCandidateGenerator populates the candidate queue with server entries
  1062. // from the data store. Server entries are iterated in rank order, so that promoted
  1063. // servers with higher rank are priority candidates.
  1064. func (controller *Controller) establishCandidateGenerator(impairedProtocols []string) {
  1065. defer controller.establishWaitGroup.Done()
  1066. defer close(controller.candidateServerEntries)
  1067. // establishStartTime is used to calculate and report the
  1068. // client's tunnel establishment duration.
  1069. //
  1070. // networkWaitDuration is the elapsed time spent waiting
  1071. // for network connectivity. This duration will be excluded
  1072. // from reported tunnel establishment duration.
  1073. establishStartTime := monotime.Now()
  1074. var networkWaitDuration time.Duration
  1075. iterator, err := NewServerEntryIterator(controller.config)
  1076. if err != nil {
  1077. NoticeAlert("failed to iterate over candidates: %s", err)
  1078. controller.SignalComponentFailure()
  1079. return
  1080. }
  1081. defer iterator.Close()
  1082. isServerAffinityCandidate := true
  1083. // TODO: reconcile server affinity scheme with multi-tunnel mode
  1084. if controller.config.TunnelPoolSize > 1 {
  1085. isServerAffinityCandidate = false
  1086. close(controller.serverAffinityDoneBroadcast)
  1087. }
  1088. loop:
  1089. // Repeat until stopped
  1090. for i := 0; ; i++ {
  1091. networkWaitStartTime := monotime.Now()
  1092. if !WaitForNetworkConnectivity(
  1093. controller.config.NetworkConnectivityChecker,
  1094. controller.stopEstablishingBroadcast,
  1095. controller.shutdownBroadcast) {
  1096. break loop
  1097. }
  1098. networkWaitDuration += monotime.Since(networkWaitStartTime)
  1099. // Send each iterator server entry to the establish workers
  1100. startTime := monotime.Now()
  1101. for {
  1102. serverEntry, err := iterator.Next()
  1103. if err != nil {
  1104. NoticeAlert("failed to get next candidate: %s", err)
  1105. controller.SignalComponentFailure()
  1106. break loop
  1107. }
  1108. if serverEntry == nil {
  1109. // Completed this iteration
  1110. break
  1111. }
  1112. if controller.config.TargetApiProtocol == protocol.PSIPHON_SSH_API_PROTOCOL &&
  1113. !serverEntry.SupportsSSHAPIRequests() {
  1114. continue
  1115. }
  1116. // Disable impaired protocols. This is only done for the
  1117. // first iteration of the ESTABLISH_TUNNEL_WORK_TIME
  1118. // loop since (a) one iteration should be sufficient to
  1119. // evade the attack; (b) there's a good chance of false
  1120. // positives (such as short tunnel durations due to network
  1121. // hopping on a mobile device).
  1122. // The edited serverEntry is temporary copy which is not
  1123. // stored or reused.
  1124. if i == 0 {
  1125. serverEntry.DisableImpairedProtocols(impairedProtocols)
  1126. if len(serverEntry.GetSupportedProtocols(false)) == 0 {
  1127. // Skip this server entry, as it has no supported
  1128. // protocols after disabling the impaired ones
  1129. // TODO: modify ServerEntryIterator to skip these?
  1130. continue
  1131. }
  1132. }
  1133. // adjustedEstablishStartTime is establishStartTime shifted
  1134. // to exclude time spent waiting for network connectivity.
  1135. candidate := &candidateServerEntry{
  1136. serverEntry: serverEntry,
  1137. isServerAffinityCandidate: isServerAffinityCandidate,
  1138. adjustedEstablishStartTime: establishStartTime.Add(networkWaitDuration),
  1139. }
  1140. wasServerAffinityCandidate := isServerAffinityCandidate
  1141. // Note: there must be only one server affinity candidate, as it
  1142. // closes the serverAffinityDoneBroadcast channel.
  1143. isServerAffinityCandidate = false
  1144. // TODO: here we could generate multiple candidates from the
  1145. // server entry when there are many MeekFrontingAddresses.
  1146. select {
  1147. case controller.candidateServerEntries <- candidate:
  1148. case <-controller.stopEstablishingBroadcast:
  1149. break loop
  1150. case <-controller.shutdownBroadcast:
  1151. break loop
  1152. }
  1153. if startTime.Add(ESTABLISH_TUNNEL_WORK_TIME).Before(monotime.Now()) {
  1154. // Start over, after a brief pause, with a new shuffle of the server
  1155. // entries, and potentially some newly fetched server entries.
  1156. break
  1157. }
  1158. if wasServerAffinityCandidate {
  1159. // Don't start the next candidate until either the server affinity
  1160. // candidate has completed (success or failure) or is still working
  1161. // and the grace period has elapsed.
  1162. timer := time.NewTimer(ESTABLISH_TUNNEL_SERVER_AFFINITY_GRACE_PERIOD)
  1163. select {
  1164. case <-timer.C:
  1165. case <-controller.serverAffinityDoneBroadcast:
  1166. case <-controller.stopEstablishingBroadcast:
  1167. break loop
  1168. case <-controller.shutdownBroadcast:
  1169. break loop
  1170. }
  1171. } else if controller.config.StaggerConnectionWorkersMilliseconds != 0 {
  1172. // Stagger concurrent connection workers.
  1173. timer := time.NewTimer(time.Millisecond * time.Duration(
  1174. controller.config.StaggerConnectionWorkersMilliseconds))
  1175. select {
  1176. case <-timer.C:
  1177. case <-controller.stopEstablishingBroadcast:
  1178. break loop
  1179. case <-controller.shutdownBroadcast:
  1180. break loop
  1181. }
  1182. }
  1183. }
  1184. // Free up resources now, but don't reset until after the pause.
  1185. iterator.Close()
  1186. // Trigger a common remote server list fetch, since we may have failed
  1187. // to connect with all known servers. Don't block sending signal, since
  1188. // this signal may have already been sent.
  1189. // Don't wait for fetch remote to succeed, since it may fail and
  1190. // enter a retry loop and we're better off trying more known servers.
  1191. // TODO: synchronize the fetch response, so it can be incorporated
  1192. // into the server entry iterator as soon as available.
  1193. select {
  1194. case controller.signalFetchCommonRemoteServerList <- *new(struct{}):
  1195. default:
  1196. }
  1197. // Trigger an OSL fetch in parallel. Both fetches are run in parallel
  1198. // so that if one out of the common RLS and OSL set is large, it doesn't
  1199. // doesn't entirely block fetching the other.
  1200. select {
  1201. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  1202. default:
  1203. }
  1204. // Trigger an out-of-band upgrade availability check and download.
  1205. // Since we may have failed to connect, we may benefit from upgrading
  1206. // to a new client version with new circumvention capabilities.
  1207. select {
  1208. case controller.signalDownloadUpgrade <- "":
  1209. default:
  1210. }
  1211. // After a complete iteration of candidate servers, pause before iterating again.
  1212. // This helps avoid some busy wait loop conditions, and also allows some time for
  1213. // network conditions to change. Also allows for fetch remote to complete,
  1214. // in typical conditions (it isn't strictly necessary to wait for this, there will
  1215. // be more rounds if required).
  1216. timeout := time.After(
  1217. time.Duration(*controller.config.EstablishTunnelPausePeriodSeconds) * time.Second)
  1218. select {
  1219. case <-timeout:
  1220. // Retry iterating
  1221. case <-controller.stopEstablishingBroadcast:
  1222. break loop
  1223. case <-controller.shutdownBroadcast:
  1224. break loop
  1225. }
  1226. iterator.Reset()
  1227. }
  1228. }
  1229. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  1230. // a connection to the tunnel server, and delivers the connected tunnel to a channel.
  1231. func (controller *Controller) establishTunnelWorker() {
  1232. defer controller.establishWaitGroup.Done()
  1233. loop:
  1234. for candidateServerEntry := range controller.candidateServerEntries {
  1235. // Note: don't receive from candidateServerEntries and stopEstablishingBroadcast
  1236. // in the same select, since we want to prioritize receiving the stop signal
  1237. if controller.isStopEstablishingBroadcast() {
  1238. break loop
  1239. }
  1240. // There may already be a tunnel to this candidate. If so, skip it.
  1241. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  1242. continue
  1243. }
  1244. // ConnectTunnel will allocate significant memory, so first attempt to
  1245. // reclaim as much as possible.
  1246. aggressiveGarbageCollection()
  1247. // Select the tunnel protocol. Unless config.TunnelProtocol is set, the
  1248. // selection will be made at random from protocols supported by the
  1249. // server entry.
  1250. //
  1251. // When limiting concurrent meek connection workers, and at the limit,
  1252. // do not select meek since otherwise the candidate must be skipped.
  1253. //
  1254. // If at the limit and unabled to select a non-meek protocol, skip the
  1255. // candidate entirely and move on to the next. Since candidates are shuffled
  1256. // it's probable that the next candidate is not meek. In this case, a
  1257. // StaggerConnectionWorkersMilliseconds delay may still be incurred.
  1258. excludeMeek := false
  1259. controller.concurrentEstablishTunnelsMutex.Lock()
  1260. if controller.config.LimitMeekConnectionWorkers > 0 &&
  1261. controller.concurrentMeekEstablishTunnels >=
  1262. controller.config.LimitMeekConnectionWorkers {
  1263. excludeMeek = true
  1264. }
  1265. controller.concurrentEstablishTunnelsMutex.Unlock()
  1266. selectedProtocol, err := selectProtocol(
  1267. controller.config, candidateServerEntry.serverEntry, excludeMeek)
  1268. if err == errProtocolNotSupported {
  1269. // selectProtocol returns errProtocolNotSupported when excludeMeek
  1270. // is set and the server entry only supports meek protocols.
  1271. // Skip this candidate.
  1272. continue
  1273. }
  1274. var tunnel *Tunnel
  1275. if err == nil {
  1276. isMeek := protocol.TunnelProtocolUsesMeek(selectedProtocol) ||
  1277. protocol.TunnelProtocolUsesMeek(selectedProtocol)
  1278. controller.concurrentEstablishTunnelsMutex.Lock()
  1279. if isMeek {
  1280. // Recheck the limit now that we know we're selecting meek and
  1281. // adjusting concurrentMeekEstablishTunnels.
  1282. if controller.config.LimitMeekConnectionWorkers > 0 &&
  1283. controller.concurrentMeekEstablishTunnels >=
  1284. controller.config.LimitMeekConnectionWorkers {
  1285. // Skip this candidate.
  1286. controller.concurrentEstablishTunnelsMutex.Unlock()
  1287. continue
  1288. }
  1289. controller.concurrentMeekEstablishTunnels += 1
  1290. if controller.concurrentMeekEstablishTunnels > controller.peakConcurrentMeekEstablishTunnels {
  1291. controller.peakConcurrentMeekEstablishTunnels = controller.concurrentMeekEstablishTunnels
  1292. }
  1293. }
  1294. controller.concurrentEstablishTunnels += 1
  1295. if controller.concurrentEstablishTunnels > controller.peakConcurrentEstablishTunnels {
  1296. controller.peakConcurrentEstablishTunnels = controller.concurrentEstablishTunnels
  1297. }
  1298. controller.concurrentEstablishTunnelsMutex.Unlock()
  1299. tunnel, err = ConnectTunnel(
  1300. controller.config,
  1301. controller.untunneledDialConfig,
  1302. controller.sessionId,
  1303. controller.establishPendingConns,
  1304. candidateServerEntry.serverEntry,
  1305. selectedProtocol,
  1306. candidateServerEntry.adjustedEstablishStartTime)
  1307. controller.concurrentEstablishTunnelsMutex.Lock()
  1308. if isMeek {
  1309. controller.concurrentMeekEstablishTunnels -= 1
  1310. }
  1311. controller.concurrentEstablishTunnels -= 1
  1312. controller.concurrentEstablishTunnelsMutex.Unlock()
  1313. }
  1314. // Periodically emit memory metrics during the establishment cycle.
  1315. if !controller.isStopEstablishingBroadcast() {
  1316. emitMemoryMetrics()
  1317. }
  1318. // Immediately reclaim memory allocated by the establishment. In the case
  1319. // of failure, first clear the reference to the tunnel. In the case of
  1320. // success, the garbage collection may still be effective as the initial
  1321. // phases of some protocols involve significant memory allocation that
  1322. // could now be reclaimed.
  1323. if err != nil {
  1324. tunnel = nil
  1325. }
  1326. aggressiveGarbageCollection()
  1327. if err != nil {
  1328. // Unblock other candidates immediately when
  1329. // server affinity candidate fails.
  1330. if candidateServerEntry.isServerAffinityCandidate {
  1331. close(controller.serverAffinityDoneBroadcast)
  1332. }
  1333. // Before emitting error, check if establish interrupted, in which
  1334. // case the error is noise.
  1335. if controller.isStopEstablishingBroadcast() {
  1336. break loop
  1337. }
  1338. NoticeInfo("failed to connect to %s: %s", candidateServerEntry.serverEntry.IpAddress, err)
  1339. continue
  1340. }
  1341. // Deliver connected tunnel.
  1342. // Don't block. Assumes the receiver has a buffer large enough for
  1343. // the number of desired tunnels. If there's no room, the tunnel must
  1344. // not be required so it's discarded.
  1345. select {
  1346. case controller.connectedTunnels <- tunnel:
  1347. default:
  1348. controller.discardTunnel(tunnel)
  1349. // Clear the reference to this discarded tunnel and immediately run
  1350. // a garbage collection to reclaim its memory.
  1351. tunnel = nil
  1352. aggressiveGarbageCollection()
  1353. }
  1354. // Unblock other candidates only after delivering when
  1355. // server affinity candidate succeeds.
  1356. if candidateServerEntry.isServerAffinityCandidate {
  1357. close(controller.serverAffinityDoneBroadcast)
  1358. }
  1359. }
  1360. }
  1361. func (controller *Controller) isStopEstablishingBroadcast() bool {
  1362. select {
  1363. case <-controller.stopEstablishingBroadcast:
  1364. return true
  1365. default:
  1366. }
  1367. return false
  1368. }