controller.go 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497
  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 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. // establishedTunnels and failedTunnels buffer sizes are large enough to
  114. // receive full pools of tunnels without blocking. Senders should not block.
  115. establishedTunnels: 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. // and access isEstablishing.
  551. if !controller.isEstablishing {
  552. controller.startEstablishing()
  553. }
  554. case establishedTunnel := <-controller.establishedTunnels:
  555. if controller.isImpairedProtocol(establishedTunnel.protocol) {
  556. // Protocol was classified as impaired while this tunnel established.
  557. // This is most likely to occur with TunnelPoolSize > 0. We log the
  558. // event but take no action. Discarding the tunnel would break the
  559. // impaired logic unless we did that (a) only if there are other
  560. // unimpaired protocols; (b) only during the first interation of the
  561. // ESTABLISH_TUNNEL_WORK_TIME loop. By not discarding here, a true
  562. // impaired protocol may require an extra reconnect.
  563. NoticeAlert("established tunnel with impaired protocol: %s", establishedTunnel.protocol)
  564. }
  565. tunnelCount, registered := controller.registerTunnel(establishedTunnel)
  566. if !registered {
  567. // Already fully established, so discard.
  568. controller.discardTunnel(establishedTunnel)
  569. // Clear the reference to this discarded tunnel and immediately run
  570. // a garbage collection to reclaim its memory.
  571. establishedTunnel = nil
  572. aggressiveGarbageCollection()
  573. break
  574. }
  575. NoticeActiveTunnel(establishedTunnel.serverEntry.IpAddress, establishedTunnel.protocol, establishedTunnel.serverEntry.SupportsSSHAPIRequests())
  576. if tunnelCount == 1 {
  577. // The split tunnel classifier is started once the first tunnel is
  578. // established. This first tunnel is passed in to be used to make
  579. // the routes data request.
  580. // A long-running controller may run while the host device is present
  581. // in different regions. In this case, we want the split tunnel logic
  582. // to switch to routes for new regions and not classify traffic based
  583. // on routes installed for older regions.
  584. // We assume that when regions change, the host network will also
  585. // change, and so all tunnels will fail and be re-established. Under
  586. // that assumption, the classifier will be re-Start()-ed here when
  587. // the region has changed.
  588. controller.splitTunnelClassifier.Start(establishedTunnel)
  589. // Signal a connected request on each 1st tunnel establishment. For
  590. // multi-tunnels, the session is connected as long as at least one
  591. // tunnel is established.
  592. controller.startOrSignalConnectedReporter()
  593. // If the handshake indicated that a new client version is available,
  594. // trigger an upgrade download.
  595. // Note: serverContext is nil when DisableApi is set
  596. if establishedTunnel.serverContext != nil &&
  597. establishedTunnel.serverContext.clientUpgradeVersion != "" {
  598. handshakeVersion := establishedTunnel.serverContext.clientUpgradeVersion
  599. select {
  600. case controller.signalDownloadUpgrade <- handshakeVersion:
  601. default:
  602. }
  603. }
  604. }
  605. // Set the new tunnel as the transport for the packet tunnel. The packet tunnel
  606. // client remains up when reestablishing, but no packets are relayed while there
  607. // is no connected tunnel. UseTunnel will establish a new packet tunnel SSH
  608. // channel over the new SSH tunnel and configure the packet tunnel client to use
  609. // the new SSH channel as its transport.
  610. //
  611. // Note: as is, this logic is suboptimal for TunnelPoolSize > 1, as this would
  612. // continuously initialize new packet tunnel sessions for each established
  613. // server. For now, config validation requires TunnelPoolSize == 1 when
  614. // the packet tunnel is used.
  615. if controller.packetTunnelTransport != nil {
  616. controller.packetTunnelTransport.UseTunnel(establishedTunnel)
  617. }
  618. // TODO: design issue -- might not be enough server entries with region/caps to ever fill tunnel slots;
  619. // possible solution is establish target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  620. if controller.isFullyEstablished() {
  621. controller.stopEstablishing()
  622. }
  623. case clientVerificationPayload = <-controller.newClientVerificationPayload:
  624. controller.setClientVerificationPayloadForActiveTunnels(clientVerificationPayload)
  625. case <-controller.shutdownBroadcast:
  626. break loop
  627. }
  628. }
  629. // Stop running
  630. controller.stopEstablishing()
  631. controller.terminateAllTunnels()
  632. // Drain tunnel channels
  633. close(controller.establishedTunnels)
  634. for tunnel := range controller.establishedTunnels {
  635. controller.discardTunnel(tunnel)
  636. }
  637. close(controller.failedTunnels)
  638. for tunnel := range controller.failedTunnels {
  639. controller.discardTunnel(tunnel)
  640. }
  641. NoticeInfo("exiting run tunnels")
  642. }
  643. // TerminateNextActiveTunnel is a support routine for
  644. // test code that must terminate the active tunnel and
  645. // restart establishing. This function is not guaranteed
  646. // to be safe for use in other cases.
  647. func (controller *Controller) TerminateNextActiveTunnel() {
  648. tunnel := controller.getNextActiveTunnel()
  649. if tunnel != nil {
  650. controller.SignalTunnelFailure(tunnel)
  651. }
  652. }
  653. // classifyImpairedProtocol tracks "impaired" protocol classifications for failed
  654. // tunnels. A protocol is classified as impaired if a tunnel using that protocol
  655. // fails, repeatedly, shortly after the start of the connection. During tunnel
  656. // establishment, impaired protocols are briefly skipped.
  657. //
  658. // One purpose of this measure is to defend against an attack where the adversary,
  659. // for example, tags an OSSH TCP connection as an "unidentified" protocol; allows
  660. // it to connect; but then kills the underlying TCP connection after a short time.
  661. // Since OSSH has less latency than other protocols that may bypass an "unidentified"
  662. // filter, these other protocols might never be selected for use.
  663. //
  664. // Concurrency note: only the runTunnels() goroutine may call classifyImpairedProtocol
  665. func (controller *Controller) classifyImpairedProtocol(failedTunnel *Tunnel) {
  666. if failedTunnel.establishedTime.Add(IMPAIRED_PROTOCOL_CLASSIFICATION_DURATION).After(monotime.Now()) {
  667. controller.impairedProtocolClassification[failedTunnel.protocol] += 1
  668. } else {
  669. controller.impairedProtocolClassification[failedTunnel.protocol] = 0
  670. }
  671. // Reset classification once all known protocols are classified as impaired, as
  672. // there is now no way to proceed with only unimpaired protocols. The network
  673. // situation (or attack) resulting in classification may not be protocol-specific.
  674. //
  675. // Note: with controller.config.TunnelProtocol set, this will always reset once
  676. // that protocol has reached IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD.
  677. if CountNonImpairedProtocols(
  678. controller.config.EgressRegion,
  679. controller.config.TunnelProtocol,
  680. controller.getImpairedProtocols()) == 0 {
  681. controller.impairedProtocolClassification = make(map[string]int)
  682. }
  683. }
  684. // getImpairedProtocols returns a list of protocols that have sufficient
  685. // classifications to be considered impaired protocols.
  686. //
  687. // Concurrency note: only the runTunnels() goroutine may call getImpairedProtocols
  688. func (controller *Controller) getImpairedProtocols() []string {
  689. NoticeImpairedProtocolClassification(controller.impairedProtocolClassification)
  690. impairedProtocols := make([]string, 0)
  691. for protocol, count := range controller.impairedProtocolClassification {
  692. if count >= IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD {
  693. impairedProtocols = append(impairedProtocols, protocol)
  694. }
  695. }
  696. return impairedProtocols
  697. }
  698. // isImpairedProtocol checks if the specified protocol is classified as impaired.
  699. //
  700. // Concurrency note: only the runTunnels() goroutine may call isImpairedProtocol
  701. func (controller *Controller) isImpairedProtocol(protocol string) bool {
  702. count, ok := controller.impairedProtocolClassification[protocol]
  703. return ok && count >= IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD
  704. }
  705. // SignalSeededNewSLOK implements the TunnelOwner interface. This function
  706. // is called by Tunnel.operateTunnel when the tunnel has received a new,
  707. // previously unknown SLOK from the server. The Controller triggers an OSL
  708. // fetch, as the new SLOK may be sufficient to access new OSLs.
  709. func (controller *Controller) SignalSeededNewSLOK() {
  710. select {
  711. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  712. default:
  713. }
  714. }
  715. // SignalTunnelFailure implements the TunnelOwner interface. This function
  716. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  717. // has failed. The Controller will signal runTunnels to create a new
  718. // tunnel and/or remove the tunnel from the list of active tunnels.
  719. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  720. // Don't block. Assumes the receiver has a buffer large enough for
  721. // the typical number of operated tunnels. In case there's no room,
  722. // terminate the tunnel (runTunnels won't get a signal in this case,
  723. // but the tunnel will be removed from the list of active tunnels).
  724. select {
  725. case controller.failedTunnels <- tunnel:
  726. default:
  727. controller.terminateTunnel(tunnel)
  728. }
  729. }
  730. // discardTunnel disposes of a successful connection that is no longer required.
  731. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  732. NoticeInfo("discard tunnel: %s", tunnel.serverEntry.IpAddress)
  733. // TODO: not calling PromoteServerEntry, since that would rank the
  734. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  735. // be promoted (since it connects), but with lower rank than all active
  736. // tunnels?
  737. tunnel.Close(true)
  738. }
  739. // registerTunnel adds the connected tunnel to the pool of active tunnels
  740. // which are candidates for port forwarding. Returns true if the pool has an
  741. // empty slot and false if the pool is full (caller should discard the tunnel).
  742. func (controller *Controller) registerTunnel(tunnel *Tunnel) (int, bool) {
  743. controller.tunnelMutex.Lock()
  744. defer controller.tunnelMutex.Unlock()
  745. if len(controller.tunnels) >= controller.config.TunnelPoolSize {
  746. return len(controller.tunnels), false
  747. }
  748. // Perform a final check just in case we've established
  749. // a duplicate connection.
  750. for _, activeTunnel := range controller.tunnels {
  751. if activeTunnel.serverEntry.IpAddress == tunnel.serverEntry.IpAddress {
  752. NoticeAlert("duplicate tunnel: %s", tunnel.serverEntry.IpAddress)
  753. return len(controller.tunnels), false
  754. }
  755. }
  756. controller.establishedOnce = true
  757. controller.tunnels = append(controller.tunnels, tunnel)
  758. NoticeTunnels(len(controller.tunnels))
  759. // Promote this successful tunnel to first rank so it's one
  760. // of the first candidates next time establish runs.
  761. // Connecting to a TargetServerEntry does not change the
  762. // ranking.
  763. if controller.config.TargetServerEntry == "" {
  764. PromoteServerEntry(tunnel.serverEntry.IpAddress)
  765. }
  766. return len(controller.tunnels), true
  767. }
  768. // hasEstablishedOnce indicates if at least one active tunnel has
  769. // been established up to this point. This is regardeless of how many
  770. // tunnels are presently active.
  771. func (controller *Controller) hasEstablishedOnce() bool {
  772. controller.tunnelMutex.Lock()
  773. defer controller.tunnelMutex.Unlock()
  774. return controller.establishedOnce
  775. }
  776. // isFullyEstablished indicates if the pool of active tunnels is full.
  777. func (controller *Controller) isFullyEstablished() bool {
  778. controller.tunnelMutex.Lock()
  779. defer controller.tunnelMutex.Unlock()
  780. return len(controller.tunnels) >= controller.config.TunnelPoolSize
  781. }
  782. // terminateTunnel removes a tunnel from the pool of active tunnels
  783. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  784. // is adjusted as required.
  785. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  786. controller.tunnelMutex.Lock()
  787. defer controller.tunnelMutex.Unlock()
  788. for index, activeTunnel := range controller.tunnels {
  789. if tunnel == activeTunnel {
  790. controller.tunnels = append(
  791. controller.tunnels[:index], controller.tunnels[index+1:]...)
  792. if controller.nextTunnel > index {
  793. controller.nextTunnel--
  794. }
  795. if controller.nextTunnel >= len(controller.tunnels) {
  796. controller.nextTunnel = 0
  797. }
  798. activeTunnel.Close(false)
  799. NoticeTunnels(len(controller.tunnels))
  800. break
  801. }
  802. }
  803. }
  804. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  805. // This is used when shutting down the controller.
  806. func (controller *Controller) terminateAllTunnels() {
  807. controller.tunnelMutex.Lock()
  808. defer controller.tunnelMutex.Unlock()
  809. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  810. // may take a few seconds to send a final status request. We only want
  811. // to wait as long as the single slowest tunnel.
  812. closeWaitGroup := new(sync.WaitGroup)
  813. closeWaitGroup.Add(len(controller.tunnels))
  814. for _, activeTunnel := range controller.tunnels {
  815. tunnel := activeTunnel
  816. go func() {
  817. defer closeWaitGroup.Done()
  818. tunnel.Close(false)
  819. }()
  820. }
  821. closeWaitGroup.Wait()
  822. controller.tunnels = make([]*Tunnel, 0)
  823. controller.nextTunnel = 0
  824. NoticeTunnels(len(controller.tunnels))
  825. }
  826. // getNextActiveTunnel returns the next tunnel from the pool of active
  827. // tunnels. Currently, tunnel selection order is simple round-robin.
  828. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  829. controller.tunnelMutex.Lock()
  830. defer controller.tunnelMutex.Unlock()
  831. for i := len(controller.tunnels); i > 0; i-- {
  832. tunnel = controller.tunnels[controller.nextTunnel]
  833. controller.nextTunnel =
  834. (controller.nextTunnel + 1) % len(controller.tunnels)
  835. return tunnel
  836. }
  837. return nil
  838. }
  839. // isActiveTunnelServerEntry is used to check if there's already
  840. // an existing tunnel to a candidate server.
  841. func (controller *Controller) isActiveTunnelServerEntry(
  842. serverEntry *protocol.ServerEntry) bool {
  843. controller.tunnelMutex.Lock()
  844. defer controller.tunnelMutex.Unlock()
  845. for _, activeTunnel := range controller.tunnels {
  846. if activeTunnel.serverEntry.IpAddress == serverEntry.IpAddress {
  847. return true
  848. }
  849. }
  850. return false
  851. }
  852. // setClientVerificationPayloadForActiveTunnels triggers the client verification
  853. // request for all active tunnels.
  854. func (controller *Controller) setClientVerificationPayloadForActiveTunnels(
  855. clientVerificationPayload string) {
  856. controller.tunnelMutex.Lock()
  857. defer controller.tunnelMutex.Unlock()
  858. for _, activeTunnel := range controller.tunnels {
  859. activeTunnel.SetClientVerificationPayload(clientVerificationPayload)
  860. }
  861. }
  862. // Dial selects an active tunnel and establishes a port forward
  863. // connection through the selected tunnel. Failure to connect is considered
  864. // a port forward failure, for the purpose of monitoring tunnel health.
  865. func (controller *Controller) Dial(
  866. remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error) {
  867. tunnel := controller.getNextActiveTunnel()
  868. if tunnel == nil {
  869. return nil, common.ContextError(errors.New("no active tunnels"))
  870. }
  871. // Perform split tunnel classification when feature is enabled, and if the remote
  872. // address is classified as untunneled, dial directly.
  873. if !alwaysTunnel && controller.config.SplitTunnelDnsServer != "" {
  874. host, _, err := net.SplitHostPort(remoteAddr)
  875. if err != nil {
  876. return nil, common.ContextError(err)
  877. }
  878. // Note: a possible optimization, when split tunnel is active and IsUntunneled performs
  879. // a DNS resolution in order to make its classification, is to reuse that IP address in
  880. // the following Dials so they do not need to make their own resolutions. However, the
  881. // way this is currently implemented ensures that, e.g., DNS geo load balancing occurs
  882. // relative to the outbound network.
  883. if controller.splitTunnelClassifier.IsUntunneled(host) {
  884. // TODO: track downstreamConn and close it when the DialTCP conn closes, as with tunnel.Dial conns?
  885. return DialTCP(remoteAddr, controller.untunneledDialConfig)
  886. }
  887. }
  888. tunneledConn, err := tunnel.Dial(remoteAddr, alwaysTunnel, downstreamConn)
  889. if err != nil {
  890. return nil, common.ContextError(err)
  891. }
  892. return tunneledConn, nil
  893. }
  894. // startEstablishing creates a pool of worker goroutines which will
  895. // attempt to establish tunnels to candidate servers. The candidates
  896. // are generated by another goroutine.
  897. func (controller *Controller) startEstablishing() {
  898. if controller.isEstablishing {
  899. return
  900. }
  901. NoticeInfo("start establishing")
  902. controller.concurrentEstablishTunnelsMutex.Lock()
  903. controller.concurrentEstablishTunnels = 0
  904. controller.concurrentMeekEstablishTunnels = 0
  905. controller.peakConcurrentEstablishTunnels = 0
  906. controller.peakConcurrentMeekEstablishTunnels = 0
  907. controller.concurrentEstablishTunnelsMutex.Unlock()
  908. aggressiveGarbageCollection()
  909. emitMemoryMetrics()
  910. controller.isEstablishing = true
  911. controller.establishWaitGroup = new(sync.WaitGroup)
  912. controller.stopEstablishingBroadcast = make(chan struct{})
  913. controller.candidateServerEntries = make(chan *candidateServerEntry)
  914. controller.establishPendingConns.Reset()
  915. // The server affinity mechanism attempts to favor the previously
  916. // used server when reconnecting. This is beneficial for user
  917. // applications which expect consistency in user IP address (for
  918. // example, a web site which prompts for additional user
  919. // authentication when the IP address changes).
  920. //
  921. // Only the very first server, as determined by
  922. // datastore.PromoteServerEntry(), is the server affinity candidate.
  923. // Concurrent connections attempts to many servers are launched
  924. // without delay, in case the affinity server connection fails.
  925. // While the affinity server connection is outstanding, when any
  926. // other connection is established, there is a short grace period
  927. // delay before delivering the established tunnel; this allows some
  928. // time for the affinity server connection to succeed first.
  929. // When the affinity server connection fails, any other established
  930. // tunnel is registered without delay.
  931. //
  932. // Note: the establishTunnelWorker that receives the affinity
  933. // candidate is solely resonsible for closing
  934. // controller.serverAffinityDoneBroadcast.
  935. //
  936. // Note: if config.EgressRegion or config.TunnelProtocol has changed
  937. // since the top server was promoted, the first server may not actually
  938. // be the last connected server.
  939. // TODO: should not favor the first server in this case
  940. controller.serverAffinityDoneBroadcast = make(chan struct{})
  941. for i := 0; i < controller.config.ConnectionWorkerPoolSize; i++ {
  942. controller.establishWaitGroup.Add(1)
  943. go controller.establishTunnelWorker()
  944. }
  945. controller.establishWaitGroup.Add(1)
  946. go controller.establishCandidateGenerator(
  947. controller.getImpairedProtocols())
  948. }
  949. // stopEstablishing signals the establish goroutines to stop and waits
  950. // for the group to halt. pendingConns is used to interrupt any worker
  951. // blocked on a socket connect.
  952. func (controller *Controller) stopEstablishing() {
  953. if !controller.isEstablishing {
  954. return
  955. }
  956. NoticeInfo("stop establishing")
  957. close(controller.stopEstablishingBroadcast)
  958. // Note: interruptibleTCPClose doesn't really interrupt socket connects
  959. // and may leave goroutines running for a time after the Wait call.
  960. controller.establishPendingConns.CloseAll()
  961. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  962. // (as it may be sending to that channel).
  963. controller.establishWaitGroup.Wait()
  964. controller.isEstablishing = false
  965. controller.establishWaitGroup = nil
  966. controller.stopEstablishingBroadcast = nil
  967. controller.candidateServerEntries = nil
  968. controller.serverAffinityDoneBroadcast = nil
  969. controller.concurrentEstablishTunnelsMutex.Lock()
  970. peakConcurrent := controller.peakConcurrentEstablishTunnels
  971. peakConcurrentMeek := controller.peakConcurrentMeekEstablishTunnels
  972. controller.concurrentEstablishTunnels = 0
  973. controller.concurrentMeekEstablishTunnels = 0
  974. controller.peakConcurrentEstablishTunnels = 0
  975. controller.peakConcurrentMeekEstablishTunnels = 0
  976. controller.concurrentEstablishTunnelsMutex.Unlock()
  977. NoticeInfo("peak concurrent establish tunnels: %d", peakConcurrent)
  978. NoticeInfo("peak concurrent meek establish tunnels: %d", peakConcurrentMeek)
  979. emitMemoryMetrics()
  980. standardGarbageCollection()
  981. }
  982. // establishCandidateGenerator populates the candidate queue with server entries
  983. // from the data store. Server entries are iterated in rank order, so that promoted
  984. // servers with higher rank are priority candidates.
  985. func (controller *Controller) establishCandidateGenerator(impairedProtocols []string) {
  986. defer controller.establishWaitGroup.Done()
  987. defer close(controller.candidateServerEntries)
  988. // establishStartTime is used to calculate and report the
  989. // client's tunnel establishment duration.
  990. //
  991. // networkWaitDuration is the elapsed time spent waiting
  992. // for network connectivity. This duration will be excluded
  993. // from reported tunnel establishment duration.
  994. establishStartTime := monotime.Now()
  995. var networkWaitDuration time.Duration
  996. iterator, err := NewServerEntryIterator(controller.config)
  997. if err != nil {
  998. NoticeAlert("failed to iterate over candidates: %s", err)
  999. controller.SignalComponentFailure()
  1000. return
  1001. }
  1002. defer iterator.Close()
  1003. isServerAffinityCandidate := true
  1004. // TODO: reconcile server affinity scheme with multi-tunnel mode
  1005. if controller.config.TunnelPoolSize > 1 {
  1006. isServerAffinityCandidate = false
  1007. close(controller.serverAffinityDoneBroadcast)
  1008. }
  1009. loop:
  1010. // Repeat until stopped
  1011. for i := 0; ; i++ {
  1012. networkWaitStartTime := monotime.Now()
  1013. if !WaitForNetworkConnectivity(
  1014. controller.config.NetworkConnectivityChecker,
  1015. controller.stopEstablishingBroadcast,
  1016. controller.shutdownBroadcast) {
  1017. break loop
  1018. }
  1019. networkWaitDuration += monotime.Since(networkWaitStartTime)
  1020. // Send each iterator server entry to the establish workers
  1021. startTime := monotime.Now()
  1022. for {
  1023. serverEntry, err := iterator.Next()
  1024. if err != nil {
  1025. NoticeAlert("failed to get next candidate: %s", err)
  1026. controller.SignalComponentFailure()
  1027. break loop
  1028. }
  1029. if serverEntry == nil {
  1030. // Completed this iteration
  1031. break
  1032. }
  1033. if controller.config.TargetApiProtocol == protocol.PSIPHON_SSH_API_PROTOCOL &&
  1034. !serverEntry.SupportsSSHAPIRequests() {
  1035. continue
  1036. }
  1037. // Disable impaired protocols. This is only done for the
  1038. // first iteration of the ESTABLISH_TUNNEL_WORK_TIME
  1039. // loop since (a) one iteration should be sufficient to
  1040. // evade the attack; (b) there's a good chance of false
  1041. // positives (such as short tunnel durations due to network
  1042. // hopping on a mobile device).
  1043. // The edited serverEntry is temporary copy which is not
  1044. // stored or reused.
  1045. if i == 0 {
  1046. serverEntry.DisableImpairedProtocols(impairedProtocols)
  1047. if len(serverEntry.GetSupportedProtocols(false)) == 0 {
  1048. // Skip this server entry, as it has no supported
  1049. // protocols after disabling the impaired ones
  1050. // TODO: modify ServerEntryIterator to skip these?
  1051. continue
  1052. }
  1053. }
  1054. // adjustedEstablishStartTime is establishStartTime shifted
  1055. // to exclude time spent waiting for network connectivity.
  1056. candidate := &candidateServerEntry{
  1057. serverEntry: serverEntry,
  1058. isServerAffinityCandidate: isServerAffinityCandidate,
  1059. adjustedEstablishStartTime: establishStartTime.Add(networkWaitDuration),
  1060. }
  1061. wasServerAffinityCandidate := isServerAffinityCandidate
  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. if wasServerAffinityCandidate {
  1080. // Don't start the next candidate until either the server affinity
  1081. // candidate has completed (success or failure) or is still working
  1082. // and the grace period has elapsed.
  1083. timer := time.NewTimer(ESTABLISH_TUNNEL_SERVER_AFFINITY_GRACE_PERIOD)
  1084. select {
  1085. case <-timer.C:
  1086. case <-controller.serverAffinityDoneBroadcast:
  1087. case <-controller.stopEstablishingBroadcast:
  1088. break loop
  1089. case <-controller.shutdownBroadcast:
  1090. break loop
  1091. }
  1092. } else if controller.config.StaggerConnectionWorkersMilliseconds != 0 {
  1093. // Stagger concurrent connection workers.
  1094. timer := time.NewTimer(time.Millisecond * time.Duration(
  1095. controller.config.StaggerConnectionWorkersMilliseconds))
  1096. select {
  1097. case <-timer.C:
  1098. case <-controller.stopEstablishingBroadcast:
  1099. break loop
  1100. case <-controller.shutdownBroadcast:
  1101. break loop
  1102. }
  1103. }
  1104. }
  1105. // Free up resources now, but don't reset until after the pause.
  1106. iterator.Close()
  1107. // Trigger a common remote server list fetch, since we may have failed
  1108. // to connect with all known servers. Don't block sending signal, since
  1109. // this signal may have already been sent.
  1110. // Don't wait for fetch remote to succeed, since it may fail and
  1111. // enter a retry loop and we're better off trying more known servers.
  1112. // TODO: synchronize the fetch response, so it can be incorporated
  1113. // into the server entry iterator as soon as available.
  1114. select {
  1115. case controller.signalFetchCommonRemoteServerList <- *new(struct{}):
  1116. default:
  1117. }
  1118. // Trigger an OSL fetch in parallel. Both fetches are run in parallel
  1119. // so that if one out of the common RLS and OSL set is large, it doesn't
  1120. // doesn't entirely block fetching the other.
  1121. select {
  1122. case controller.signalFetchObfuscatedServerLists <- *new(struct{}):
  1123. default:
  1124. }
  1125. // Trigger an out-of-band upgrade availability check and download.
  1126. // Since we may have failed to connect, we may benefit from upgrading
  1127. // to a new client version with new circumvention capabilities.
  1128. select {
  1129. case controller.signalDownloadUpgrade <- "":
  1130. default:
  1131. }
  1132. // After a complete iteration of candidate servers, pause before iterating again.
  1133. // This helps avoid some busy wait loop conditions, and also allows some time for
  1134. // network conditions to change. Also allows for fetch remote to complete,
  1135. // in typical conditions (it isn't strictly necessary to wait for this, there will
  1136. // be more rounds if required).
  1137. timeout := time.After(
  1138. time.Duration(*controller.config.EstablishTunnelPausePeriodSeconds) * time.Second)
  1139. select {
  1140. case <-timeout:
  1141. // Retry iterating
  1142. case <-controller.stopEstablishingBroadcast:
  1143. break loop
  1144. case <-controller.shutdownBroadcast:
  1145. break loop
  1146. }
  1147. iterator.Reset()
  1148. }
  1149. NoticeInfo("stopped candidate generator")
  1150. }
  1151. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  1152. // a connection to the tunnel server, and delivers the established tunnel to a channel.
  1153. func (controller *Controller) establishTunnelWorker() {
  1154. defer controller.establishWaitGroup.Done()
  1155. loop:
  1156. for candidateServerEntry := range controller.candidateServerEntries {
  1157. // Note: don't receive from candidateServerEntries and stopEstablishingBroadcast
  1158. // in the same select, since we want to prioritize receiving the stop signal
  1159. if controller.isStopEstablishingBroadcast() {
  1160. break loop
  1161. }
  1162. // There may already be a tunnel to this candidate. If so, skip it.
  1163. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  1164. continue
  1165. }
  1166. // EstablishTunnel will allocate significant memory, so first attempt to
  1167. // reclaim as much as possible.
  1168. aggressiveGarbageCollection()
  1169. // Select the tunnel protocol. Unless config.TunnelProtocol is set, the
  1170. // selection will be made at random from protocols supported by the
  1171. // server entry.
  1172. //
  1173. // When limiting concurrent meek connection workers, and at the limit,
  1174. // do not select meek since otherwise the candidate must be skipped.
  1175. //
  1176. // If at the limit and unabled to select a non-meek protocol, skip the
  1177. // candidate entirely and move on to the next. Since candidates are shuffled
  1178. // it's probable that the next candidate is not meek. In this case, a
  1179. // StaggerConnectionWorkersMilliseconds delay may still be incurred.
  1180. excludeMeek := false
  1181. controller.concurrentEstablishTunnelsMutex.Lock()
  1182. if controller.config.LimitMeekConnectionWorkers > 0 &&
  1183. controller.concurrentMeekEstablishTunnels >=
  1184. controller.config.LimitMeekConnectionWorkers {
  1185. excludeMeek = true
  1186. }
  1187. controller.concurrentEstablishTunnelsMutex.Unlock()
  1188. selectedProtocol, err := selectProtocol(
  1189. controller.config, candidateServerEntry.serverEntry, excludeMeek)
  1190. if err == errProtocolNotSupported {
  1191. // selectProtocol returns errProtocolNotSupported when excludeMeek
  1192. // is set and the server entry only supports meek protocols.
  1193. // Skip this candidate.
  1194. continue
  1195. }
  1196. var tunnel *Tunnel
  1197. if err == nil {
  1198. isMeek := protocol.TunnelProtocolUsesMeek(selectedProtocol) ||
  1199. protocol.TunnelProtocolUsesMeek(selectedProtocol)
  1200. controller.concurrentEstablishTunnelsMutex.Lock()
  1201. if isMeek {
  1202. // Recheck the limit now that we know we're selecting meek and
  1203. // adjusting concurrentMeekEstablishTunnels.
  1204. if controller.config.LimitMeekConnectionWorkers > 0 &&
  1205. controller.concurrentMeekEstablishTunnels >=
  1206. controller.config.LimitMeekConnectionWorkers {
  1207. // Skip this candidate.
  1208. controller.concurrentEstablishTunnelsMutex.Unlock()
  1209. continue
  1210. }
  1211. controller.concurrentMeekEstablishTunnels += 1
  1212. if controller.concurrentMeekEstablishTunnels > controller.peakConcurrentMeekEstablishTunnels {
  1213. controller.peakConcurrentMeekEstablishTunnels = controller.concurrentMeekEstablishTunnels
  1214. }
  1215. }
  1216. controller.concurrentEstablishTunnels += 1
  1217. if controller.concurrentEstablishTunnels > controller.peakConcurrentEstablishTunnels {
  1218. controller.peakConcurrentEstablishTunnels = controller.concurrentEstablishTunnels
  1219. }
  1220. controller.concurrentEstablishTunnelsMutex.Unlock()
  1221. tunnel, err = EstablishTunnel(
  1222. controller.config,
  1223. controller.untunneledDialConfig,
  1224. controller.sessionId,
  1225. controller.establishPendingConns,
  1226. candidateServerEntry.serverEntry,
  1227. selectedProtocol,
  1228. candidateServerEntry.adjustedEstablishStartTime,
  1229. controller) // TunnelOwner
  1230. controller.concurrentEstablishTunnelsMutex.Lock()
  1231. if isMeek {
  1232. controller.concurrentMeekEstablishTunnels -= 1
  1233. }
  1234. controller.concurrentEstablishTunnels -= 1
  1235. controller.concurrentEstablishTunnelsMutex.Unlock()
  1236. }
  1237. // Periodically emit memory metrics during the establishment cycle.
  1238. if !controller.isStopEstablishingBroadcast() {
  1239. emitMemoryMetrics()
  1240. }
  1241. // Immediately reclaim memory allocated by the establishment. In the case
  1242. // of failure, first clear the reference to the tunnel. In the case of
  1243. // success, the garbage collection may still be effective as the initial
  1244. // phases of some protocols involve significant memory allocation that
  1245. // could now be reclaimed.
  1246. if err != nil {
  1247. tunnel = nil
  1248. }
  1249. aggressiveGarbageCollection()
  1250. if err != nil {
  1251. // Unblock other candidates immediately when
  1252. // server affinity candidate fails.
  1253. if candidateServerEntry.isServerAffinityCandidate {
  1254. close(controller.serverAffinityDoneBroadcast)
  1255. }
  1256. // Before emitting error, check if establish interrupted, in which
  1257. // case the error is noise.
  1258. if controller.isStopEstablishingBroadcast() {
  1259. break loop
  1260. }
  1261. NoticeInfo("failed to connect to %s: %s", candidateServerEntry.serverEntry.IpAddress, err)
  1262. continue
  1263. }
  1264. // Deliver established tunnel.
  1265. // Don't block. Assumes the receiver has a buffer large enough for
  1266. // the number of desired tunnels. If there's no room, the tunnel must
  1267. // not be required so it's discarded.
  1268. select {
  1269. case controller.establishedTunnels <- tunnel:
  1270. default:
  1271. controller.discardTunnel(tunnel)
  1272. // Clear the reference to this discarded tunnel and immediately run
  1273. // a garbage collection to reclaim its memory.
  1274. tunnel = nil
  1275. aggressiveGarbageCollection()
  1276. }
  1277. // Unblock other candidates only after delivering when
  1278. // server affinity candidate succeeds.
  1279. if candidateServerEntry.isServerAffinityCandidate {
  1280. close(controller.serverAffinityDoneBroadcast)
  1281. }
  1282. }
  1283. NoticeInfo("stopped establish worker")
  1284. }
  1285. func (controller *Controller) isStopEstablishingBroadcast() bool {
  1286. select {
  1287. case <-controller.stopEstablishingBroadcast:
  1288. return true
  1289. default:
  1290. }
  1291. return false
  1292. }