PsiphonTunnel.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. )
  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 = 1
  69. startResultCodeOtherError = 2
  70. )
  71. type noticeEvent struct {
  72. Data map[string]interface{}
  73. NoticeType string
  74. }
  75. type startResult struct {
  76. Code startResultCode
  77. ConnectTimeMS int64 `json:",omitempty"`
  78. Error string `json:",omitempty"`
  79. HTTPProxyPort int `json:",omitempty"`
  80. SOCKSProxyPort int `json:",omitempty"`
  81. }
  82. var tunnel *clientlib.PsiphonTunnel
  83. // Memory managed by PsiphonTunnel which is allocated in Start and freed in Stop
  84. var managedStartResult *C.char
  85. //export PsiphonTunnelStart
  86. //
  87. // ******************************* WARNING ********************************
  88. // The underlying memory referenced by the return value of Start is managed
  89. // by PsiphonTunnel and attempting to free it explicitly will cause the
  90. // program to crash. This memory is freed once Stop is called, or if Start
  91. // is called again.
  92. // ************************************************************************
  93. //
  94. // Start starts the controller and returns once one of the following has occured:
  95. // an active tunnel has been established, the timeout has elapsed before an active tunnel
  96. // could be established, or an error has occured.
  97. //
  98. // Start returns a startResult object serialized as a JSON string in the form of a
  99. // null-terminated buffer of C chars.
  100. // Start will return,
  101. // On success:
  102. // {
  103. // "Code": 0,
  104. // "ConnectTimeMS": <milliseconds to establish tunnel>,
  105. // "HTTPProxyPort": <http proxy port number>,
  106. // "SOCKSProxyPort": <socks proxy port number>
  107. // }
  108. //
  109. // On timeout:
  110. // {
  111. // "Code": 1,
  112. // "Error": <error message>
  113. // }
  114. //
  115. // On other error:
  116. // {
  117. // "Code": 2,
  118. // "Error": <error message>
  119. // }
  120. //
  121. // Parameters.clientPlatform should be of the form OS_OSVersion_BundleIdentifier where
  122. // both the OSVersion and BundleIdentifier fields are optional. If clientPlatform is set
  123. // to an empty string the "ClientPlatform" field in the provided JSON config will be
  124. // used instead.
  125. //
  126. // Provided below are links to platform specific code which can be used to find some of the above fields:
  127. // Android:
  128. // - OSVersion: https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/Android/PsiphonTunnel/PsiphonTunnel.java#L573
  129. // - BundleIdentifier: https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/Android/PsiphonTunnel/PsiphonTunnel.java#L575
  130. // iOS:
  131. // - OSVersion: https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/iOS/PsiphonTunnel/PsiphonTunnel/PsiphonTunnel.m#L612
  132. // - BundleIdentifier: https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/iOS/PsiphonTunnel/PsiphonTunnel/PsiphonTunnel.m#L622
  133. //
  134. // Some examples of valid client platform strings are:
  135. //
  136. // "Android_4.2.2_com.example.exampleApp"
  137. // "iOS_11.4_com.example.exampleApp"
  138. // "Windows"
  139. //
  140. // Parameters.networkID must be a non-empty string and follow the format specified by:
  141. // https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter.
  142. // Provided below are links to platform specific code which can be used to generate
  143. // valid network identifier strings:
  144. // Android:
  145. // - https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/Android/PsiphonTunnel/PsiphonTunnel.java#L371
  146. // iOS:
  147. // - https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/iOS/PsiphonTunnel/PsiphonTunnel/PsiphonTunnel.m#L1105
  148. //
  149. // Parameters.establishTunnelTimeoutSeconds specifies a time limit after which to stop
  150. // attempting to connect and return an error if an active tunnel has not been established.
  151. // A timeout of 0 will result in no timeout condition and the controller will attempt to
  152. // establish an active tunnel indefinitely (or until PsiphonTunnelStop is called).
  153. // Timeout values >= 0 override the optional `EstablishTunnelTimeoutSeconds` config field;
  154. // null causes the config value to be used.
  155. func PsiphonTunnelStart(cConfigJSON, cEmbeddedServerEntryList *C.char, cParams *C.struct_Parameters) *C.char {
  156. // Stop any active tunnels
  157. PsiphonTunnelStop()
  158. if cConfigJSON == nil {
  159. err := common.ContextError(fmt.Errorf("configJSON is required"))
  160. managedStartResult = startErrorJSON(err)
  161. return managedStartResult
  162. }
  163. if cParams == nil {
  164. err := common.ContextError(fmt.Errorf("params is required"))
  165. managedStartResult = startErrorJSON(err)
  166. return managedStartResult
  167. }
  168. if cParams.sizeofStruct != C.sizeof_struct_Parameters {
  169. err := common.ContextError(fmt.Errorf("sizeofStruct does not match sizeof(Parameters)"))
  170. managedStartResult = startErrorJSON(err)
  171. return managedStartResult
  172. }
  173. // NOTE: all arguments which may be referenced once Start returns must be copied onto
  174. // the Go heap to ensure that they don't disappear later on and cause Go to crash.
  175. configJSON := []byte(C.GoString(cConfigJSON))
  176. embeddedServerEntryList := C.GoString(cEmbeddedServerEntryList)
  177. params := clientlib.Parameters{}
  178. if cParams.dataRootDirectory != nil {
  179. v := C.GoString(cParams.dataRootDirectory)
  180. params.DataRootDirectory = &v
  181. }
  182. if cParams.clientPlatform != nil {
  183. v := C.GoString(cParams.clientPlatform)
  184. params.ClientPlatform = &v
  185. }
  186. if cParams.networkID != nil {
  187. v := C.GoString(cParams.networkID)
  188. params.NetworkID = &v
  189. }
  190. if cParams.establishTunnelTimeoutSeconds != nil {
  191. v := int(*cParams.establishTunnelTimeoutSeconds)
  192. params.EstablishTunnelTimeoutSeconds = &v
  193. }
  194. startTime := time.Now()
  195. // Start the tunnel connection
  196. var err error
  197. tunnel, err = clientlib.StartTunnel(
  198. context.Background(), configJSON, embeddedServerEntryList, params, nil, nil)
  199. if err != nil {
  200. if err == clientlib.ErrTimeout {
  201. managedStartResult = marshalStartResult(startResult{
  202. Code: startResultCodeTimeout,
  203. Error: fmt.Sprintf("Timeout occurred before Psiphon connected: %s", err.Error()),
  204. })
  205. } else {
  206. managedStartResult = marshalStartResult(startResult{
  207. Code: startResultCodeOtherError,
  208. Error: err.Error(),
  209. })
  210. }
  211. return managedStartResult
  212. }
  213. // Success
  214. managedStartResult = marshalStartResult(startResult{
  215. Code: startResultCodeSuccess,
  216. ConnectTimeMS: int64(time.Now().Sub(startTime) / time.Millisecond),
  217. HTTPProxyPort: tunnel.HTTPProxyPort,
  218. SOCKSProxyPort: tunnel.SOCKSProxyPort,
  219. })
  220. return managedStartResult
  221. }
  222. //export PsiphonTunnelStop
  223. //
  224. // Stop stops the controller if it is running and waits for it to clean up and exit.
  225. //
  226. // Stop should always be called after a successful call to Start to ensure the
  227. // controller is not left running and memory is released.
  228. // It is safe to call this function when the tunnel is not running.
  229. func PsiphonTunnelStop() {
  230. freeManagedStartResult()
  231. if tunnel != nil {
  232. tunnel.Stop()
  233. }
  234. }
  235. // marshalStartResult serializes a startResult object as a JSON string in the form
  236. // of a null-terminated buffer of C chars.
  237. func marshalStartResult(result startResult) *C.char {
  238. resultJSON, err := json.Marshal(result)
  239. if err != nil {
  240. err = common.ContextErrorMsg(err, "json.Marshal failed")
  241. // Fail back to manually constructing the JSON
  242. return C.CString(fmt.Sprintf("{\"Code\":%d, \"Error\": \"%s\"}",
  243. startResultCodeOtherError, err.Error()))
  244. }
  245. return C.CString(string(resultJSON))
  246. }
  247. // startErrorJSON returns a startResult object serialized as a JSON string in the form of
  248. // a null-terminated buffer of C chars. The object's return result code will be set to
  249. // startResultCodeOtherError (2) and its error string set to the error string of the
  250. // provided error.
  251. //
  252. // The JSON will be in the form of:
  253. // {
  254. // "Code": 2,
  255. // "Error": <error message>
  256. // }
  257. func startErrorJSON(err error) *C.char {
  258. var result startResult
  259. result.Code = startResultCodeOtherError
  260. result.Error = err.Error()
  261. return marshalStartResult(result)
  262. }
  263. // freeManagedStartResult frees the memory on the heap pointed to by managedStartResult.
  264. func freeManagedStartResult() {
  265. if managedStartResult != nil {
  266. managedMemory := unsafe.Pointer(managedStartResult)
  267. if managedMemory != nil {
  268. C.free(managedMemory)
  269. }
  270. managedStartResult = nil
  271. }
  272. }
  273. // main is a stub required by cgo.
  274. func main() {}