PsiphonTunnel.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. package main
  2. // #include <stdlib.h>
  3. import "C"
  4. import (
  5. "context"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "sync"
  10. "time"
  11. "unsafe"
  12. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  13. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  14. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  15. )
  16. type startResultCode int
  17. const (
  18. startResultCodeSuccess startResultCode = iota
  19. startResultCodeTimeout
  20. startResultCodeOtherError
  21. )
  22. type noticeEvent struct {
  23. Data map[string]interface{} `json:"data"`
  24. NoticeType string `json:"noticeType"`
  25. }
  26. type startResult struct {
  27. Code startResultCode `json:"result_code"`
  28. BootstrapTime float64 `json:"bootstrap_time,omitempty"`
  29. ErrorString string `json:"error,omitempty"`
  30. HttpProxyPort int `json:"http_proxy_port,omitempty"`
  31. SocksProxyPort int `json:"socks_proxy_port,omitempty"`
  32. }
  33. type psiphonTunnel struct {
  34. controllerWaitGroup sync.WaitGroup
  35. controllerCtx context.Context
  36. stopController context.CancelFunc
  37. httpProxyPort int
  38. socksProxyPort int
  39. }
  40. var tunnel psiphonTunnel
  41. // Memory managed by PsiphonTunnel which is allocated in Start and freed in Stop
  42. var managedStartResult *C.char
  43. //export Start
  44. //
  45. // ******************************* WARNING ********************************
  46. // The underlying memory referenced by the return value of Start is managed
  47. // by PsiphonTunnel and attempting to free it explicitly will cause the
  48. // program to crash. This memory is freed once Stop is called.
  49. // ************************************************************************
  50. //
  51. // Start starts the controller and returns once either of the following has occured: an active tunnel has been
  52. // established, the timeout has elapsed before an active tunnel could be established or an error has occured.
  53. //
  54. // Start returns a startResult object serialized as a JSON string in the form of a null-terminated buffer of C chars.
  55. // Start will return,
  56. // On success:
  57. // {
  58. // "result_code": 0,
  59. // "bootstrap_time": <time_to_establish_tunnel>,
  60. // "http_proxy_port": <http_proxy_port_num>,
  61. // "socks_proxy_port": <socks_proxy_port_num>
  62. // }
  63. //
  64. // On timeout:
  65. // {
  66. // "result_code": 1,
  67. // "error": <error message>
  68. // }
  69. //
  70. // On other error:
  71. // {
  72. // "result_code": 2,
  73. // "error": <error message>
  74. // }
  75. //
  76. // clientPlatform should be of the form OS_OSVersion_BundleIdentifier where both the OSVersion and BundleIdentifier
  77. // fields are optional.
  78. //
  79. // Provided below are links to platform specific code which can be used to find some of the above fields:
  80. // Android:
  81. // - OSVersion: https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/Android/PsiphonTunnel/PsiphonTunnel.java#L573
  82. // - BundleIdentifier: https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/Android/PsiphonTunnel/PsiphonTunnel.java#L575
  83. // iOS:
  84. // - OSVersion: https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/iOS/PsiphonTunnel/PsiphonTunnel/PsiphonTunnel.m#L612
  85. // - BundleIdentifier: https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3d344194d21b250e0f18ededa4b4459a373b0690/MobileLibrary/iOS/PsiphonTunnel/PsiphonTunnel/PsiphonTunnel.m#L622
  86. //
  87. // Some examples of valid client platform strings are:
  88. //
  89. // "Android_4.2.2_com.example.exampleApp"
  90. // "iOS_11.4_com.example.exampleApp"
  91. // "Windows"
  92. //
  93. // networkID should be not be blank and should follow the format specified by
  94. // https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter.
  95. func Start(configJSON, embeddedServerEntryList, clientPlatform, networkID string, timeout int64) *C.char {
  96. // Load provided config
  97. config, err := psiphon.LoadConfig([]byte(configJSON))
  98. if err != nil {
  99. return startErrorJson(err)
  100. }
  101. // Set network ID
  102. if networkID != "" {
  103. config.NetworkID = networkID
  104. }
  105. // Set client platform
  106. config.ClientPlatform = clientPlatform;
  107. // All config fields should be set before calling commit
  108. err = config.Commit()
  109. if err != nil {
  110. return startErrorJson(err)
  111. }
  112. // Setup signals
  113. connected := make(chan bool)
  114. testError := make(chan error)
  115. // Set up notice handling
  116. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  117. func(notice []byte) {
  118. var event noticeEvent
  119. err := json.Unmarshal(notice, &event)
  120. if err != nil {
  121. err = errors.New(fmt.Sprintf("Failed to unmarshal json: %s", err.Error()))
  122. select {
  123. case testError <- err:
  124. default:
  125. }
  126. }
  127. if event.NoticeType == "ListeningHttpProxyPort" {
  128. port := event.Data["port"].(float64)
  129. tunnel.httpProxyPort = int(port)
  130. } else if event.NoticeType == "ListeningSocksProxyPort" {
  131. port := event.Data["port"].(float64)
  132. tunnel.socksProxyPort = int(port)
  133. } else if event.NoticeType == "Tunnels" {
  134. count := event.Data["count"].(float64)
  135. if count > 0 {
  136. select {
  137. case connected <- true:
  138. default:
  139. }
  140. }
  141. }
  142. }))
  143. // Initialize data store
  144. err = psiphon.InitDataStore(config)
  145. if err != nil {
  146. return startErrorJson(err)
  147. }
  148. // Store embedded server entries
  149. serverEntries, err := protocol.DecodeServerEntryList(
  150. embeddedServerEntryList,
  151. common.GetCurrentTimestamp(),
  152. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  153. if err != nil {
  154. return startErrorJson(err)
  155. }
  156. err = psiphon.StoreServerEntries(config, serverEntries, false)
  157. if err != nil {
  158. return startErrorJson(err)
  159. }
  160. // Run Psiphon
  161. controller, err := psiphon.NewController(config)
  162. if err != nil {
  163. return startErrorJson(err)
  164. }
  165. tunnel.controllerCtx, tunnel.stopController = context.WithCancel(context.Background())
  166. // Set start time
  167. startTime := time.Now()
  168. // Setup timeout signal
  169. runtimeTimeout := time.Duration(timeout) * time.Second
  170. timeoutSignal, cancelTimeout := context.WithTimeout(context.Background(), runtimeTimeout)
  171. defer cancelTimeout()
  172. // Run test
  173. var result startResult
  174. tunnel.controllerWaitGroup.Add(1)
  175. go func() {
  176. defer tunnel.controllerWaitGroup.Done()
  177. controller.Run(tunnel.controllerCtx)
  178. select {
  179. case testError <- errors.New("controller.Run exited unexpectedly"):
  180. default:
  181. }
  182. }()
  183. // Wait for an active tunnel, timeout or error
  184. select {
  185. case <-connected:
  186. result.Code = startResultCodeSuccess
  187. result.BootstrapTime = secondsBeforeNow(startTime)
  188. result.HttpProxyPort = tunnel.httpProxyPort
  189. result.SocksProxyPort = tunnel.socksProxyPort
  190. case <-timeoutSignal.Done():
  191. result.Code = startResultCodeTimeout
  192. err = timeoutSignal.Err()
  193. if err != nil {
  194. result.ErrorString = fmt.Sprintf("Timeout occured before Psiphon connected: %s", err.Error())
  195. }
  196. tunnel.stopController()
  197. case err := <-testError:
  198. result.Code = startResultCodeOtherError
  199. result.ErrorString = err.Error()
  200. tunnel.stopController()
  201. }
  202. // Free previous result
  203. freeManagedStartResult()
  204. // Return result
  205. managedStartResult = marshalStartResult(result)
  206. return managedStartResult
  207. }
  208. //export Stop
  209. // Stop stops the controller if it is running and waits for it to clean up and exit.
  210. //
  211. // Stop should always be called after a successful call to Start to ensure the
  212. // controller is not left running.
  213. func Stop() {
  214. freeManagedStartResult()
  215. if tunnel.stopController != nil {
  216. tunnel.stopController()
  217. }
  218. tunnel.controllerWaitGroup.Wait()
  219. }
  220. // secondsBeforeNow returns the delta seconds of the current time subtract startTime.
  221. func secondsBeforeNow(startTime time.Time) float64 {
  222. delta := time.Now().Sub(startTime)
  223. return delta.Seconds()
  224. }
  225. // marshalStartResult serializes a startResult object as a JSON string in the form
  226. // of a null-terminated buffer of C chars.
  227. func marshalStartResult(result startResult) *C.char {
  228. resultJSON, err := json.Marshal(result)
  229. if err != nil {
  230. return C.CString(fmt.Sprintf("{\"result_code\":%d, \"error\": \"%s\"}", startResultCodeOtherError, err.Error()))
  231. }
  232. return C.CString(string(resultJSON))
  233. }
  234. // startErrorJson returns a startResult object serialized as a JSON string in the form
  235. // of a null-terminated buffer of C chars. The object's return result code will be set to
  236. // startResultCodeOtherError (2) and its error string set to the error string of the provided error.
  237. //
  238. // The JSON will be in the form of:
  239. // {
  240. // "result_code": 2,
  241. // "error": <error message>
  242. // }
  243. func startErrorJson(err error) *C.char {
  244. var result startResult
  245. result.Code = startResultCodeOtherError
  246. result.ErrorString = err.Error()
  247. return marshalStartResult(result)
  248. }
  249. // freeManagedStartResult frees the memory on the heap pointed to by managedStartResult.
  250. func freeManagedStartResult() {
  251. if managedStartResult != nil {
  252. managedMemory := unsafe.Pointer(managedStartResult)
  253. if managedMemory != nil {
  254. C.free(managedMemory)
  255. }
  256. }
  257. }
  258. // main is a stub required by cgo.
  259. func main() {}