clientlib.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /*
  2. * Copyright (c) 2018, 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 clientlib
  20. import (
  21. "context"
  22. "encoding/json"
  23. std_errors "errors"
  24. "fmt"
  25. "net"
  26. "path/filepath"
  27. "sync"
  28. "sync/atomic"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  31. )
  32. // Parameters provide an easier way to modify the tunnel config at runtime.
  33. type Parameters struct {
  34. // Used as the directory for the datastore, remote server list, and obfuscasted
  35. // server list.
  36. // Empty string means the default will be used (current working directory).
  37. // nil means the values in the config file will be used.
  38. // Optional, but strongly recommended.
  39. DataRootDirectory *string
  40. // Overrides config.ClientPlatform. See config.go for details.
  41. // nil means the value in the config file will be used.
  42. // Optional, but strongly recommended.
  43. ClientPlatform *string
  44. // Overrides config.NetworkID. For details see:
  45. // https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter
  46. // nil means the value in the config file will be used. (If not set in the config,
  47. // an error will result.)
  48. // Empty string will produce an error.
  49. // Optional, but strongly recommended.
  50. NetworkID *string
  51. // Overrides config.EstablishTunnelTimeoutSeconds. See config.go for details.
  52. // nil means the EstablishTunnelTimeoutSeconds value in the config file will be used.
  53. // If there's no such value in the config file, the default will be used.
  54. // Zero means there will be no timeout.
  55. // Optional.
  56. EstablishTunnelTimeoutSeconds *int
  57. // EmitDiagnosticNoticesToFile indicates whether to use the rotating log file
  58. // facility to record diagnostic notices instead of sending diagnostic
  59. // notices to noticeReceiver. Has no effect unless the tunnel
  60. // config.EmitDiagnosticNotices flag is set.
  61. EmitDiagnosticNoticesToFiles bool
  62. // DisableLocalSocksProxy disables running the local SOCKS proxy.
  63. DisableLocalSocksProxy *bool
  64. // DisableLocalHTTPProxy disables running the local HTTP proxy.
  65. DisableLocalHTTPProxy *bool
  66. }
  67. // PsiphonTunnel is the tunnel object. It can be used for stopping the tunnel and
  68. // retrieving proxy ports.
  69. type PsiphonTunnel struct {
  70. mu sync.Mutex
  71. cancelTunnelCtx context.CancelCauseFunc
  72. embeddedServerListWaitGroup sync.WaitGroup
  73. controllerWaitGroup sync.WaitGroup
  74. controllerDial func(string, net.Conn) (net.Conn, error)
  75. // The port on which the HTTP proxy is running
  76. HTTPProxyPort int
  77. // The port on which the SOCKS proxy is running
  78. SOCKSProxyPort int
  79. }
  80. // ParametersDelta allows for fine-grained modification of parameters.Parameters.
  81. // NOTE: Ordinary users of this library should never need this.
  82. type ParametersDelta map[string]interface{}
  83. // NoticeEvent represents the notices emitted by tunnel core. It will be passed to
  84. // noticeReceiver, if supplied.
  85. // NOTE: Ordinary users of this library should never need this.
  86. type NoticeEvent struct {
  87. Data map[string]interface{} `json:"data"`
  88. Type string `json:"noticeType"`
  89. Timestamp string `json:"timestamp"`
  90. }
  91. // ErrTimeout is returned when the tunnel establishment attempt fails due to timeout
  92. var ErrTimeout = std_errors.New("clientlib: tunnel establishment timeout")
  93. var errMultipleStart = std_errors.New("clientlib: StartTunnel called multiple times")
  94. // started is used to ensure StartTunnel is called only once
  95. var started atomic.Bool
  96. // StartTunnel establishes a Psiphon tunnel. It returns an error if the establishment
  97. // was not successful. If the returned error is nil, the returned tunnel can be used
  98. // to find out the proxy ports and subsequently stop the tunnel.
  99. //
  100. // ctx may be cancelable, if the caller wants to be able to interrupt the establishment
  101. // attempt, or context.Background().
  102. //
  103. // configJSON will be passed to psiphon.LoadConfig to configure the tunnel. Required.
  104. //
  105. // embeddedServerEntryList is the encoded embedded server entry list. It is optional.
  106. //
  107. // params are config values that typically need to be overridden at runtime.
  108. //
  109. // paramsDelta contains changes that will be applied to the Parameters.
  110. // NOTE: Ordinary users of this library should never need this and should pass nil.
  111. //
  112. // noticeReceiver, if non-nil, will be called for each notice emitted by tunnel core.
  113. // NOTE: Ordinary users of this library should never need this and should pass nil.
  114. func StartTunnel(
  115. ctx context.Context,
  116. configJSON []byte,
  117. embeddedServerEntryList string,
  118. params Parameters,
  119. paramsDelta ParametersDelta,
  120. noticeReceiver func(NoticeEvent)) (retTunnel *PsiphonTunnel, retErr error) {
  121. if !started.CompareAndSwap(false, true) {
  122. return nil, errMultipleStart
  123. }
  124. config, err := psiphon.LoadConfig(configJSON)
  125. if err != nil {
  126. return nil, fmt.Errorf("failed to load config file: %w", err)
  127. }
  128. // Use params.DataRootDirectory to set related config values.
  129. if params.DataRootDirectory != nil {
  130. config.DataRootDirectory = *params.DataRootDirectory
  131. // Migrate old fields
  132. config.MigrateDataStoreDirectory = *params.DataRootDirectory
  133. config.MigrateObfuscatedServerListDownloadDirectory = *params.DataRootDirectory
  134. config.MigrateRemoteServerListDownloadFilename = filepath.Join(*params.DataRootDirectory, "server_list_compressed")
  135. }
  136. if params.NetworkID != nil {
  137. config.NetworkID = *params.NetworkID
  138. }
  139. if params.ClientPlatform != nil {
  140. config.ClientPlatform = *params.ClientPlatform
  141. } // else use the value in config
  142. if params.EstablishTunnelTimeoutSeconds != nil {
  143. config.EstablishTunnelTimeoutSeconds = params.EstablishTunnelTimeoutSeconds
  144. } // else use the value in config
  145. if config.UseNoticeFiles == nil && config.EmitDiagnosticNotices && params.EmitDiagnosticNoticesToFiles {
  146. config.UseNoticeFiles = &psiphon.UseNoticeFiles{
  147. RotatingFileSize: 0,
  148. RotatingSyncFrequency: 0,
  149. }
  150. } // else use the value in the config
  151. if params.DisableLocalSocksProxy != nil {
  152. config.DisableLocalSocksProxy = *params.DisableLocalSocksProxy
  153. } // else use the value in the config
  154. if params.DisableLocalHTTPProxy != nil {
  155. config.DisableLocalHTTPProxy = *params.DisableLocalHTTPProxy
  156. } // else use the value in the config
  157. // config.Commit must be called before calling config.SetParameters
  158. // or attempting to connect.
  159. err = config.Commit(true)
  160. if err != nil {
  161. return nil, fmt.Errorf("config.Commit failed: %w", err)
  162. }
  163. // If supplied, apply the parameters delta
  164. if len(paramsDelta) > 0 {
  165. err = config.SetParameters("", false, paramsDelta)
  166. if err != nil {
  167. return nil, fmt.Errorf("SetParameters failed for delta: %v; %w", paramsDelta, err)
  168. }
  169. }
  170. // Will be closed when the tunnel has successfully connected
  171. connectedCh := make(chan struct{})
  172. // Will receive a value if an error occurs during the connection sequence
  173. erroredCh := make(chan error, 1)
  174. // Create the tunnel object
  175. tunnel := new(PsiphonTunnel)
  176. // Set up notice handling
  177. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  178. func(notice []byte) {
  179. var event NoticeEvent
  180. err := json.Unmarshal(notice, &event)
  181. if err != nil {
  182. // This is unexpected and probably indicates something fatal has occurred.
  183. // We'll interpret it as a connection error and abort.
  184. err = fmt.Errorf("failed to unmarshal notice JSON: %w", err)
  185. select {
  186. case erroredCh <- err:
  187. default:
  188. }
  189. return
  190. }
  191. if event.Type == "ListeningHttpProxyPort" {
  192. port := event.Data["port"].(float64)
  193. tunnel.HTTPProxyPort = int(port)
  194. } else if event.Type == "ListeningSocksProxyPort" {
  195. port := event.Data["port"].(float64)
  196. tunnel.SOCKSProxyPort = int(port)
  197. } else if event.Type == "EstablishTunnelTimeout" {
  198. select {
  199. case erroredCh <- ErrTimeout:
  200. default:
  201. }
  202. } else if event.Type == "Tunnels" {
  203. count := event.Data["count"].(float64)
  204. if count > 0 {
  205. close(connectedCh)
  206. }
  207. }
  208. // Some users of this package may need to add special processing of notices.
  209. // If the caller has requested it, we'll pass on the notices.
  210. if noticeReceiver != nil {
  211. noticeReceiver(event)
  212. }
  213. }))
  214. err = psiphon.OpenDataStore(config)
  215. if err != nil {
  216. return nil, fmt.Errorf("failed to open data store: %w", err)
  217. }
  218. // Make sure we close the datastore in case of error
  219. defer func() {
  220. if retErr != nil {
  221. tunnel.controllerWaitGroup.Wait()
  222. tunnel.embeddedServerListWaitGroup.Wait()
  223. psiphon.CloseDataStore()
  224. started.Store(false)
  225. }
  226. }()
  227. // Create a cancelable context that will be used for stopping the tunnel
  228. var tunnelCtx context.Context
  229. tunnelCtx, tunnel.cancelTunnelCtx = context.WithCancelCause(ctx)
  230. // If specified, the embedded server list is loaded and stored. When there
  231. // are no server candidates at all, we wait for this import to complete
  232. // before starting the Psiphon controller. Otherwise, we import while
  233. // concurrently starting the controller to minimize delay before attempting
  234. // to connect to existing candidate servers.
  235. //
  236. // If the import fails, an error notice is emitted, but the controller is
  237. // still started: either existing candidate servers may suffice, or the
  238. // remote server list fetch may obtain candidate servers.
  239. //
  240. // The import will be interrupted if it's still running when the controller
  241. // is stopped.
  242. tunnel.embeddedServerListWaitGroup.Add(1)
  243. go func() {
  244. defer tunnel.embeddedServerListWaitGroup.Done()
  245. err := psiphon.ImportEmbeddedServerEntries(
  246. tunnelCtx,
  247. config,
  248. "",
  249. embeddedServerEntryList)
  250. if err != nil {
  251. psiphon.NoticeError("error importing embedded server entry list: %s", err)
  252. return
  253. }
  254. }()
  255. if !psiphon.HasServerEntries() {
  256. psiphon.NoticeInfo("awaiting embedded server entry list import")
  257. tunnel.embeddedServerListWaitGroup.Wait()
  258. }
  259. // Create the Psiphon controller
  260. controller, err := psiphon.NewController(config)
  261. if err != nil {
  262. tunnel.cancelTunnelCtx(fmt.Errorf("psiphon.NewController failed: %w", err))
  263. return nil, fmt.Errorf("psiphon.NewController failed: %w", err)
  264. }
  265. tunnel.controllerDial = controller.Dial
  266. // Begin tunnel connection
  267. tunnel.controllerWaitGroup.Add(1)
  268. go func() {
  269. defer tunnel.controllerWaitGroup.Done()
  270. // Start the tunnel. Only returns on error (or internal timeout).
  271. controller.Run(tunnelCtx)
  272. // controller.Run does not exit until the goroutine that posts
  273. // EstablishTunnelTimeout has terminated; so, if there was a
  274. // EstablishTunnelTimeout event, ErrTimeout is guaranteed to be sent to
  275. // errored before this next error and will be the StartTunnel return value.
  276. var err error
  277. switch ctx.Err() {
  278. case context.DeadlineExceeded:
  279. err = ErrTimeout
  280. case context.Canceled:
  281. err = errors.TraceNew("StartTunnel canceled")
  282. default:
  283. err = errors.TraceNew("controller.Run exited unexpectedly")
  284. }
  285. select {
  286. case erroredCh <- err:
  287. default:
  288. }
  289. }()
  290. // Wait for an active tunnel or error
  291. select {
  292. case <-connectedCh:
  293. return tunnel, nil
  294. case err := <-erroredCh:
  295. tunnel.cancelTunnelCtx(fmt.Errorf("tunnel establishment failed: %w", err))
  296. if err != ErrTimeout {
  297. err = fmt.Errorf("tunnel start produced error: %w", err)
  298. }
  299. return nil, err
  300. }
  301. }
  302. // Stop stops/disconnects/shuts down the tunnel.
  303. // It is safe to call Stop multiple times.
  304. // It is safe to call concurrently with Dial and with itself.
  305. func (tunnel *PsiphonTunnel) Stop() {
  306. tunnel.mu.Lock()
  307. cancelTunnelCtx := tunnel.cancelTunnelCtx
  308. tunnel.cancelTunnelCtx = nil
  309. tunnel.controllerDial = nil
  310. tunnel.mu.Unlock()
  311. if cancelTunnelCtx == nil {
  312. return
  313. }
  314. cancelTunnelCtx(fmt.Errorf("Stop called"))
  315. tunnel.embeddedServerListWaitGroup.Wait()
  316. tunnel.controllerWaitGroup.Wait()
  317. psiphon.CloseDataStore()
  318. // Reset the started flag so that StartTunnel can be called again
  319. started.Store(false)
  320. }
  321. // Dial connects to the specified address through the Psiphon tunnel.
  322. // It is safe to call Dial after the tunnel has been stopped.
  323. // It is safe to call Dial concurrently with Stop.
  324. func (tunnel *PsiphonTunnel) Dial(remoteAddr string) (conn net.Conn, err error) {
  325. // Ensure the dial is accessed in a thread-safe manner, without holding the lock
  326. // while calling the dial function.
  327. // Note that it is safe for controller.Dial to be called even after or during a tunnel
  328. // shutdown (i.e., if the context has been canceled).
  329. tunnel.mu.Lock()
  330. dial := tunnel.controllerDial
  331. tunnel.mu.Unlock()
  332. if dial == nil {
  333. return nil, errors.TraceNew("tunnel not started")
  334. }
  335. return dial(remoteAddr, nil)
  336. }