clientlib.go 12 KB

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