psi.go 7.3 KB

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