controller.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. /*
  2. * Copyright (c) 2014, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. // Package psiphon implements the core tunnel functionality of a Psiphon client.
  20. // The main function is RunForever, which runs a Controller that obtains lists of
  21. // servers, establishes tunnel connections, and runs local proxies through which
  22. // tunneled traffic may be sent.
  23. package psiphon
  24. import (
  25. "errors"
  26. "fmt"
  27. "log"
  28. "net"
  29. "os"
  30. "sync"
  31. "time"
  32. )
  33. // Controller is a tunnel lifecycle coordinator. It manages lists of servers to
  34. // connect to; establishes and monitors tunnels; and runs local proxies which
  35. // route traffic through the tunnels.
  36. type Controller struct {
  37. config *Config
  38. failureSignal chan struct{}
  39. shutdownBroadcast chan struct{}
  40. runWaitGroup *sync.WaitGroup
  41. establishedTunnels chan *Tunnel
  42. failedTunnels chan *Tunnel
  43. tunnelMutex sync.Mutex
  44. tunnels []*Tunnel
  45. nextTunnel int
  46. operateWaitGroup *sync.WaitGroup
  47. isEstablishing bool
  48. establishWaitGroup *sync.WaitGroup
  49. stopEstablishingBroadcast chan struct{}
  50. candidateServerEntries chan *ServerEntry
  51. pendingConns *Conns
  52. }
  53. // NewController initializes a new controller.
  54. func NewController(config *Config) (controller *Controller) {
  55. return &Controller{
  56. config: config,
  57. // failureSignal receives a signal from a component (including socks and
  58. // http local proxies) if they unexpectedly fail. Senders should not block.
  59. // A buffer allows at least one stop signal to be sent before there is a receiver.
  60. failureSignal: make(chan struct{}, 1),
  61. shutdownBroadcast: make(chan struct{}),
  62. runWaitGroup: new(sync.WaitGroup),
  63. // establishedTunnels and failedTunnels buffer sizes are large enough to
  64. // receive full pools of tunnels without blocking. Senders should not block.
  65. establishedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  66. failedTunnels: make(chan *Tunnel, config.TunnelPoolSize),
  67. tunnels: make([]*Tunnel, 0),
  68. operateWaitGroup: new(sync.WaitGroup),
  69. isEstablishing: false,
  70. pendingConns: new(Conns),
  71. }
  72. }
  73. // Run executes the controller. It launches components and then monitors
  74. // for a shutdown signal; after receiving the signal it shuts down the
  75. // controller.
  76. // The components include:
  77. // - the periodic remote server list fetcher
  78. // - the tunnel manager
  79. // - a local SOCKS proxy that port forwards through the pool of tunnels
  80. // - a local HTTP proxy that port forwards through the pool of tunnels
  81. func (controller *Controller) Run(shutdownBroadcast <-chan struct{}) {
  82. socksProxy, err := NewSocksProxy(controller.config, controller)
  83. if err != nil {
  84. Notice(NOTICE_ALERT, "error initializing local SOCKS proxy: %s", err)
  85. return
  86. }
  87. defer socksProxy.Close()
  88. httpProxy, err := NewHttpProxy(controller.config, controller)
  89. if err != nil {
  90. Notice(NOTICE_ALERT, "error initializing local SOCKS proxy: %s", err)
  91. return
  92. }
  93. defer httpProxy.Close()
  94. controller.runWaitGroup.Add(2)
  95. go controller.remoteServerListFetcher()
  96. go controller.runTunnels()
  97. select {
  98. case <-shutdownBroadcast:
  99. Notice(NOTICE_INFO, "controller shutdown by request")
  100. case <-controller.failureSignal:
  101. Notice(NOTICE_ALERT, "controller shutdown due to failure")
  102. }
  103. // Note: in addition to establish(), this pendingConns will interrupt
  104. // FetchRemoteServerList
  105. controller.pendingConns.CloseAll()
  106. close(controller.shutdownBroadcast)
  107. controller.runWaitGroup.Wait()
  108. Notice(NOTICE_INFO, "exiting controller")
  109. }
  110. // SignalFailure notifies the controller that an associated component has failed.
  111. // This will terminate the controller.
  112. func (controller *Controller) SignalFailure() {
  113. select {
  114. case controller.failureSignal <- *new(struct{}):
  115. default:
  116. }
  117. }
  118. // remoteServerListFetcher fetches an out-of-band list of server entries
  119. // for more tunnel candidates. It fetches immediately, retries after failure
  120. // with a wait period, and refetches after success with a longer wait period.
  121. func (controller *Controller) remoteServerListFetcher() {
  122. defer controller.runWaitGroup.Done()
  123. // Note: unlike existing Psiphon clients, this code
  124. // always makes the fetch remote server list request
  125. loop:
  126. for {
  127. // TODO: FetchRemoteServerList should have its own pendingConns,
  128. // otherwise it may needlessly abort when establish is stopped.
  129. err := FetchRemoteServerList(controller.config, controller.pendingConns)
  130. var duration time.Duration
  131. if err != nil {
  132. Notice(NOTICE_ALERT, "failed to fetch remote server list: %s", err)
  133. duration = FETCH_REMOTE_SERVER_LIST_RETRY_TIMEOUT
  134. } else {
  135. duration = FETCH_REMOTE_SERVER_LIST_STALE_TIMEOUT
  136. }
  137. timeout := time.After(duration)
  138. select {
  139. case <-timeout:
  140. // Fetch again
  141. case <-controller.shutdownBroadcast:
  142. break loop
  143. }
  144. }
  145. Notice(NOTICE_INFO, "exiting remote server list fetcher")
  146. }
  147. // runTunnels is the controller tunnel management main loop. It starts and stops
  148. // establishing tunnels based on the target tunnel pool size and the current size
  149. // of the pool. Tunnels are established asynchronously using worker goroutines.
  150. // When a tunnel is established, it's added to the active pool and a corresponding
  151. // operateTunnel goroutine is launched which starts a session in the tunnel and
  152. // monitors the tunnel for failures.
  153. // When a tunnel fails, it's removed from the pool and the establish process is
  154. // restarted to fill the pool.
  155. func (controller *Controller) runTunnels() {
  156. defer controller.runWaitGroup.Done()
  157. // Don't start establishing until there are some server candidates. The
  158. // typical case is a client with no server entries which will wait for
  159. // the first successful FetchRemoteServerList to populate the data store.
  160. for {
  161. if HasServerEntries(
  162. controller.config.EgressRegion, controller.config.TunnelProtocol) {
  163. break
  164. }
  165. // TODO: replace polling with signal
  166. timeout := time.After(1 * time.Second)
  167. select {
  168. case <-timeout:
  169. case <-controller.shutdownBroadcast:
  170. return
  171. }
  172. }
  173. controller.startEstablishing()
  174. loop:
  175. for {
  176. select {
  177. case failedTunnel := <-controller.failedTunnels:
  178. Notice(NOTICE_ALERT, "tunnel failed: %s", failedTunnel.serverEntry.IpAddress)
  179. controller.terminateTunnel(failedTunnel)
  180. // Note: only this goroutine may call startEstablishing/stopEstablishing and access
  181. // isEstablishing.
  182. if !controller.isEstablishing {
  183. controller.startEstablishing()
  184. }
  185. // !TODO! design issue: might not be enough server entries with region/caps to ever fill tunnel slots
  186. // solution(?) target MIN(CountServerEntries(region, protocol), TunnelPoolSize)
  187. case establishedTunnel := <-controller.establishedTunnels:
  188. Notice(NOTICE_INFO, "established tunnel: %s", establishedTunnel.serverEntry.IpAddress)
  189. // !TODO! design issue: activateTunnel makes tunnel avail for port forward *before* operates does handshake
  190. // solution(?) distinguish between two stages or states: connected, and then active.
  191. if controller.activateTunnel(establishedTunnel) {
  192. Notice(NOTICE_INFO, "active tunnel: %s", establishedTunnel.serverEntry.IpAddress)
  193. controller.operateWaitGroup.Add(1)
  194. go controller.operateTunnel(establishedTunnel)
  195. } else {
  196. controller.discardTunnel(establishedTunnel)
  197. }
  198. if controller.isFullyEstablished() {
  199. controller.stopEstablishing()
  200. }
  201. case <-controller.shutdownBroadcast:
  202. break loop
  203. }
  204. }
  205. controller.stopEstablishing()
  206. controller.terminateAllTunnels()
  207. controller.operateWaitGroup.Wait()
  208. // Drain tunnel channels
  209. close(controller.establishedTunnels)
  210. for tunnel := range controller.establishedTunnels {
  211. controller.discardTunnel(tunnel)
  212. }
  213. close(controller.failedTunnels)
  214. for tunnel := range controller.failedTunnels {
  215. controller.discardTunnel(tunnel)
  216. }
  217. Notice(NOTICE_INFO, "exiting run tunnels")
  218. }
  219. // discardTunnel disposes of a successful connection that is no longer required.
  220. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  221. Notice(NOTICE_INFO, "discard tunnel: %s", tunnel.serverEntry.IpAddress)
  222. // TODO: not calling PromoteServerEntry, since that would rank the
  223. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  224. // be promoted (since it connects), but with lower rank than all active
  225. // tunnels?
  226. tunnel.Close()
  227. }
  228. // activateTunnel adds the connected tunnel to the pool of active tunnels
  229. // which are used for port forwarding. Returns true if the pool has an empty
  230. // slot and false if the pool is full (caller should discard the tunnel).
  231. func (controller *Controller) activateTunnel(tunnel *Tunnel) bool {
  232. controller.tunnelMutex.Lock()
  233. defer controller.tunnelMutex.Unlock()
  234. // !TODO! double check not already a tunnel to this server
  235. if len(controller.tunnels) >= controller.config.TunnelPoolSize {
  236. return false
  237. }
  238. controller.tunnels = append(controller.tunnels, tunnel)
  239. Notice(NOTICE_TUNNEL, "%d tunnels", len(controller.tunnels))
  240. return true
  241. }
  242. // isFullyEstablished indicates if the pool of active tunnels is full.
  243. func (controller *Controller) isFullyEstablished() bool {
  244. controller.tunnelMutex.Lock()
  245. defer controller.tunnelMutex.Unlock()
  246. return len(controller.tunnels) >= controller.config.TunnelPoolSize
  247. }
  248. // terminateTunnel removes a tunnel from the pool of active tunnels
  249. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  250. // is adjusted as required.
  251. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  252. controller.tunnelMutex.Lock()
  253. defer controller.tunnelMutex.Unlock()
  254. for index, activeTunnel := range controller.tunnels {
  255. if tunnel == activeTunnel {
  256. controller.tunnels = append(
  257. controller.tunnels[:index], controller.tunnels[index+1:]...)
  258. if controller.nextTunnel > index {
  259. controller.nextTunnel--
  260. }
  261. if controller.nextTunnel >= len(controller.tunnels) {
  262. controller.nextTunnel = 0
  263. }
  264. activeTunnel.Close()
  265. Notice(NOTICE_TUNNEL, "%d tunnels", len(controller.tunnels))
  266. break
  267. }
  268. }
  269. }
  270. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  271. // This is used when shutting down the controller.
  272. func (controller *Controller) terminateAllTunnels() {
  273. controller.tunnelMutex.Lock()
  274. defer controller.tunnelMutex.Unlock()
  275. for _, activeTunnel := range controller.tunnels {
  276. activeTunnel.Close()
  277. }
  278. controller.tunnels = make([]*Tunnel, 0)
  279. controller.nextTunnel = 0
  280. Notice(NOTICE_TUNNEL, "%d tunnels", len(controller.tunnels))
  281. }
  282. // getNextActiveTunnel returns the next tunnel from the pool of active
  283. // tunnels. Currently, tunnel selection order is simple round-robin.
  284. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  285. controller.tunnelMutex.Lock()
  286. defer controller.tunnelMutex.Unlock()
  287. if len(controller.tunnels) == 0 {
  288. return nil
  289. }
  290. tunnel = controller.tunnels[controller.nextTunnel]
  291. controller.nextTunnel =
  292. (controller.nextTunnel + 1) % len(controller.tunnels)
  293. return tunnel
  294. }
  295. // getActiveTunnelServerEntries lists the Server Entries for
  296. // all the active tunnels. This is used to exclude those servers
  297. // from the set of candidates to establish connections to.
  298. func (controller *Controller) getActiveTunnelServerEntries() (serverEntries []*ServerEntry) {
  299. controller.tunnelMutex.Lock()
  300. defer controller.tunnelMutex.Unlock()
  301. serverEntries = make([]*ServerEntry, 0)
  302. for _, activeTunnel := range controller.tunnels {
  303. serverEntries = append(serverEntries, activeTunnel.serverEntry)
  304. }
  305. return serverEntries
  306. }
  307. // operateTunnel starts a Psiphon session (handshake, etc.) on a newly
  308. // connected tunnel, and then monitors the tunnel for failures:
  309. //
  310. // 1. Overall tunnel failure: the tunnel sends a signal to the ClosedSignal
  311. // channel on keep-alive failure and other transport I/O errors. In case
  312. // of such a failure, the tunnel is marked as failed.
  313. //
  314. // 2. Tunnel port forward failures: the tunnel connection may stay up but
  315. // the client may still fail to establish port forwards due to server load
  316. // and other conditions. After a threshold number of such failures, the
  317. // overall tunnel is marked as failed.
  318. //
  319. // TODO: currently, any connect (dial), read, or write error associated with
  320. // a port forward is counted as a failure. It may be important to differentiate
  321. // between failures due to Psiphon server conditions and failures due to the
  322. // origin/target server (in the latter case, the tunnel is healthy). Here are
  323. // some typical error messages to consider matching against (or ignoring):
  324. //
  325. // - "ssh: rejected: administratively prohibited (open failed)"
  326. // - "ssh: rejected: connect failed (Connection timed out)"
  327. // - "write tcp ... broken pipe"
  328. // - "read tcp ... connection reset by peer"
  329. // - "ssh: unexpected packet in response to channel open: <nil>"
  330. //
  331. func (controller *Controller) operateTunnel(tunnel *Tunnel) {
  332. defer controller.operateWaitGroup.Done()
  333. tunnelClosedSignal := make(chan struct{}, 1)
  334. err := tunnel.conn.SetClosedSignal(tunnelClosedSignal)
  335. if err != nil {
  336. err = fmt.Errorf("failed to set closed signal: %s", err)
  337. }
  338. Notice(NOTICE_INFO, "starting session for %s", tunnel.serverEntry.IpAddress)
  339. // TODO: NewSession server API calls may block shutdown
  340. _, err = NewSession(controller.config, tunnel)
  341. if err != nil {
  342. err = fmt.Errorf("error starting session for %s: %s", tunnel.serverEntry.IpAddress, err)
  343. }
  344. // Promote this successful tunnel to first rank so it's one
  345. // of the first candidates next time establish runs.
  346. PromoteServerEntry(tunnel.serverEntry.IpAddress)
  347. for err == nil {
  348. select {
  349. case failures := <-tunnel.portForwardFailures:
  350. tunnel.portForwardFailureTotal += failures
  351. if tunnel.portForwardFailureTotal > controller.config.PortForwardFailureThreshold {
  352. err = errors.New("tunnel exceeded port forward failure threshold")
  353. }
  354. case <-tunnelClosedSignal:
  355. // TODO: this signal can be received during a commanded shutdown due to
  356. // how tunnels are closed; should rework this to avoid log noise.
  357. err = errors.New("tunnel closed unexpectedly")
  358. case <-controller.shutdownBroadcast:
  359. Notice(NOTICE_INFO, "shutdown operate tunnel")
  360. return
  361. }
  362. }
  363. if err != nil {
  364. Notice(NOTICE_ALERT, "operate tunnel error for %s: %s", tunnel.serverEntry.IpAddress, err)
  365. // Don't block. Assumes the receiver has a buffer large enough for
  366. // the typical number of operated tunnels. In case there's no room,
  367. // terminate the tunnel (runTunnels won't get a signal in this case).
  368. select {
  369. case controller.failedTunnels <- tunnel:
  370. default:
  371. controller.terminateTunnel(tunnel)
  372. }
  373. }
  374. }
  375. // TunneledConn implements net.Conn and wraps a port foward connection.
  376. // It is used to hook into Read and Write to observe I/O errors and
  377. // report these errors back to the tunnel monitor as port forward failures.
  378. type TunneledConn struct {
  379. net.Conn
  380. tunnel *Tunnel
  381. }
  382. func (conn *TunneledConn) Read(buffer []byte) (n int, err error) {
  383. n, err = conn.Conn.Read(buffer)
  384. if err != nil {
  385. // Report 1 new failure. Won't block; assumes the receiver
  386. // has a sufficient buffer for the threshold number of reports.
  387. // TODO: conditional on type of error or error message?
  388. select {
  389. case conn.tunnel.portForwardFailures <- 1:
  390. default:
  391. }
  392. }
  393. return
  394. }
  395. func (conn *TunneledConn) Write(buffer []byte) (n int, err error) {
  396. n, err = conn.Conn.Write(buffer)
  397. if err != nil {
  398. // Same as TunneledConn.Read()
  399. select {
  400. case conn.tunnel.portForwardFailures <- 1:
  401. default:
  402. }
  403. }
  404. return
  405. }
  406. // DialWithTunnel selects an active tunnel and establishes a port forward
  407. // connection through the selected tunnel. Failure to connect is considered
  408. // a port foward failure, for the purpose of monitoring tunnel health.
  409. func (controller *Controller) Dial(remoteAddr string) (conn net.Conn, err error) {
  410. tunnel := controller.getNextActiveTunnel()
  411. if tunnel == nil {
  412. return nil, ContextError(errors.New("no active tunnels"))
  413. }
  414. tunnelConn, err := tunnel.Dial(remoteAddr)
  415. if err != nil {
  416. // TODO: conditional on type of error or error message?
  417. select {
  418. case tunnel.portForwardFailures <- 1:
  419. default:
  420. }
  421. return nil, ContextError(err)
  422. }
  423. return &TunneledConn{
  424. Conn: tunnelConn,
  425. tunnel: tunnel},
  426. nil
  427. }
  428. // startEstablishing creates a pool of worker goroutines which will
  429. // attempt to establish tunnels to candidate servers. The candidates
  430. // are generated by another goroutine.
  431. func (controller *Controller) startEstablishing() {
  432. if controller.isEstablishing {
  433. return
  434. }
  435. Notice(NOTICE_INFO, "start establishing")
  436. controller.isEstablishing = true
  437. controller.establishWaitGroup = new(sync.WaitGroup)
  438. controller.stopEstablishingBroadcast = make(chan struct{})
  439. controller.candidateServerEntries = make(chan *ServerEntry)
  440. for i := 0; i < controller.config.ConnectionWorkerPoolSize; i++ {
  441. controller.establishWaitGroup.Add(1)
  442. go controller.establishTunnelWorker()
  443. }
  444. controller.establishWaitGroup.Add(1)
  445. go controller.establishCandidateGenerator()
  446. }
  447. // stopEstablishing signals the establish goroutines to stop and waits
  448. // for the group to halt. pendingConns is used to interrupt any worker
  449. // blocked on a socket connect.
  450. func (controller *Controller) stopEstablishing() {
  451. if !controller.isEstablishing {
  452. return
  453. }
  454. Notice(NOTICE_INFO, "stop establishing")
  455. // Note: on Windows, interruptibleTCPClose doesn't really interrupt socket connects
  456. // and may leave goroutines running for a time after the Wait call.
  457. controller.pendingConns.CloseAll()
  458. close(controller.stopEstablishingBroadcast)
  459. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  460. // (as it may be sending to that channel).
  461. controller.establishWaitGroup.Wait()
  462. controller.isEstablishing = false
  463. controller.establishWaitGroup = nil
  464. controller.stopEstablishingBroadcast = nil
  465. controller.candidateServerEntries = nil
  466. }
  467. // establishCandidateGenerator populates the candidate queue with server entries
  468. // from the data store. Server entries are iterated in rank order, so that promoted
  469. // servers with higher rank are priority candidates.
  470. func (controller *Controller) establishCandidateGenerator() {
  471. defer controller.establishWaitGroup.Done()
  472. loop:
  473. for {
  474. // Note: it's possible that an active tunnel in excludeServerEntries will
  475. // fail during this iteration of server entries and in that case the
  476. // cooresponding server will not be retried (within the same iteration).
  477. // !TODO! is there also a race that can result in multiple tunnels to the same server
  478. excludeServerEntries := controller.getActiveTunnelServerEntries()
  479. iterator, err := NewServerEntryIterator(
  480. controller.config.EgressRegion, controller.config.TunnelProtocol, excludeServerEntries)
  481. if err != nil {
  482. Notice(NOTICE_ALERT, "failed to iterate over candidates: %s", err)
  483. controller.SignalFailure()
  484. break loop
  485. }
  486. for {
  487. serverEntry, err := iterator.Next()
  488. if err != nil {
  489. Notice(NOTICE_ALERT, "failed to get next candidate: %s", err)
  490. controller.SignalFailure()
  491. break loop
  492. }
  493. if serverEntry == nil {
  494. // Completed this iteration
  495. break
  496. }
  497. select {
  498. case controller.candidateServerEntries <- serverEntry:
  499. case <-controller.stopEstablishingBroadcast:
  500. break loop
  501. case <-controller.shutdownBroadcast:
  502. break loop
  503. }
  504. }
  505. iterator.Close()
  506. // After a complete iteration of candidate servers, pause before iterating again.
  507. // This helps avoid some busy wait loop conditions, and also allows some time for
  508. // network conditions to change.
  509. timeout := time.After(ESTABLISH_TUNNEL_PAUSE_PERIOD)
  510. select {
  511. case <-timeout:
  512. // Retry iterating
  513. case <-controller.stopEstablishingBroadcast:
  514. break loop
  515. case <-controller.shutdownBroadcast:
  516. break loop
  517. }
  518. }
  519. close(controller.candidateServerEntries)
  520. Notice(NOTICE_INFO, "stopped candidate generator")
  521. }
  522. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  523. // a connection to the tunnel server, and delivers the established tunnel to a channel.
  524. func (controller *Controller) establishTunnelWorker() {
  525. defer controller.establishWaitGroup.Done()
  526. for serverEntry := range controller.candidateServerEntries {
  527. // Note: don't receive from candidateQueue and broadcastStopWorkers in the same
  528. // select, since we want to prioritize receiving the stop signal
  529. select {
  530. case <-controller.stopEstablishingBroadcast:
  531. return
  532. default:
  533. }
  534. tunnel, err := EstablishTunnel(
  535. controller.config, controller.pendingConns, serverEntry)
  536. if err != nil {
  537. // TODO: distingush case where conn is interrupted?
  538. Notice(NOTICE_INFO, "failed to connect to %s: %s", serverEntry.IpAddress, err)
  539. } else {
  540. // Don't block. Assumes the receiver has a buffer large enough for
  541. // the number of desired tunnels. If there's no room, the tunnel must
  542. // not be required so it's discarded.
  543. select {
  544. case controller.establishedTunnels <- tunnel:
  545. default:
  546. controller.discardTunnel(tunnel)
  547. }
  548. }
  549. }
  550. Notice(NOTICE_INFO, "stopped establish worker")
  551. }
  552. // RunForever executes the main loop of the Psiphon client. It launches
  553. // the controller with a shutdown that it never signaled.
  554. func RunForever(config *Config) {
  555. if config.LogFilename != "" {
  556. logFile, err := os.OpenFile(config.LogFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  557. if err != nil {
  558. Fatal("error opening log file: %s", err)
  559. }
  560. defer logFile.Close()
  561. log.SetOutput(logFile)
  562. }
  563. Notice(NOTICE_VERSION, VERSION)
  564. controller := NewController(config)
  565. shutdownBroadcast := make(chan struct{})
  566. controller.Run(shutdownBroadcast)
  567. }