controller.go 42 KB

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