psi.go 8.7 KB

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