psi.go 8.0 KB

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