psi.go 8.2 KB

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