controller.go 50 KB

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