controller.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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. "net"
  27. "sync"
  28. "time"
  29. )
  30. // Controller is a tunnel lifecycle coordinator. It manages lists of servers to
  31. // connect to; establishes and monitors tunnels; and runs local proxies which
  32. // route traffic through the tunnels.
  33. type Controller struct {
  34. config *Config
  35. sessionId string
  36. componentFailureSignal chan struct{}
  37. shutdownBroadcast chan struct{}
  38. runWaitGroup *sync.WaitGroup
  39. establishedTunnels chan *Tunnel
  40. failedTunnels chan *Tunnel
  41. tunnelMutex sync.Mutex
  42. tunnels []*Tunnel
  43. nextTunnel int
  44. startedConnectedReporter bool
  45. isEstablishing bool
  46. establishWaitGroup *sync.WaitGroup
  47. stopEstablishingBroadcast chan struct{}
  48. candidateServerEntries chan *ServerEntry
  49. establishPendingConns *Conns
  50. fetchRemotePendingConns *Conns
  51. }
  52. // NewController initializes a new controller.
  53. func NewController(config *Config) (controller *Controller, err error) {
  54. // Generate a session ID for the Psiphon server API. This session ID is
  55. // used across all tunnels established by the controller.
  56. sessionId, err := MakeSessionId()
  57. if err != nil {
  58. return nil, ContextError(err)
  59. }
  60. return &Controller{
  61. config: config,
  62. sessionId: sessionId,
  63. // componentFailureSignal receives a signal from a component (including socks and
  64. // http local proxies) if they unexpectedly fail. Senders should not block.
  65. // A buffer allows at least one stop signal to be sent before there is a receiver.
  66. componentFailureSignal: make(chan struct{}, 1),
  67. shutdownBroadcast: make(chan struct{}),
  68. runWaitGroup: new(sync.WaitGroup),
  69. // establishedTunnels and failedTunnels buffer sizes are large enough to
  70. // receive full pools of tunnels without blocking. Senders should not block.
  71. establishedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  72. failedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  73. tunnels: make([]*Tunnel, 0),
  74. startedConnectedReporter: false,
  75. isEstablishing: false,
  76. establishPendingConns: new(Conns),
  77. fetchRemotePendingConns: new(Conns),
  78. }, nil
  79. }
  80. // Run executes the controller. It launches components and then monitors
  81. // for a shutdown signal; after receiving the signal it shuts down the
  82. // controller.
  83. // The components include:
  84. // - the periodic remote server list fetcher
  85. // - the connected reporter
  86. // - the tunnel manager
  87. // - a local SOCKS proxy that port forwards through the pool of tunnels
  88. // - a local HTTP proxy that port forwards through the pool of tunnels
  89. func (controller *Controller) Run(shutdownBroadcast <-chan struct{}) {
  90. Notice(NOTICE_VERSION, VERSION)
  91. socksProxy, err := NewSocksProxy(controller.config, controller)
  92. if err != nil {
  93. Notice(NOTICE_ALERT, "error initializing local SOCKS proxy: %s", err)
  94. return
  95. }
  96. defer socksProxy.Close()
  97. httpProxy, err := NewHttpProxy(controller.config, controller)
  98. if err != nil {
  99. Notice(NOTICE_ALERT, "error initializing local HTTP proxy: %s", err)
  100. return
  101. }
  102. defer httpProxy.Close()
  103. /// Note: the connected reporter isn't started until a tunnel is established
  104. controller.runWaitGroup.Add(2)
  105. go controller.remoteServerListFetcher()
  106. go controller.runTunnels()
  107. select {
  108. case <-shutdownBroadcast:
  109. Notice(NOTICE_INFO, "controller shutdown by request")
  110. case <-controller.componentFailureSignal:
  111. Notice(NOTICE_ALERT, "controller shutdown due to component failure")
  112. }
  113. close(controller.shutdownBroadcast)
  114. controller.establishPendingConns.CloseAll()
  115. controller.fetchRemotePendingConns.CloseAll()
  116. controller.runWaitGroup.Wait()
  117. Notice(NOTICE_INFO, "exiting controller")
  118. }
  119. // SignalComponentFailure notifies the controller that an associated component has failed.
  120. // This will terminate the controller.
  121. func (controller *Controller) SignalComponentFailure() {
  122. select {
  123. case controller.componentFailureSignal <- *new(struct{}):
  124. default:
  125. }
  126. }
  127. // remoteServerListFetcher fetches an out-of-band list of server entries
  128. // for more tunnel candidates. It fetches immediately, retries after failure
  129. // with a wait period, and refetches after success with a longer wait period.
  130. func (controller *Controller) remoteServerListFetcher() {
  131. defer controller.runWaitGroup.Done()
  132. // Note: unlike legacy Psiphon clients, this code
  133. // always makes the fetch remote server list request
  134. loop:
  135. for {
  136. err := FetchRemoteServerList(
  137. controller.config, controller.fetchRemotePendingConns)
  138. var duration time.Duration
  139. if err != nil {
  140. Notice(NOTICE_ALERT, "failed to fetch remote server list: %s", err)
  141. duration = FETCH_REMOTE_SERVER_LIST_RETRY_PERIOD
  142. } else {
  143. duration = FETCH_REMOTE_SERVER_LIST_STALE_PERIOD
  144. }
  145. timeout := time.After(duration)
  146. select {
  147. case <-timeout:
  148. // Fetch again
  149. case <-controller.shutdownBroadcast:
  150. break loop
  151. }
  152. }
  153. Notice(NOTICE_INFO, "exiting remote server list fetcher")
  154. }
  155. // connectedReporter sends periodic "connected" requests to the Psiphon API.
  156. // These requests are for server-side unique user stats calculation. See the
  157. // comment in DoConnectedRequest for a description of the request mechanism.
  158. // To ensure we don't over- or under-count unique users, only one connected
  159. // request is made across all simultaneous multi-tunnels; and the connected
  160. // request is repeated periodically.
  161. func (controller *Controller) connectedReporter() {
  162. defer controller.runWaitGroup.Done()
  163. loop:
  164. for {
  165. // Pick any active tunnel and make the next connected request. No error
  166. // is logged if there's no active tunnel, as that's not an unexpected condition.
  167. reported := false
  168. tunnel := controller.getNextActiveTunnel()
  169. if tunnel != nil {
  170. err := tunnel.session.DoConnectedRequest()
  171. if err == nil {
  172. reported = true
  173. } else {
  174. Notice(NOTICE_ALERT, "failed to make connected request: %s", err)
  175. }
  176. }
  177. // Schedule the next connected request and wait.
  178. var duration time.Duration
  179. if reported {
  180. duration = PSIPHON_API_CONNECTED_REQUEST_PERIOD
  181. } else {
  182. duration = PSIPHON_API_CONNECTED_REQUEST_RETRY_PERIOD
  183. }
  184. timeout := time.After(duration)
  185. select {
  186. case <-timeout:
  187. // Make another connected request
  188. case <-controller.shutdownBroadcast:
  189. break loop
  190. }
  191. }
  192. Notice(NOTICE_INFO, "exiting connected reporter")
  193. }
  194. // runTunnels is the controller tunnel management main loop. It starts and stops
  195. // establishing tunnels based on the target tunnel pool size and the current size
  196. // of the pool. Tunnels are established asynchronously using worker goroutines.
  197. // When a tunnel is established, it's added to the active pool. The tunnel's
  198. // operateTunnel goroutine monitors the tunnel.
  199. // When a tunnel fails, it's removed from the pool and the establish process is
  200. // restarted to fill the pool.
  201. func (controller *Controller) runTunnels() {
  202. defer controller.runWaitGroup.Done()
  203. // Don't start establishing until there are some server candidates. The
  204. // typical case is a client with no server entries which will wait for
  205. // the first successful FetchRemoteServerList to populate the data store.
  206. for {
  207. if HasServerEntries(
  208. controller.config.EgressRegion, controller.config.TunnelProtocol) {
  209. break
  210. }
  211. // TODO: replace polling with signal
  212. timeout := time.After(5 * time.Second)
  213. select {
  214. case <-timeout:
  215. case <-controller.shutdownBroadcast:
  216. return
  217. }
  218. }
  219. controller.startEstablishing()
  220. loop:
  221. for {
  222. select {
  223. case failedTunnel := <-controller.failedTunnels:
  224. Notice(NOTICE_ALERT, "tunnel failed: %s", failedTunnel.serverEntry.IpAddress)
  225. controller.terminateTunnel(failedTunnel)
  226. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing
  227. // and access isEstablishing.
  228. if !controller.isEstablishing {
  229. controller.startEstablishing()
  230. }
  231. // !TODO! design issue: might not be enough server entries with region/caps to ever fill tunnel slots
  232. // solution(?) target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  233. case establishedTunnel := <-controller.establishedTunnels:
  234. Notice(NOTICE_INFO, "established tunnel: %s", establishedTunnel.serverEntry.IpAddress)
  235. if controller.registerTunnel(establishedTunnel) {
  236. Notice(NOTICE_INFO, "active tunnel: %s", establishedTunnel.serverEntry.IpAddress)
  237. } else {
  238. controller.discardTunnel(establishedTunnel)
  239. }
  240. if controller.isFullyEstablished() {
  241. controller.stopEstablishing()
  242. }
  243. // Start the connected reporter after the first tunnel is established.
  244. // Concurrency note: only this goroutine may access startedConnectedReporter.
  245. // isEstablishing.
  246. if !controller.startedConnectedReporter {
  247. controller.startedConnectedReporter = true
  248. controller.runWaitGroup.Add(1)
  249. go controller.connectedReporter()
  250. }
  251. case <-controller.shutdownBroadcast:
  252. break loop
  253. }
  254. }
  255. controller.stopEstablishing()
  256. controller.terminateAllTunnels()
  257. // Drain tunnel channels
  258. close(controller.establishedTunnels)
  259. for tunnel := range controller.establishedTunnels {
  260. controller.discardTunnel(tunnel)
  261. }
  262. close(controller.failedTunnels)
  263. for tunnel := range controller.failedTunnels {
  264. controller.discardTunnel(tunnel)
  265. }
  266. Notice(NOTICE_INFO, "exiting run tunnels")
  267. }
  268. // SignalTunnelFailure implements the TunnelOwner interface. This function
  269. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  270. // has failed. The Controller will signal runTunnels to create a new
  271. // tunnel and/or remove the tunnel from the list of active tunnels.
  272. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  273. // Don't block. Assumes the receiver has a buffer large enough for
  274. // the typical number of operated tunnels. In case there's no room,
  275. // terminate the tunnel (runTunnels won't get a signal in this case,
  276. // but the tunnel will be removed from the list of active tunnels).
  277. select {
  278. case controller.failedTunnels <- tunnel:
  279. default:
  280. controller.terminateTunnel(tunnel)
  281. }
  282. }
  283. // discardTunnel disposes of a successful connection that is no longer required.
  284. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  285. Notice(NOTICE_INFO, "discard tunnel: %s", tunnel.serverEntry.IpAddress)
  286. // TODO: not calling PromoteServerEntry, since that would rank the
  287. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  288. // be promoted (since it connects), but with lower rank than all active
  289. // tunnels?
  290. tunnel.Close()
  291. }
  292. // registerTunnel adds the connected tunnel to the pool of active tunnels
  293. // which are candidates for port forwarding. Returns true if the pool has an
  294. // empty slot and false if the pool is full (caller should discard the tunnel).
  295. func (controller *Controller) registerTunnel(tunnel *Tunnel) bool {
  296. controller.tunnelMutex.Lock()
  297. defer controller.tunnelMutex.Unlock()
  298. if len(controller.tunnels) >= controller.config.TunnelPoolSize {
  299. return false
  300. }
  301. // Perform a final check just in case we've established
  302. // a duplicate connection.
  303. for _, activeTunnel := range controller.tunnels {
  304. if activeTunnel.serverEntry.IpAddress == tunnel.serverEntry.IpAddress {
  305. Notice(NOTICE_ALERT, "duplicate tunnel: %s", tunnel.serverEntry.IpAddress)
  306. return false
  307. }
  308. }
  309. controller.tunnels = append(controller.tunnels, tunnel)
  310. Notice(NOTICE_TUNNELS, "%d", len(controller.tunnels))
  311. return true
  312. }
  313. // isFullyEstablished indicates if the pool of active tunnels is full.
  314. func (controller *Controller) isFullyEstablished() bool {
  315. controller.tunnelMutex.Lock()
  316. defer controller.tunnelMutex.Unlock()
  317. return len(controller.tunnels) >= controller.config.TunnelPoolSize
  318. }
  319. // terminateTunnel removes a tunnel from the pool of active tunnels
  320. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  321. // is adjusted as required.
  322. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  323. controller.tunnelMutex.Lock()
  324. defer controller.tunnelMutex.Unlock()
  325. for index, activeTunnel := range controller.tunnels {
  326. if tunnel == activeTunnel {
  327. controller.tunnels = append(
  328. controller.tunnels[:index], controller.tunnels[index+1:]...)
  329. if controller.nextTunnel > index {
  330. controller.nextTunnel--
  331. }
  332. if controller.nextTunnel >= len(controller.tunnels) {
  333. controller.nextTunnel = 0
  334. }
  335. activeTunnel.Close()
  336. Notice(NOTICE_TUNNELS, "%d", len(controller.tunnels))
  337. break
  338. }
  339. }
  340. }
  341. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  342. // This is used when shutting down the controller.
  343. func (controller *Controller) terminateAllTunnels() {
  344. controller.tunnelMutex.Lock()
  345. defer controller.tunnelMutex.Unlock()
  346. for _, activeTunnel := range controller.tunnels {
  347. activeTunnel.Close()
  348. }
  349. controller.tunnels = make([]*Tunnel, 0)
  350. controller.nextTunnel = 0
  351. Notice(NOTICE_TUNNELS, "%d", len(controller.tunnels))
  352. }
  353. // getNextActiveTunnel returns the next tunnel from the pool of active
  354. // tunnels. Currently, tunnel selection order is simple round-robin.
  355. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  356. controller.tunnelMutex.Lock()
  357. defer controller.tunnelMutex.Unlock()
  358. for i := len(controller.tunnels); i > 0; i-- {
  359. tunnel = controller.tunnels[controller.nextTunnel]
  360. controller.nextTunnel =
  361. (controller.nextTunnel + 1) % len(controller.tunnels)
  362. return tunnel
  363. }
  364. return nil
  365. }
  366. // isActiveTunnelServerEntries is used to check if there's already
  367. // an existing tunnel to a candidate server.
  368. func (controller *Controller) isActiveTunnelServerEntry(serverEntry *ServerEntry) bool {
  369. controller.tunnelMutex.Lock()
  370. defer controller.tunnelMutex.Unlock()
  371. for _, activeTunnel := range controller.tunnels {
  372. if activeTunnel.serverEntry.IpAddress == serverEntry.IpAddress {
  373. return true
  374. }
  375. }
  376. return false
  377. }
  378. // Dial selects an active tunnel and establishes a port forward
  379. // connection through the selected tunnel. Failure to connect is considered
  380. // a port foward failure, for the purpose of monitoring tunnel health.
  381. func (controller *Controller) Dial(remoteAddr string) (conn net.Conn, err error) {
  382. tunnel := controller.getNextActiveTunnel()
  383. if tunnel == nil {
  384. return nil, ContextError(errors.New("no active tunnels"))
  385. }
  386. tunneledConn, err := tunnel.Dial(remoteAddr)
  387. if err != nil {
  388. return nil, ContextError(err)
  389. }
  390. statsConn := NewStatsConn(
  391. tunneledConn, tunnel.session.StatsServerID(), tunnel.session.StatsRegexps())
  392. return statsConn, nil
  393. }
  394. // startEstablishing creates a pool of worker goroutines which will
  395. // attempt to establish tunnels to candidate servers. The candidates
  396. // are generated by another goroutine.
  397. func (controller *Controller) startEstablishing() {
  398. if controller.isEstablishing {
  399. return
  400. }
  401. Notice(NOTICE_INFO, "start establishing")
  402. controller.isEstablishing = true
  403. controller.establishWaitGroup = new(sync.WaitGroup)
  404. controller.stopEstablishingBroadcast = make(chan struct{})
  405. controller.candidateServerEntries = make(chan *ServerEntry)
  406. controller.establishPendingConns.Reset()
  407. for i := 0; i < controller.config.ConnectionWorkerPoolSize; i++ {
  408. controller.establishWaitGroup.Add(1)
  409. go controller.establishTunnelWorker()
  410. }
  411. controller.establishWaitGroup.Add(1)
  412. go controller.establishCandidateGenerator()
  413. }
  414. // stopEstablishing signals the establish goroutines to stop and waits
  415. // for the group to halt. pendingConns is used to interrupt any worker
  416. // blocked on a socket connect.
  417. func (controller *Controller) stopEstablishing() {
  418. if !controller.isEstablishing {
  419. return
  420. }
  421. Notice(NOTICE_INFO, "stop establishing")
  422. close(controller.stopEstablishingBroadcast)
  423. // Note: on Windows, interruptibleTCPClose doesn't really interrupt socket connects
  424. // and may leave goroutines running for a time after the Wait call.
  425. controller.establishPendingConns.CloseAll()
  426. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  427. // (as it may be sending to that channel).
  428. controller.establishWaitGroup.Wait()
  429. controller.isEstablishing = false
  430. controller.establishWaitGroup = nil
  431. controller.stopEstablishingBroadcast = nil
  432. controller.candidateServerEntries = nil
  433. }
  434. // establishCandidateGenerator populates the candidate queue with server entries
  435. // from the data store. Server entries are iterated in rank order, so that promoted
  436. // servers with higher rank are priority candidates.
  437. func (controller *Controller) establishCandidateGenerator() {
  438. defer controller.establishWaitGroup.Done()
  439. iterator, err := NewServerEntryIterator(
  440. controller.config.EgressRegion, controller.config.TunnelProtocol)
  441. if err != nil {
  442. Notice(NOTICE_ALERT, "failed to iterate over candidates: %s", err)
  443. controller.SignalComponentFailure()
  444. return
  445. }
  446. defer iterator.Close()
  447. loop:
  448. for {
  449. for {
  450. serverEntry, err := iterator.Next()
  451. if err != nil {
  452. Notice(NOTICE_ALERT, "failed to get next candidate: %s", err)
  453. controller.SignalComponentFailure()
  454. break loop
  455. }
  456. if serverEntry == nil {
  457. // Completed this iteration
  458. break
  459. }
  460. select {
  461. case controller.candidateServerEntries <- serverEntry:
  462. case <-controller.stopEstablishingBroadcast:
  463. break loop
  464. case <-controller.shutdownBroadcast:
  465. break loop
  466. }
  467. }
  468. iterator.Reset()
  469. // After a complete iteration of candidate servers, pause before iterating again.
  470. // This helps avoid some busy wait loop conditions, and also allows some time for
  471. // network conditions to change.
  472. timeout := time.After(ESTABLISH_TUNNEL_PAUSE_PERIOD)
  473. select {
  474. case <-timeout:
  475. // Retry iterating
  476. case <-controller.stopEstablishingBroadcast:
  477. break loop
  478. case <-controller.shutdownBroadcast:
  479. break loop
  480. }
  481. }
  482. close(controller.candidateServerEntries)
  483. Notice(NOTICE_INFO, "stopped candidate generator")
  484. }
  485. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  486. // a connection to the tunnel server, and delivers the established tunnel to a channel.
  487. func (controller *Controller) establishTunnelWorker() {
  488. defer controller.establishWaitGroup.Done()
  489. loop:
  490. for serverEntry := range controller.candidateServerEntries {
  491. // Note: don't receive from candidateServerEntries and stopEstablishingBroadcast
  492. // in the same select, since we want to prioritize receiving the stop signal
  493. if controller.isStopEstablishingBroadcast() {
  494. break loop
  495. }
  496. // There may already be a tunnel to this candidate. If so, skip it.
  497. if controller.isActiveTunnelServerEntry(serverEntry) {
  498. continue
  499. }
  500. tunnel, err := EstablishTunnel(
  501. controller.config,
  502. controller.sessionId,
  503. controller.establishPendingConns,
  504. serverEntry,
  505. controller) // TunnelOwner
  506. if err != nil {
  507. // Before emitting error, check if establish interrupted, in which
  508. // case the error is noise.
  509. if controller.isStopEstablishingBroadcast() {
  510. break loop
  511. }
  512. Notice(NOTICE_INFO, "failed to connect to %s: %s", serverEntry.IpAddress, err)
  513. continue
  514. }
  515. // Deliver established tunnel.
  516. // Don't block. Assumes the receiver has a buffer large enough for
  517. // the number of desired tunnels. If there's no room, the tunnel must
  518. // not be required so it's discarded.
  519. select {
  520. case controller.establishedTunnels <- tunnel:
  521. default:
  522. controller.discardTunnel(tunnel)
  523. }
  524. }
  525. Notice(NOTICE_INFO, "stopped establish worker")
  526. }
  527. func (controller *Controller) isStopEstablishingBroadcast() bool {
  528. select {
  529. case <-controller.stopEstablishingBroadcast:
  530. return true
  531. default:
  532. }
  533. return false
  534. }