PsiphonTunnel.go 11 KB

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