clientlib.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. "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"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  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. }
  57. // PsiphonTunnel is the tunnel object. It can be used for stopping the tunnel and
  58. // retrieving proxy ports.
  59. type PsiphonTunnel struct {
  60. controllerWaitGroup sync.WaitGroup
  61. stopController context.CancelFunc
  62. // The port on which the HTTP proxy is running
  63. HTTPProxyPort int
  64. // The port on which the SOCKS proxy is running
  65. SOCKSProxyPort int
  66. }
  67. // ClientParametersDelta allows for fine-grained modification of parameters.ClientParameters.
  68. // NOTE: Ordinary users of this library should never need this.
  69. type ClientParametersDelta map[string]interface{}
  70. // NoticeEvent represents the notices emitted by tunnel core. It will be passed to
  71. // noticeReceiver, if supplied.
  72. // NOTE: Ordinary users of this library should never need this.
  73. type NoticeEvent struct {
  74. Data map[string]interface{} `json:"data"`
  75. Type string `json:"noticeType"`
  76. Timestamp string `json:"timestamp"`
  77. }
  78. // ErrTimeout is returned when the tunnel connection attempt fails due to timeout
  79. var ErrTimeout = errors.New("clientlib: tunnel connection timeout")
  80. // StartTunnel makes a Psiphon tunnel connection. It returns an error if the connection
  81. // was not successful. If the returned error is nil, the returned tunnel can be used
  82. // to find out the proxy ports and subsequently stop the tunnel.
  83. //
  84. // ctx may be cancelable, if the caller wants to be able to interrupt the connection
  85. // attempt, or context.Background().
  86. //
  87. // configJSON will be passed to psiphon.LoadConfig to configure the tunnel. Required.
  88. //
  89. // embeddedServerEntryList is the encoded embedded server entry list. It is optional.
  90. //
  91. // params are config values that typically need to be overridden at runtime.
  92. //
  93. // paramsDelta contains changes that will be applied to the ClientParameters.
  94. // NOTE: Ordinary users of this library should never need this and should pass nil.
  95. //
  96. // noticeReceiver, if non-nil, will be called for each notice emitted by tunnel core.
  97. // NOTE: Ordinary users of this library should never need this and should pass nil.
  98. func StartTunnel(ctx context.Context,
  99. configJSON []byte, embeddedServerEntryList string,
  100. params Parameters, paramsDelta ClientParametersDelta,
  101. noticeReceiver func(NoticeEvent)) (tunnel *PsiphonTunnel, err error) {
  102. config, err := psiphon.LoadConfig(configJSON)
  103. if err != nil {
  104. return nil, common.ContextErrorMsg(err, "failed to load config file")
  105. }
  106. // Use params.DataRootDirectory to set related config values.
  107. if params.DataRootDirectory != nil {
  108. config.DataStoreDirectory = *params.DataRootDirectory
  109. config.ObfuscatedServerListDownloadDirectory = *params.DataRootDirectory
  110. config.RemoteServerListDownloadFilename = filepath.Join(*params.DataRootDirectory, "server_list_compressed")
  111. }
  112. if params.NetworkID != nil {
  113. config.NetworkID = *params.NetworkID
  114. }
  115. if params.ClientPlatform != nil {
  116. config.ClientPlatform = *params.ClientPlatform
  117. } // else use the value in config
  118. if params.EstablishTunnelTimeoutSeconds != nil {
  119. config.EstablishTunnelTimeoutSeconds = params.EstablishTunnelTimeoutSeconds
  120. } // else use the value in config
  121. // config.Commit must be called before calling config.SetClientParameters
  122. // or attempting to connect.
  123. err = config.Commit()
  124. if err != nil {
  125. return nil, common.ContextErrorMsg(err, "config.Commit failed")
  126. }
  127. // If supplied, apply the client parameters delta
  128. if len(paramsDelta) > 0 {
  129. err = config.SetClientParameters("", false, paramsDelta)
  130. if err != nil {
  131. return nil, common.ContextErrorMsg(
  132. err, fmt.Sprintf("SetClientParameters failed for delta: %v", paramsDelta))
  133. }
  134. }
  135. // As Client Library doesn't currently implement callbacks, diagnostic
  136. // notices aren't relayed to the client application. So, when
  137. // EmitDiagnosticNotices is set, initialize the rotating diagnostic log file
  138. // facility.
  139. if config.EmitDiagnosticNotices {
  140. err := psiphon.SetNoticeFiles("", filepath.Join(config.DataStoreDirectory, "diagnostics.log"), 0, 0)
  141. if err != nil {
  142. return nil, common.ContextErrorMsg(err, "failed to initialize diagnostic logging")
  143. }
  144. }
  145. err = psiphon.OpenDataStore(config)
  146. if err != nil {
  147. return nil, common.ContextErrorMsg(err, "failed to open data store")
  148. }
  149. // Make sure we close the datastore in case of error
  150. defer func() {
  151. if err != nil {
  152. psiphon.CloseDataStore()
  153. }
  154. }()
  155. // Store embedded server entries
  156. serverEntries, err := protocol.DecodeServerEntryList(
  157. embeddedServerEntryList,
  158. common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  159. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  160. if err != nil {
  161. return nil, common.ContextErrorMsg(err, "failed to decode server entry list")
  162. }
  163. err = psiphon.StoreServerEntries(config, serverEntries, false)
  164. if err != nil {
  165. return nil, common.ContextErrorMsg(err, "failed to store server entries")
  166. }
  167. // Will receive a value when the tunnel has successfully connected.
  168. connected := make(chan struct{})
  169. // Will receive a value if the tunnel times out trying to connect.
  170. timedOut := make(chan struct{})
  171. // Will receive a value if an error occurs during the connection sequence.
  172. errored := make(chan error)
  173. // Create the tunnel object
  174. tunnel = new(PsiphonTunnel)
  175. // Set up notice handling
  176. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  177. func(notice []byte) {
  178. var event NoticeEvent
  179. err := json.Unmarshal(notice, &event)
  180. if err != nil {
  181. // This is unexpected and probably indicates something fatal has occurred.
  182. // We'll interpret it as a connection error and abort.
  183. err = common.ContextErrorMsg(err, "failed to unmarshal notice JSON")
  184. select {
  185. case errored <- err:
  186. default:
  187. }
  188. return
  189. }
  190. if event.Type == "ListeningHttpProxyPort" {
  191. port := event.Data["port"].(float64)
  192. tunnel.HTTPProxyPort = int(port)
  193. } else if event.Type == "ListeningSocksProxyPort" {
  194. port := event.Data["port"].(float64)
  195. tunnel.SOCKSProxyPort = int(port)
  196. } else if event.Type == "EstablishTunnelTimeout" {
  197. select {
  198. case timedOut <- struct{}{}:
  199. default:
  200. }
  201. } else if event.Type == "Tunnels" {
  202. count := event.Data["count"].(float64)
  203. if count > 0 {
  204. select {
  205. case connected <- struct{}{}:
  206. default:
  207. }
  208. }
  209. }
  210. // Some users of this package may need to add special processing of notices.
  211. // If the caller has requested it, we'll pass on the notices.
  212. if noticeReceiver != nil {
  213. noticeReceiver(event)
  214. }
  215. }))
  216. // Create the Psiphon controller
  217. controller, err := psiphon.NewController(config)
  218. if err != nil {
  219. return nil, common.ContextErrorMsg(err, "psiphon.NewController failed")
  220. }
  221. // Create a cancelable context that will be used for stopping the tunnel
  222. var controllerCtx context.Context
  223. controllerCtx, tunnel.stopController = context.WithCancel(ctx)
  224. // Begin tunnel connection
  225. tunnel.controllerWaitGroup.Add(1)
  226. go func() {
  227. defer tunnel.controllerWaitGroup.Done()
  228. // Start the tunnel. Only returns on error (or internal timeout).
  229. controller.Run(controllerCtx)
  230. select {
  231. case errored <- errors.New("controller.Run exited unexpectedly"):
  232. default:
  233. }
  234. }()
  235. // Wait for an active tunnel, timeout, or error
  236. select {
  237. case <-connected:
  238. return tunnel, nil
  239. case <-timedOut:
  240. tunnel.Stop()
  241. return nil, ErrTimeout
  242. case err := <-errored:
  243. tunnel.Stop()
  244. return nil, common.ContextErrorMsg(err, "tunnel start produced error")
  245. }
  246. }
  247. // Stop stops/disconnects/shuts down the tunnel. It is safe to call when not connected.
  248. func (tunnel *PsiphonTunnel) Stop() {
  249. if tunnel.stopController != nil {
  250. tunnel.stopController()
  251. }
  252. tunnel.controllerWaitGroup.Wait()
  253. psiphon.CloseDataStore()
  254. }