clientlib.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. // 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. }
  62. // PsiphonTunnel is the tunnel object. It can be used for stopping the tunnel and
  63. // retrieving proxy ports.
  64. type PsiphonTunnel struct {
  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. // ClientParametersDelta allows for fine-grained modification of parameters.ClientParameters.
  73. // NOTE: Ordinary users of this library should never need this.
  74. type ClientParametersDelta 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 connection attempt fails due to timeout
  84. var ErrTimeout = errors.New("clientlib: tunnel connection timeout")
  85. // StartTunnel makes a Psiphon tunnel connection. It returns an error if the connection
  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 connection
  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 ClientParameters.
  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 ClientParametersDelta,
  106. noticeReceiver func(NoticeEvent)) (tunnel *PsiphonTunnel, err error) {
  107. config, err := psiphon.LoadConfig(configJSON)
  108. if err != nil {
  109. return nil, common.ContextErrorMsg(err, "failed to load config file")
  110. }
  111. // Use params.DataRootDirectory to set related config values.
  112. if params.DataRootDirectory != nil {
  113. config.DataStoreDirectory = *params.DataRootDirectory
  114. config.ObfuscatedServerListDownloadDirectory = *params.DataRootDirectory
  115. config.RemoteServerListDownloadFilename = filepath.Join(*params.DataRootDirectory, "server_list_compressed")
  116. }
  117. if params.NetworkID != nil {
  118. config.NetworkID = *params.NetworkID
  119. }
  120. if params.ClientPlatform != nil {
  121. config.ClientPlatform = *params.ClientPlatform
  122. } // else use the value in config
  123. if params.EstablishTunnelTimeoutSeconds != nil {
  124. config.EstablishTunnelTimeoutSeconds = params.EstablishTunnelTimeoutSeconds
  125. } // else use the value in config
  126. // config.Commit must be called before calling config.SetClientParameters
  127. // or attempting to connect.
  128. err = config.Commit()
  129. if err != nil {
  130. return nil, common.ContextErrorMsg(err, "config.Commit failed")
  131. }
  132. // If supplied, apply the client parameters delta
  133. if len(paramsDelta) > 0 {
  134. err = config.SetClientParameters("", false, paramsDelta)
  135. if err != nil {
  136. return nil, common.ContextErrorMsg(
  137. err, fmt.Sprintf("SetClientParameters failed for delta: %v", paramsDelta))
  138. }
  139. }
  140. if config.EmitDiagnosticNotices && params.EmitDiagnosticNoticesToFiles {
  141. err := psiphon.SetNoticeFiles("", filepath.Join(config.DataStoreDirectory, "diagnostics.log"), 0, 0)
  142. if err != nil {
  143. return nil, common.ContextErrorMsg(err, "failed to initialize diagnostic logging")
  144. }
  145. }
  146. err = psiphon.OpenDataStore(config)
  147. if err != nil {
  148. return nil, common.ContextErrorMsg(err, "failed to open data store")
  149. }
  150. // Make sure we close the datastore in case of error
  151. defer func() {
  152. if err != nil {
  153. psiphon.CloseDataStore()
  154. }
  155. }()
  156. // Store embedded server entries
  157. serverEntries, err := protocol.DecodeServerEntryList(
  158. embeddedServerEntryList,
  159. common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  160. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  161. if err != nil {
  162. return nil, common.ContextErrorMsg(err, "failed to decode server entry list")
  163. }
  164. err = psiphon.StoreServerEntries(config, serverEntries, false)
  165. if err != nil {
  166. return nil, common.ContextErrorMsg(err, "failed to store server entries")
  167. }
  168. // Will receive a value when the tunnel has successfully connected.
  169. connected := make(chan struct{})
  170. // Will receive a value if the tunnel times out trying to connect.
  171. timedOut := make(chan struct{})
  172. // Will receive a value if an error occurs during the connection sequence.
  173. errored := make(chan error)
  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 = common.ContextErrorMsg(err, "failed to unmarshal notice JSON")
  185. select {
  186. case errored <- 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 timedOut <- struct{}{}:
  200. default:
  201. }
  202. } else if event.Type == "Tunnels" {
  203. count := event.Data["count"].(float64)
  204. if count > 0 {
  205. select {
  206. case connected <- struct{}{}:
  207. default:
  208. }
  209. }
  210. }
  211. // Some users of this package may need to add special processing of notices.
  212. // If the caller has requested it, we'll pass on the notices.
  213. if noticeReceiver != nil {
  214. noticeReceiver(event)
  215. }
  216. }))
  217. // Create the Psiphon controller
  218. controller, err := psiphon.NewController(config)
  219. if err != nil {
  220. return nil, common.ContextErrorMsg(err, "psiphon.NewController failed")
  221. }
  222. // Create a cancelable context that will be used for stopping the tunnel
  223. var controllerCtx context.Context
  224. controllerCtx, tunnel.stopController = context.WithCancel(ctx)
  225. // Begin tunnel connection
  226. tunnel.controllerWaitGroup.Add(1)
  227. go func() {
  228. defer tunnel.controllerWaitGroup.Done()
  229. // Start the tunnel. Only returns on error (or internal timeout).
  230. controller.Run(controllerCtx)
  231. select {
  232. case errored <- errors.New("controller.Run exited unexpectedly"):
  233. default:
  234. }
  235. }()
  236. // Wait for an active tunnel, timeout, or error
  237. select {
  238. case <-connected:
  239. return tunnel, nil
  240. case <-timedOut:
  241. tunnel.Stop()
  242. return nil, ErrTimeout
  243. case err := <-errored:
  244. tunnel.Stop()
  245. return nil, common.ContextErrorMsg(err, "tunnel start produced error")
  246. }
  247. }
  248. // Stop stops/disconnects/shuts down the tunnel. It is safe to call when not connected.
  249. func (tunnel *PsiphonTunnel) Stop() {
  250. if tunnel.stopController != nil {
  251. tunnel.stopController()
  252. }
  253. tunnel.controllerWaitGroup.Wait()
  254. psiphon.CloseDataStore()
  255. }