controller.go 21 KB

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