psi.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /*
  2. * Copyright (c) 2015, 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 psi
  20. // This package is a shim between Java/Obj-C and the "psiphon" package. Due to limitations
  21. // on what Go types may be exposed (http://godoc.org/golang.org/x/mobile/cmd/gobind),
  22. // a psiphon.Controller cannot be directly used by Java. This shim exposes a trivial
  23. // Start/Stop interface on top of a single Controller instance.
  24. import (
  25. "context"
  26. "encoding/json"
  27. "fmt"
  28. "sync"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  33. "os"
  34. )
  35. type PsiphonProvider interface {
  36. Notice(noticeJSON string)
  37. HasNetworkConnectivity() int
  38. BindToDevice(fileDescriptor int) (string, error)
  39. IPv6Synthesize(IPv4Addr string) string
  40. GetPrimaryDnsServer() string
  41. GetSecondaryDnsServer() string
  42. }
  43. func SetNoticeFiles(
  44. homepageFilename,
  45. rotatingFilename string,
  46. rotatingFileSize,
  47. rotatingSyncFrequency int) error {
  48. return psiphon.SetNoticeFiles(
  49. homepageFilename,
  50. rotatingFilename,
  51. rotatingFileSize,
  52. rotatingSyncFrequency)
  53. }
  54. func NoticeUserLog(message string) {
  55. psiphon.NoticeUserLog(message)
  56. }
  57. var controllerMutex sync.Mutex
  58. var controller *psiphon.Controller
  59. var controllerCtx context.Context
  60. var stopController context.CancelFunc
  61. var controllerWaitGroup *sync.WaitGroup
  62. func Start(
  63. configJson,
  64. embeddedServerEntryList,
  65. embeddedServerEntryListFilename string,
  66. provider PsiphonProvider,
  67. useDeviceBinder,
  68. useIPv6Synthesizer bool) error {
  69. controllerMutex.Lock()
  70. defer controllerMutex.Unlock()
  71. if controller != nil {
  72. return fmt.Errorf("already started")
  73. }
  74. // Wrap the provider in a layer that locks a mutex before calling a provider function.
  75. // The the provider callbacks are Java/Obj-C via gomobile, they are cgo calls that
  76. // can cause OS threads to be spawned. The mutex prevents many calling goroutines from
  77. // causing unbounded numbers of OS threads to be spawned.
  78. // TODO: replace the mutex with a semaphore, to allow a larger but still bounded concurrent
  79. // number of calls to the provider?
  80. provider = newMutexPsiphonProvider(provider)
  81. config, err := psiphon.LoadConfig([]byte(configJson))
  82. if err != nil {
  83. return fmt.Errorf("error loading configuration file: %s", err)
  84. }
  85. config.NetworkConnectivityChecker = provider
  86. if useDeviceBinder {
  87. config.DeviceBinder = newLoggingDeviceBinder(provider)
  88. config.DnsServerGetter = provider
  89. }
  90. if useIPv6Synthesizer {
  91. config.IPv6Synthesizer = provider
  92. }
  93. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  94. func(notice []byte) {
  95. provider.Notice(string(notice))
  96. }))
  97. psiphon.NoticeBuildInfo()
  98. err = psiphon.InitDataStore(config)
  99. if err != nil {
  100. return fmt.Errorf("error initializing datastore: %s", err)
  101. }
  102. // Stores list of server entries.
  103. err = storeServerEntries(embeddedServerEntryListFilename, embeddedServerEntryList)
  104. if err != nil {
  105. return err
  106. }
  107. controller, err = psiphon.NewController(config)
  108. if err != nil {
  109. return fmt.Errorf("error initializing controller: %s", err)
  110. }
  111. controllerCtx, stopController = context.WithCancel(context.Background())
  112. controllerWaitGroup = new(sync.WaitGroup)
  113. controllerWaitGroup.Add(1)
  114. go func() {
  115. defer controllerWaitGroup.Done()
  116. controller.Run(controllerCtx)
  117. }()
  118. return nil
  119. }
  120. func Stop() {
  121. controllerMutex.Lock()
  122. defer controllerMutex.Unlock()
  123. if controller != nil {
  124. stopController()
  125. controllerWaitGroup.Wait()
  126. controller = nil
  127. controllerCtx = nil
  128. stopController = nil
  129. controllerWaitGroup = nil
  130. }
  131. }
  132. func ReconnectTunnel() {
  133. controllerMutex.Lock()
  134. defer controllerMutex.Unlock()
  135. if controller != nil {
  136. // TODO: ensure TerminateNextActiveTunnel is safe for use (see godoc)
  137. controller.TerminateNextActiveTunnel()
  138. }
  139. }
  140. // SetClientVerificationPayload is a passthrough to
  141. // Controller.SetClientVerificationPayloadForActiveTunnels.
  142. // Note: should only be called after Start() and before Stop(); otherwise,
  143. // will silently take no action.
  144. func SetClientVerificationPayload(clientVerificationPayload string) {
  145. controllerMutex.Lock()
  146. defer controllerMutex.Unlock()
  147. if controller != nil {
  148. controller.SetClientVerificationPayloadForActiveTunnels(clientVerificationPayload)
  149. }
  150. }
  151. // Encrypt and upload feedback.
  152. func SendFeedback(configJson, diagnosticsJson, b64EncodedPublicKey, uploadServer, uploadPath, uploadServerHeaders string) error {
  153. return psiphon.SendFeedback(configJson, diagnosticsJson, b64EncodedPublicKey, uploadServer, uploadPath, uploadServerHeaders)
  154. }
  155. // Get build info from tunnel-core
  156. func GetBuildInfo() string {
  157. buildInfo, err := json.Marshal(common.GetBuildInfo())
  158. if err != nil {
  159. return ""
  160. }
  161. return string(buildInfo)
  162. }
  163. func GetPacketTunnelMTU() int {
  164. return tun.DEFAULT_MTU
  165. }
  166. func GetPacketTunnelDNSResolverIPv4Address() string {
  167. return tun.GetTransparentDNSResolverIPv4Address().String()
  168. }
  169. func GetPacketTunnelDNSResolverIPv6Address() string {
  170. return tun.GetTransparentDNSResolverIPv6Address().String()
  171. }
  172. // Helper function to store a list of server entries.
  173. // if embeddedServerEntryListFilename is not empty, embeddedServerEntryList will be ignored.
  174. func storeServerEntries(embeddedServerEntryListFilename, embeddedServerEntryList string) error {
  175. if embeddedServerEntryListFilename != "" {
  176. file, err := os.Open(embeddedServerEntryListFilename)
  177. if err != nil {
  178. return fmt.Errorf("error reading embedded server list file: %s", common.ContextError(err))
  179. }
  180. defer file.Close()
  181. err = psiphon.StreamingStoreServerEntries(
  182. protocol.NewStreamingServerEntryDecoder(
  183. file,
  184. common.GetCurrentTimestamp(),
  185. protocol.SERVER_ENTRY_SOURCE_EMBEDDED),
  186. false)
  187. if err != nil {
  188. return fmt.Errorf("error storing embedded server list: %s", common.ContextError(err))
  189. }
  190. } else {
  191. serverEntries, err := protocol.DecodeServerEntryList(
  192. embeddedServerEntryList,
  193. common.GetCurrentTimestamp(),
  194. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  195. if err != nil {
  196. return fmt.Errorf("error decoding embedded server list: %s", err)
  197. }
  198. err = psiphon.StoreServerEntries(serverEntries, false)
  199. if err != nil {
  200. return fmt.Errorf("error storing embedded server list: %s", err)
  201. }
  202. }
  203. return nil
  204. }
  205. type mutexPsiphonProvider struct {
  206. sync.Mutex
  207. p PsiphonProvider
  208. }
  209. func newMutexPsiphonProvider(p PsiphonProvider) *mutexPsiphonProvider {
  210. return &mutexPsiphonProvider{p: p}
  211. }
  212. func (p *mutexPsiphonProvider) Notice(noticeJSON string) {
  213. p.Lock()
  214. defer p.Unlock()
  215. p.p.Notice(noticeJSON)
  216. }
  217. func (p *mutexPsiphonProvider) HasNetworkConnectivity() int {
  218. p.Lock()
  219. defer p.Unlock()
  220. return p.p.HasNetworkConnectivity()
  221. }
  222. func (p *mutexPsiphonProvider) BindToDevice(fileDescriptor int) (string, error) {
  223. p.Lock()
  224. defer p.Unlock()
  225. return p.p.BindToDevice(fileDescriptor)
  226. }
  227. func (p *mutexPsiphonProvider) IPv6Synthesize(IPv4Addr string) string {
  228. p.Lock()
  229. defer p.Unlock()
  230. return p.p.IPv6Synthesize(IPv4Addr)
  231. }
  232. func (p *mutexPsiphonProvider) GetPrimaryDnsServer() string {
  233. p.Lock()
  234. defer p.Unlock()
  235. return p.p.GetPrimaryDnsServer()
  236. }
  237. func (p *mutexPsiphonProvider) GetSecondaryDnsServer() string {
  238. p.Lock()
  239. defer p.Unlock()
  240. return p.p.GetSecondaryDnsServer()
  241. }
  242. type loggingDeviceBinder struct {
  243. p PsiphonProvider
  244. }
  245. func newLoggingDeviceBinder(p PsiphonProvider) *loggingDeviceBinder {
  246. return &loggingDeviceBinder{p: p}
  247. }
  248. func (d *loggingDeviceBinder) BindToDevice(fileDescriptor int) error {
  249. deviceInfo, err := d.p.BindToDevice(fileDescriptor)
  250. if err == nil && deviceInfo != "" {
  251. psiphon.NoticeInfo("BindToDevice: %s", deviceInfo)
  252. }
  253. return err
  254. }