psi.go 8.7 KB

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