PsiphonTunnel.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 main
  20. /*
  21. #include <stdlib.h>
  22. #include <stdint.h>
  23. // For descriptions of fields, see below.
  24. // Additional information can also be found in the Parameters structure in clientlib.go.
  25. struct Parameters {
  26. size_t sizeofStruct; // Must be set to sizeof(Parameters); helps with ABI compatibiity
  27. char *dataRootDirectory;
  28. char *clientPlatform;
  29. char *networkID;
  30. int32_t *establishTunnelTimeoutSeconds;
  31. };
  32. */
  33. import "C"
  34. import (
  35. "context"
  36. "encoding/json"
  37. "fmt"
  38. "time"
  39. "unsafe"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/ClientLibrary/clientlib"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  43. )
  44. /*
  45. If/when new fields are added to the C Parameters struct, we can use this code to ensure
  46. ABI compatibility. We'll take these steps:
  47. 1. Copy the old struct into a new `ParametersV1`. The new struct will be `Parameters`.
  48. 2. Uncomment the code below. It will not compile (link, specifically) if the size of
  49. `Parameters` is the same as the size of `ParametersV1`.
  50. - If the compile fails, padding may need to be added to `Parameters` to force it to be
  51. a different size than `ParametersV1`.
  52. 3. In `Start`, we'll check the value of `sizeofStruct` to determine which version of
  53. `Parameters` the caller is using, and behave according.
  54. 4. Do similar kinds of things for V2, V3, etc.
  55. */
  56. /*
  57. func nonexistentFunction()
  58. func init() {
  59. if C.sizeof_struct_Parameters == C.sizeof_struct_ParametersV1 {
  60. // There is only an attempt to link this nonexistent function if the struct sizes
  61. // are the same. So they must not be.
  62. nonexistentFunction()
  63. }
  64. }
  65. */
  66. type startResultCode int
  67. const (
  68. startResultCodeSuccess startResultCode = 0
  69. startResultCodeTimeout = 1
  70. startResultCodeOtherError = 2
  71. )
  72. type startResult struct {
  73. Code startResultCode
  74. ConnectTimeMS int64 `json:",omitempty"`
  75. Error string `json:",omitempty"`
  76. HTTPProxyPort int `json:",omitempty"`
  77. SOCKSProxyPort int `json:",omitempty"`
  78. }
  79. var tunnel *clientlib.PsiphonTunnel
  80. // Memory managed by PsiphonTunnel which is allocated in Start and freed in Stop
  81. var managedStartResult *C.char
  82. //export PsiphonTunnelStart
  83. //
  84. // ******************************* WARNING ********************************
  85. // The underlying memory referenced by the return value of Start is managed
  86. // by PsiphonTunnel and attempting to free it explicitly will cause the
  87. // program to crash. This memory is freed once Stop is called, or if Start
  88. // is called again.
  89. // ************************************************************************
  90. //
  91. // Start starts the controller and returns once one of the following has occured:
  92. // an active tunnel has been established, the timeout has elapsed before an active tunnel
  93. // could be established, or an error has occured.
  94. //
  95. // Start returns a startResult object serialized as a JSON string in the form of a
  96. // null-terminated buffer of C chars.
  97. // Start will return,
  98. // On success:
  99. // {
  100. // "Code": 0,
  101. // "ConnectTimeMS": <milliseconds to establish tunnel>,
  102. // "HTTPProxyPort": <http proxy port number>,
  103. // "SOCKSProxyPort": <socks proxy port number>
  104. // }
  105. //
  106. // On timeout:
  107. // {
  108. // "Code": 1,
  109. // "Error": <error message>
  110. // }
  111. //
  112. // On other error:
  113. // {
  114. // "Code": 2,
  115. // "Error": <error message>
  116. // }
  117. //
  118. // Parameters.clientPlatform should be of the form OS_OSVersion_BundleIdentifier where
  119. // both the OSVersion and BundleIdentifier fields are optional. If clientPlatform is set
  120. // to an empty string the "ClientPlatform" field in the provided JSON config will be
  121. // used instead.
  122. //
  123. // Provided below are links to platform specific code which can be used to find some of the above fields:
  124. // Android:
  125. // - OSVersion: https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/Android/PsiphonTunnel/PsiphonTunnel.java#L573
  126. // - BundleIdentifier: https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/Android/PsiphonTunnel/PsiphonTunnel.java#L575
  127. // iOS:
  128. // - OSVersion: https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/iOS/PsiphonTunnel/PsiphonTunnel/PsiphonTunnel.m#L612
  129. // - BundleIdentifier: https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/iOS/PsiphonTunnel/PsiphonTunnel/PsiphonTunnel.m#L622
  130. //
  131. // Some examples of valid client platform strings are:
  132. //
  133. // "Android_4.2.2_com.example.exampleApp"
  134. // "iOS_11.4_com.example.exampleApp"
  135. // "Windows"
  136. //
  137. // Parameters.networkID must be a non-empty string and follow the format specified by:
  138. // https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter.
  139. // Provided below are links to platform specific code which can be used to generate
  140. // valid network identifier strings:
  141. // Android:
  142. // - https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/Android/PsiphonTunnel/PsiphonTunnel.java#L371
  143. // iOS:
  144. // - https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/iOS/PsiphonTunnel/PsiphonTunnel/PsiphonTunnel.m#L1105
  145. //
  146. // Parameters.establishTunnelTimeoutSeconds specifies a time limit after which to stop
  147. // attempting to connect and return an error if an active tunnel has not been established.
  148. // A timeout of 0 will result in no timeout condition and the controller will attempt to
  149. // establish an active tunnel indefinitely (or until PsiphonTunnelStop is called).
  150. // Timeout values >= 0 override the optional `EstablishTunnelTimeoutSeconds` config field;
  151. // null causes the config value to be used.
  152. func PsiphonTunnelStart(cConfigJSON, cEmbeddedServerEntryList *C.char, cParams *C.struct_Parameters) *C.char {
  153. // Stop any active tunnels
  154. PsiphonTunnelStop()
  155. if cConfigJSON == nil {
  156. err := errors.Tracef("configJSON is required")
  157. managedStartResult = startErrorJSON(err)
  158. return managedStartResult
  159. }
  160. if cParams == nil {
  161. err := errors.Tracef("params is required")
  162. managedStartResult = startErrorJSON(err)
  163. return managedStartResult
  164. }
  165. if cParams.sizeofStruct != C.sizeof_struct_Parameters {
  166. err := errors.Tracef("sizeofStruct does not match sizeof(Parameters)")
  167. managedStartResult = startErrorJSON(err)
  168. return managedStartResult
  169. }
  170. // NOTE: all arguments which may be referenced once Start returns must be copied onto
  171. // the Go heap to ensure that they don't disappear later on and cause Go to crash.
  172. configJSON := []byte(C.GoString(cConfigJSON))
  173. embeddedServerEntryList := C.GoString(cEmbeddedServerEntryList)
  174. params := clientlib.Parameters{}
  175. if cParams.dataRootDirectory != nil {
  176. v := C.GoString(cParams.dataRootDirectory)
  177. params.DataRootDirectory = &v
  178. }
  179. if cParams.clientPlatform != nil {
  180. v := C.GoString(cParams.clientPlatform)
  181. params.ClientPlatform = &v
  182. }
  183. if cParams.networkID != nil {
  184. v := C.GoString(cParams.networkID)
  185. params.NetworkID = &v
  186. }
  187. if cParams.establishTunnelTimeoutSeconds != nil {
  188. v := int(*cParams.establishTunnelTimeoutSeconds)
  189. params.EstablishTunnelTimeoutSeconds = &v
  190. }
  191. // As Client Library doesn't currently implement callbacks, diagnostic
  192. // notices aren't relayed to the client application. Set
  193. // EmitDiagnosticNoticesToFiles to ensure the rotating diagnostic log file
  194. // facility is used when EmitDiagnosticNotices is specified in the config.
  195. params.EmitDiagnosticNoticesToFiles = true
  196. startTime := time.Now()
  197. // Start the tunnel connection
  198. var err error
  199. tunnel, err = clientlib.StartTunnel(
  200. context.Background(), configJSON, embeddedServerEntryList, params, nil, nil)
  201. if err != nil {
  202. if err == clientlib.ErrTimeout {
  203. managedStartResult = marshalStartResult(startResult{
  204. Code: startResultCodeTimeout,
  205. Error: fmt.Sprintf("Timeout occurred before Psiphon connected: %s", err.Error()),
  206. })
  207. } else {
  208. managedStartResult = marshalStartResult(startResult{
  209. Code: startResultCodeOtherError,
  210. Error: err.Error(),
  211. })
  212. }
  213. return managedStartResult
  214. }
  215. // Success
  216. managedStartResult = marshalStartResult(startResult{
  217. Code: startResultCodeSuccess,
  218. ConnectTimeMS: int64(time.Now().Sub(startTime) / time.Millisecond),
  219. HTTPProxyPort: tunnel.HTTPProxyPort,
  220. SOCKSProxyPort: tunnel.SOCKSProxyPort,
  221. })
  222. return managedStartResult
  223. }
  224. //export PsiphonTunnelStop
  225. //
  226. // Stop stops the controller if it is running and waits for it to clean up and exit.
  227. //
  228. // Stop should always be called after a successful call to Start to ensure the
  229. // controller is not left running and memory is released.
  230. // It is safe to call this function when the tunnel is not running.
  231. func PsiphonTunnelStop() {
  232. freeManagedStartResult()
  233. if tunnel != nil {
  234. tunnel.Stop()
  235. }
  236. }
  237. // marshalStartResult serializes a startResult object as a JSON string in the form
  238. // of a null-terminated buffer of C chars.
  239. func marshalStartResult(result startResult) *C.char {
  240. resultJSON, err := json.Marshal(result)
  241. if err != nil {
  242. err = errors.TraceMsg(err, "json.Marshal failed")
  243. // Fail back to manually constructing the JSON
  244. return C.CString(fmt.Sprintf("{\"Code\":%d, \"Error\": \"%s\"}",
  245. startResultCodeOtherError, err.Error()))
  246. }
  247. return C.CString(string(resultJSON))
  248. }
  249. // startErrorJSON returns a startResult object serialized as a JSON string in the form of
  250. // a null-terminated buffer of C chars. The object's return result code will be set to
  251. // startResultCodeOtherError (2) and its error string set to the error string of the
  252. // provided error.
  253. //
  254. // The JSON will be in the form of:
  255. // {
  256. // "Code": 2,
  257. // "Error": <error message>
  258. // }
  259. func startErrorJSON(err error) *C.char {
  260. var result startResult
  261. result.Code = startResultCodeOtherError
  262. result.Error = err.Error()
  263. return marshalStartResult(result)
  264. }
  265. // freeManagedStartResult frees the memory on the heap pointed to by managedStartResult.
  266. func freeManagedStartResult() {
  267. if managedStartResult != nil {
  268. managedMemory := unsafe.Pointer(managedStartResult)
  269. if managedMemory != nil {
  270. C.free(managedMemory)
  271. }
  272. managedStartResult = nil
  273. }
  274. }
  275. // main is a stub required by cgo.
  276. func main() {}