controller.go 18 KB

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