controller.go 48 KB

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