controller.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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. Notice(
  353. NOTICE_INFO, "port forward failures for %s: %d",
  354. tunnel.serverEntry.IpAddress, tunnel.portForwardFailureTotal)
  355. if tunnel.portForwardFailureTotal > controller.config.PortForwardFailureThreshold {
  356. err = errors.New("tunnel exceeded port forward failure threshold")
  357. }
  358. case <-tunnelClosedSignal:
  359. // TODO: this signal can be received during a commanded shutdown due to
  360. // how tunnels are closed; should rework this to avoid log noise.
  361. err = errors.New("tunnel closed unexpectedly")
  362. case <-controller.shutdownBroadcast:
  363. Notice(NOTICE_INFO, "shutdown operate tunnel")
  364. return
  365. }
  366. }
  367. if err != nil {
  368. Notice(NOTICE_ALERT, "operate tunnel error for %s: %s", tunnel.serverEntry.IpAddress, err)
  369. // Don't block. Assumes the receiver has a buffer large enough for
  370. // the typical number of operated tunnels. In case there's no room,
  371. // terminate the tunnel (runTunnels won't get a signal in this case).
  372. select {
  373. case controller.failedTunnels <- tunnel:
  374. default:
  375. controller.terminateTunnel(tunnel)
  376. }
  377. }
  378. }
  379. // TunneledConn implements net.Conn and wraps a port foward connection.
  380. // It is used to hook into Read and Write to observe I/O errors and
  381. // report these errors back to the tunnel monitor as port forward failures.
  382. type TunneledConn struct {
  383. net.Conn
  384. tunnel *Tunnel
  385. }
  386. func (conn *TunneledConn) Read(buffer []byte) (n int, err error) {
  387. n, err = conn.Conn.Read(buffer)
  388. if err != nil && err != io.EOF {
  389. // Report 1 new failure. Won't block; assumes the receiver
  390. // has a sufficient buffer for the threshold number of reports.
  391. // TODO: conditional on type of error or error message?
  392. select {
  393. case conn.tunnel.portForwardFailures <- 1:
  394. default:
  395. }
  396. }
  397. return
  398. }
  399. func (conn *TunneledConn) Write(buffer []byte) (n int, err error) {
  400. n, err = conn.Conn.Write(buffer)
  401. if err != nil && err != io.EOF {
  402. // Same as TunneledConn.Read()
  403. select {
  404. case conn.tunnel.portForwardFailures <- 1:
  405. default:
  406. }
  407. }
  408. return
  409. }
  410. // Dial selects an active tunnel and establishes a port forward
  411. // connection through the selected tunnel. Failure to connect is considered
  412. // a port foward failure, for the purpose of monitoring tunnel health.
  413. func (controller *Controller) Dial(remoteAddr string) (conn net.Conn, err error) {
  414. tunnel := controller.getNextActiveTunnel()
  415. if tunnel == nil {
  416. return nil, ContextError(errors.New("no active tunnels"))
  417. }
  418. tunnelConn, err := tunnel.Dial(remoteAddr)
  419. if err != nil {
  420. // TODO: conditional on type of error or error message?
  421. select {
  422. case tunnel.portForwardFailures <- 1:
  423. default:
  424. }
  425. return nil, ContextError(err)
  426. }
  427. return &TunneledConn{
  428. Conn: tunnelConn,
  429. tunnel: tunnel},
  430. nil
  431. }
  432. // startEstablishing creates a pool of worker goroutines which will
  433. // attempt to establish tunnels to candidate servers. The candidates
  434. // are generated by another goroutine.
  435. func (controller *Controller) startEstablishing() {
  436. if controller.isEstablishing {
  437. return
  438. }
  439. Notice(NOTICE_INFO, "start establishing")
  440. controller.isEstablishing = true
  441. controller.establishWaitGroup = new(sync.WaitGroup)
  442. controller.stopEstablishingBroadcast = make(chan struct{})
  443. controller.candidateServerEntries = make(chan *ServerEntry)
  444. for i := 0; i < controller.config.ConnectionWorkerPoolSize; i++ {
  445. controller.establishWaitGroup.Add(1)
  446. go controller.establishTunnelWorker()
  447. }
  448. controller.establishWaitGroup.Add(1)
  449. go controller.establishCandidateGenerator()
  450. }
  451. // stopEstablishing signals the establish goroutines to stop and waits
  452. // for the group to halt. pendingConns is used to interrupt any worker
  453. // blocked on a socket connect.
  454. func (controller *Controller) stopEstablishing() {
  455. if !controller.isEstablishing {
  456. return
  457. }
  458. Notice(NOTICE_INFO, "stop establishing")
  459. // Note: on Windows, interruptibleTCPClose doesn't really interrupt socket connects
  460. // and may leave goroutines running for a time after the Wait call.
  461. controller.pendingConns.CloseAll()
  462. close(controller.stopEstablishingBroadcast)
  463. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  464. // (as it may be sending to that channel).
  465. controller.establishWaitGroup.Wait()
  466. controller.isEstablishing = false
  467. controller.establishWaitGroup = nil
  468. controller.stopEstablishingBroadcast = nil
  469. controller.candidateServerEntries = nil
  470. }
  471. // establishCandidateGenerator populates the candidate queue with server entries
  472. // from the data store. Server entries are iterated in rank order, so that promoted
  473. // servers with higher rank are priority candidates.
  474. func (controller *Controller) establishCandidateGenerator() {
  475. defer controller.establishWaitGroup.Done()
  476. loop:
  477. for {
  478. // Note: it's possible that an active tunnel in excludeServerEntries will
  479. // fail during this iteration of server entries and in that case the
  480. // cooresponding server will not be retried (within the same iteration).
  481. // !TODO! is there also a race that can result in multiple tunnels to the same server
  482. excludeServerEntries := controller.getActiveTunnelServerEntries()
  483. iterator, err := NewServerEntryIterator(
  484. controller.config.EgressRegion, controller.config.TunnelProtocol, excludeServerEntries)
  485. if err != nil {
  486. Notice(NOTICE_ALERT, "failed to iterate over candidates: %s", err)
  487. controller.SignalFailure()
  488. break loop
  489. }
  490. for {
  491. serverEntry, err := iterator.Next()
  492. if err != nil {
  493. Notice(NOTICE_ALERT, "failed to get next candidate: %s", err)
  494. controller.SignalFailure()
  495. break loop
  496. }
  497. if serverEntry == nil {
  498. // Completed this iteration
  499. break
  500. }
  501. select {
  502. case controller.candidateServerEntries <- serverEntry:
  503. case <-controller.stopEstablishingBroadcast:
  504. break loop
  505. case <-controller.shutdownBroadcast:
  506. break loop
  507. }
  508. }
  509. iterator.Close()
  510. // After a complete iteration of candidate servers, pause before iterating again.
  511. // This helps avoid some busy wait loop conditions, and also allows some time for
  512. // network conditions to change.
  513. timeout := time.After(ESTABLISH_TUNNEL_PAUSE_PERIOD)
  514. select {
  515. case <-timeout:
  516. // Retry iterating
  517. case <-controller.stopEstablishingBroadcast:
  518. break loop
  519. case <-controller.shutdownBroadcast:
  520. break loop
  521. }
  522. }
  523. close(controller.candidateServerEntries)
  524. Notice(NOTICE_INFO, "stopped candidate generator")
  525. }
  526. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  527. // a connection to the tunnel server, and delivers the established tunnel to a channel.
  528. func (controller *Controller) establishTunnelWorker() {
  529. defer controller.establishWaitGroup.Done()
  530. for serverEntry := range controller.candidateServerEntries {
  531. // Note: don't receive from candidateQueue and broadcastStopWorkers in the same
  532. // select, since we want to prioritize receiving the stop signal
  533. select {
  534. case <-controller.stopEstablishingBroadcast:
  535. return
  536. default:
  537. }
  538. tunnel, err := EstablishTunnel(
  539. controller.config, controller.pendingConns, serverEntry)
  540. if err != nil {
  541. // TODO: distingush case where conn is interrupted?
  542. Notice(NOTICE_INFO, "failed to connect to %s: %s", serverEntry.IpAddress, err)
  543. } else {
  544. // Don't block. Assumes the receiver has a buffer large enough for
  545. // the number of desired tunnels. If there's no room, the tunnel must
  546. // not be required so it's discarded.
  547. select {
  548. case controller.establishedTunnels <- tunnel:
  549. default:
  550. controller.discardTunnel(tunnel)
  551. }
  552. }
  553. }
  554. Notice(NOTICE_INFO, "stopped establish worker")
  555. }
  556. // RunForever executes the main loop of the Psiphon client. It launches
  557. // the controller with a shutdown that it never signaled.
  558. func RunForever(config *Config) {
  559. if config.LogFilename != "" {
  560. logFile, err := os.OpenFile(config.LogFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  561. if err != nil {
  562. Fatal("error opening log file: %s", err)
  563. }
  564. defer logFile.Close()
  565. log.SetOutput(logFile)
  566. }
  567. Notice(NOTICE_VERSION, VERSION)
  568. controller := NewController(config)
  569. shutdownBroadcast := make(chan struct{})
  570. controller.Run(shutdownBroadcast)
  571. }