controller.go 21 KB

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