controller.go 22 KB

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