psi.go 8.5 KB

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