clientlib.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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(ctx context.Context,
  104. configJSON []byte, embeddedServerEntryList string,
  105. params Parameters, paramsDelta ParametersDelta,
  106. noticeReceiver func(NoticeEvent)) (retTunnel *PsiphonTunnel, retErr error) {
  107. config, err := psiphon.LoadConfig(configJSON)
  108. if err != nil {
  109. return nil, errors.TraceMsg(err, "failed to load config file")
  110. }
  111. // Use params.DataRootDirectory to set related config values.
  112. if params.DataRootDirectory != nil {
  113. config.DataRootDirectory = *params.DataRootDirectory
  114. // Migrate old fields
  115. config.MigrateDataStoreDirectory = *params.DataRootDirectory
  116. config.MigrateObfuscatedServerListDownloadDirectory = *params.DataRootDirectory
  117. config.MigrateRemoteServerListDownloadFilename = filepath.Join(*params.DataRootDirectory, "server_list_compressed")
  118. }
  119. if params.NetworkID != nil {
  120. config.NetworkID = *params.NetworkID
  121. }
  122. if params.ClientPlatform != nil {
  123. config.ClientPlatform = *params.ClientPlatform
  124. } // else use the value in config
  125. if params.EstablishTunnelTimeoutSeconds != nil {
  126. config.EstablishTunnelTimeoutSeconds = params.EstablishTunnelTimeoutSeconds
  127. } // else use the value in config
  128. if config.UseNoticeFiles == nil && config.EmitDiagnosticNotices && params.EmitDiagnosticNoticesToFiles {
  129. config.UseNoticeFiles = &psiphon.UseNoticeFiles{
  130. RotatingFileSize: 0,
  131. RotatingSyncFrequency: 0,
  132. }
  133. } // else use the value in the config
  134. // config.Commit must be called before calling config.SetParameters
  135. // or attempting to connect.
  136. err = config.Commit(true)
  137. if err != nil {
  138. return nil, errors.TraceMsg(err, "config.Commit failed")
  139. }
  140. // If supplied, apply the parameters delta
  141. if len(paramsDelta) > 0 {
  142. err = config.SetParameters("", false, paramsDelta)
  143. if err != nil {
  144. return nil, errors.TraceMsg(
  145. err, fmt.Sprintf("SetParameters failed for delta: %v", paramsDelta))
  146. }
  147. }
  148. // Will receive a value when the tunnel has successfully connected.
  149. connected := make(chan struct{})
  150. // Will receive a value if the tunnel times out trying to connect.
  151. timedOut := make(chan struct{})
  152. // Will receive a value if an error occurs during the connection sequence.
  153. errored := make(chan error)
  154. // Create the tunnel object
  155. tunnel := new(PsiphonTunnel)
  156. // Set up notice handling
  157. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  158. func(notice []byte) {
  159. var event NoticeEvent
  160. err := json.Unmarshal(notice, &event)
  161. if err != nil {
  162. // This is unexpected and probably indicates something fatal has occurred.
  163. // We'll interpret it as a connection error and abort.
  164. err = errors.TraceMsg(err, "failed to unmarshal notice JSON")
  165. select {
  166. case errored <- err:
  167. default:
  168. }
  169. return
  170. }
  171. if event.Type == "ListeningHttpProxyPort" {
  172. port := event.Data["port"].(float64)
  173. tunnel.HTTPProxyPort = int(port)
  174. } else if event.Type == "ListeningSocksProxyPort" {
  175. port := event.Data["port"].(float64)
  176. tunnel.SOCKSProxyPort = int(port)
  177. } else if event.Type == "EstablishTunnelTimeout" {
  178. select {
  179. case timedOut <- struct{}{}:
  180. default:
  181. }
  182. } else if event.Type == "Tunnels" {
  183. count := event.Data["count"].(float64)
  184. if count > 0 {
  185. select {
  186. case connected <- struct{}{}:
  187. default:
  188. }
  189. }
  190. }
  191. // Some users of this package may need to add special processing of notices.
  192. // If the caller has requested it, we'll pass on the notices.
  193. if noticeReceiver != nil {
  194. noticeReceiver(event)
  195. }
  196. }))
  197. err = psiphon.OpenDataStore(config)
  198. if err != nil {
  199. return nil, errors.TraceMsg(err, "failed to open data store")
  200. }
  201. // Make sure we close the datastore in case of error
  202. defer func() {
  203. if retErr != nil {
  204. tunnel.controllerWaitGroup.Wait()
  205. tunnel.embeddedServerListWaitGroup.Wait()
  206. psiphon.CloseDataStore()
  207. }
  208. }()
  209. // Create a cancelable context that will be used for stopping the tunnel
  210. var controllerCtx context.Context
  211. controllerCtx, tunnel.stopController = context.WithCancel(ctx)
  212. // If specified, the embedded server list is loaded and stored. When there
  213. // are no server candidates at all, we wait for this import to complete
  214. // before starting the Psiphon controller. Otherwise, we import while
  215. // concurrently starting the controller to minimize delay before attempting
  216. // to connect to existing candidate servers.
  217. //
  218. // If the import fails, an error notice is emitted, but the controller is
  219. // still started: either existing candidate servers may suffice, or the
  220. // remote server list fetch may obtain candidate servers.
  221. //
  222. // The import will be interrupted if it's still running when the controller
  223. // is stopped.
  224. tunnel.embeddedServerListWaitGroup.Add(1)
  225. go func() {
  226. defer tunnel.embeddedServerListWaitGroup.Done()
  227. err := psiphon.ImportEmbeddedServerEntries(
  228. controllerCtx,
  229. config,
  230. "",
  231. embeddedServerEntryList)
  232. if err != nil {
  233. psiphon.NoticeError("error importing embedded server entry list: %s", err)
  234. return
  235. }
  236. }()
  237. if !psiphon.HasServerEntries() {
  238. psiphon.NoticeInfo("awaiting embedded server entry list import")
  239. tunnel.embeddedServerListWaitGroup.Wait()
  240. }
  241. // Create the Psiphon controller
  242. controller, err := psiphon.NewController(config)
  243. if err != nil {
  244. tunnel.stopController()
  245. tunnel.embeddedServerListWaitGroup.Wait()
  246. return nil, errors.TraceMsg(err, "psiphon.NewController failed")
  247. }
  248. // Begin tunnel connection
  249. tunnel.controllerWaitGroup.Add(1)
  250. go func() {
  251. defer tunnel.controllerWaitGroup.Done()
  252. // Start the tunnel. Only returns on error (or internal timeout).
  253. controller.Run(controllerCtx)
  254. select {
  255. case errored <- errors.TraceNew("controller.Run exited unexpectedly"):
  256. default:
  257. }
  258. }()
  259. // Wait for an active tunnel, timeout, or error
  260. select {
  261. case <-connected:
  262. return tunnel, nil
  263. case <-timedOut:
  264. tunnel.Stop()
  265. return nil, ErrTimeout
  266. case err := <-errored:
  267. tunnel.Stop()
  268. return nil, errors.TraceMsg(err, "tunnel start produced error")
  269. }
  270. }
  271. // Stop stops/disconnects/shuts down the tunnel. It is safe to call when not connected.
  272. // Not safe to call concurrently with Start.
  273. func (tunnel *PsiphonTunnel) Stop() {
  274. if tunnel.stopController == nil {
  275. return
  276. }
  277. tunnel.stopController()
  278. tunnel.controllerWaitGroup.Wait()
  279. tunnel.embeddedServerListWaitGroup.Wait()
  280. psiphon.CloseDataStore()
  281. }