controller.go 47 KB

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