clientlib.go 11 KB

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