PsiphonTunnel.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. package main
  2. import "C"
  3. import (
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "sync"
  9. "time"
  10. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  11. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  12. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  13. )
  14. type StartResultCode int
  15. const (
  16. StartResultCodeSuccess StartResultCode = iota
  17. StartResultCodeTimeout
  18. StartResultCodeOtherError
  19. )
  20. type NoticeEvent struct {
  21. Data map[string]interface{} `json:"data"`
  22. NoticeType string `json:"noticeType"`
  23. }
  24. type StartResult struct {
  25. Code StartResultCode `json:"result_code"`
  26. BootstrapTime float64 `json:"bootstrap_time,omitempty"`
  27. ErrorString string `json:"error,omitempty"`
  28. HttpProxyPort int `json:"http_proxy_port,omitempty"`
  29. SocksProxyPort int `json:"socks_proxy_port,omitempty"`
  30. }
  31. type PsiphonTunnel struct {
  32. controllerWaitGroup sync.WaitGroup
  33. controllerCtx context.Context
  34. stopController context.CancelFunc
  35. httpProxyPort int
  36. socksProxyPort int
  37. }
  38. var psiphonTunnel PsiphonTunnel
  39. //export Start
  40. // Start starts the controller and returns once either of the following has occured: an active tunnel has been
  41. // established, the timeout has elapsed before an active tunnel could be established or an error has occured.
  42. //
  43. // Start returns a StartResult object serialized as a JSON string in the form of a null-terminated buffer of C chars.
  44. // Start will return,
  45. // On success:
  46. // {
  47. // "result_code": 0,
  48. // "bootstrap_time": <time_to_establish_tunnel>,
  49. // "http_proxy_port": <http_proxy_port_num>,
  50. // "socks_proxy_port": <socks_proxy_port_num>
  51. // }
  52. //
  53. // On timeout:
  54. // {
  55. // "result_code": 1,
  56. // "error": <error message>
  57. // }
  58. //
  59. // On other error:
  60. // {
  61. // "result_code": 2,
  62. // "error": <error message>
  63. // }
  64. //
  65. // networkID should be not be blank and should follow the format specified by
  66. // https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter.
  67. func Start(configJSON, embeddedServerEntryList, networkID string, timeout int64) *C.char {
  68. // Load provided config
  69. config, err := psiphon.LoadConfig([]byte(configJSON))
  70. if err != nil {
  71. return startErrorJson(err)
  72. }
  73. // Set network ID
  74. if networkID != "" {
  75. config.NetworkID = networkID
  76. }
  77. // All config fields should be set before calling commit
  78. err = config.Commit()
  79. if err != nil {
  80. return startErrorJson(err)
  81. }
  82. // Setup signals
  83. connected := make(chan bool)
  84. testError := make(chan error)
  85. // Set up notice handling
  86. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  87. func(notice []byte) {
  88. var event NoticeEvent
  89. err := json.Unmarshal(notice, &event)
  90. if err != nil {
  91. err = errors.New(fmt.Sprintf("Failed to unmarshal json: %s", err.Error()))
  92. select {
  93. case testError <- err:
  94. default:
  95. }
  96. }
  97. if event.NoticeType == "ListeningHttpProxyPort" {
  98. port := event.Data["port"].(float64)
  99. psiphonTunnel.httpProxyPort = int(port)
  100. } else if event.NoticeType == "ListeningSocksProxyPort" {
  101. port := event.Data["port"].(float64)
  102. psiphonTunnel.socksProxyPort = int(port)
  103. } else if event.NoticeType == "Tunnels" {
  104. count := event.Data["count"].(float64)
  105. if count > 0 {
  106. select {
  107. case connected <- true:
  108. default:
  109. }
  110. }
  111. }
  112. }))
  113. // Initialize data store
  114. err = psiphon.InitDataStore(config)
  115. if err != nil {
  116. return startErrorJson(err)
  117. }
  118. // Store embedded server entries
  119. serverEntries, err := protocol.DecodeServerEntryList(
  120. embeddedServerEntryList,
  121. common.GetCurrentTimestamp(),
  122. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  123. if err != nil {
  124. return startErrorJson(err)
  125. }
  126. err = psiphon.StoreServerEntries(config, serverEntries, false)
  127. if err != nil {
  128. return startErrorJson(err)
  129. }
  130. // Run Psiphon
  131. controller, err := psiphon.NewController(config)
  132. if err != nil {
  133. return startErrorJson(err)
  134. }
  135. psiphonTunnel.controllerCtx, psiphonTunnel.stopController = context.WithCancel(context.Background())
  136. // Set start time
  137. startTime := time.Now()
  138. // Setup timeout signal
  139. runtimeTimeout := time.Duration(timeout) * time.Second
  140. timeoutSignal, cancelTimeout := context.WithTimeout(context.Background(), runtimeTimeout)
  141. defer cancelTimeout()
  142. // Run test
  143. var result StartResult
  144. psiphonTunnel.controllerWaitGroup.Add(1)
  145. go func() {
  146. defer psiphonTunnel.controllerWaitGroup.Done()
  147. controller.Run(psiphonTunnel.controllerCtx)
  148. select {
  149. case testError <- errors.New("controller.Run exited unexpectedly"):
  150. default:
  151. }
  152. }()
  153. // Wait for an active tunnel, timeout or error
  154. select {
  155. case <-connected:
  156. result.Code = StartResultCodeSuccess
  157. result.BootstrapTime = secondsBeforeNow(startTime)
  158. result.HttpProxyPort = psiphonTunnel.httpProxyPort
  159. result.SocksProxyPort = psiphonTunnel.socksProxyPort
  160. case <-timeoutSignal.Done():
  161. result.Code = StartResultCodeTimeout
  162. err = timeoutSignal.Err()
  163. if err != nil {
  164. result.ErrorString = fmt.Sprintf("Timeout occured before Psiphon connected: %s", err.Error())
  165. }
  166. psiphonTunnel.stopController()
  167. case err := <-testError:
  168. result.Code = StartResultCodeOtherError
  169. result.ErrorString = err.Error()
  170. psiphonTunnel.stopController()
  171. }
  172. // Return result
  173. return marshalStartResult(result)
  174. }
  175. //export Stop
  176. // Stop stops the controller if it is running and waits for it to clean up and exit.
  177. //
  178. // Stop should always be called after a successful call to Start to ensure the
  179. // controller is not left running.
  180. func Stop() {
  181. if psiphonTunnel.stopController != nil {
  182. psiphonTunnel.stopController()
  183. }
  184. psiphonTunnel.controllerWaitGroup.Wait()
  185. }
  186. // secondsBeforeNow returns the delta seconds of the current time subtract startTime.
  187. func secondsBeforeNow(startTime time.Time) float64 {
  188. delta := time.Now().Sub(startTime)
  189. return delta.Seconds()
  190. }
  191. // marshalStartResult serializes a StartResult object as a JSON string in the form
  192. // of a null-terminated buffer of C chars.
  193. func marshalStartResult(result StartResult) *C.char {
  194. resultJSON, err := json.Marshal(result)
  195. if err != nil {
  196. return C.CString(fmt.Sprintf("{\"result_code\":%d, \"error\": \"%s\"}", StartResultCodeOtherError, err.Error()))
  197. }
  198. return C.CString(string(resultJSON))
  199. }
  200. // startErrorJson returns a StartResult object serialized as a JSON string in the form
  201. // of a null-terminated buffer of C chars. The object's return result code will be set to
  202. // StartResultCodeOtherError (2) and its error string set to the error string of the provided error.
  203. //
  204. // The JSON will be in the form of:
  205. // {
  206. // "result_code": 2,
  207. // "error": <error message>
  208. // }
  209. func startErrorJson(err error) *C.char {
  210. var result StartResult
  211. result.Code = StartResultCodeOtherError
  212. result.ErrorString = err.Error()
  213. return marshalStartResult(result)
  214. }
  215. // main is a stub required by cgo.
  216. func main() {}