PsiphonTunnel.go 11 KB

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