psi.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. // As 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.OpenDataStore(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. psiphon.CloseDataStore()
  146. controller = nil
  147. controllerCtx = nil
  148. stopController = nil
  149. controllerWaitGroup = nil
  150. }
  151. }
  152. // ReconnectTunnel initiates a reconnect of the current tunnel, if one is
  153. // running.
  154. func ReconnectTunnel() {
  155. controllerMutex.Lock()
  156. defer controllerMutex.Unlock()
  157. if controller != nil {
  158. controller.TerminateNextActiveTunnel()
  159. }
  160. }
  161. // SetDynamicConfig overrides the sponsor ID and authorizations fields set in
  162. // the config passed to Start. SetDynamicConfig has no effect if no Controller
  163. // is started.
  164. //
  165. // The input newAuthorizationsList is a space-delimited list of base64
  166. // authorizations. This is a workaround for gobind type limitations.
  167. func SetDynamicConfig(newSponsorID, newAuthorizationsList string) {
  168. controllerMutex.Lock()
  169. defer controllerMutex.Unlock()
  170. if controller != nil {
  171. controller.SetDynamicConfig(
  172. newSponsorID,
  173. strings.Split(newAuthorizationsList, " "))
  174. }
  175. }
  176. // Encrypt and upload feedback.
  177. func SendFeedback(configJson, diagnosticsJson, b64EncodedPublicKey, uploadServer, uploadPath, uploadServerHeaders string) error {
  178. return psiphon.SendFeedback(configJson, diagnosticsJson, b64EncodedPublicKey, uploadServer, uploadPath, uploadServerHeaders)
  179. }
  180. // Get build info from tunnel-core
  181. func GetBuildInfo() string {
  182. buildInfo, err := json.Marshal(common.GetBuildInfo())
  183. if err != nil {
  184. return ""
  185. }
  186. return string(buildInfo)
  187. }
  188. func GetPacketTunnelMTU() int {
  189. return tun.DEFAULT_MTU
  190. }
  191. func GetPacketTunnelDNSResolverIPv4Address() string {
  192. return tun.GetTransparentDNSResolverIPv4Address().String()
  193. }
  194. func GetPacketTunnelDNSResolverIPv6Address() string {
  195. return tun.GetTransparentDNSResolverIPv6Address().String()
  196. }
  197. // WriteRuntimeProfiles writes Go runtime profile information to a set of
  198. // files in the specified output directory. See common.WriteRuntimeProfiles
  199. // for more details.
  200. //
  201. // If called before Start, log notices will emit to stderr.
  202. func WriteRuntimeProfiles(outputDirectory string, cpuSampleDurationSeconds, blockSampleDurationSeconds int) {
  203. common.WriteRuntimeProfiles(
  204. psiphon.NoticeCommonLogger(),
  205. outputDirectory,
  206. cpuSampleDurationSeconds,
  207. blockSampleDurationSeconds)
  208. }
  209. // Helper function to store a list of server entries.
  210. // if embeddedServerEntryListFilename is not empty, embeddedServerEntryList will be ignored.
  211. func storeServerEntries(
  212. config *psiphon.Config,
  213. embeddedServerEntryListFilename, embeddedServerEntryList string) error {
  214. if embeddedServerEntryListFilename != "" {
  215. file, err := os.Open(embeddedServerEntryListFilename)
  216. if err != nil {
  217. return fmt.Errorf("error reading embedded server list file: %s", common.ContextError(err))
  218. }
  219. defer file.Close()
  220. err = psiphon.StreamingStoreServerEntries(
  221. config,
  222. protocol.NewStreamingServerEntryDecoder(
  223. file,
  224. common.GetCurrentTimestamp(),
  225. protocol.SERVER_ENTRY_SOURCE_EMBEDDED),
  226. false)
  227. if err != nil {
  228. return fmt.Errorf("error storing embedded server list: %s", common.ContextError(err))
  229. }
  230. } else {
  231. serverEntries, err := protocol.DecodeServerEntryList(
  232. embeddedServerEntryList,
  233. common.GetCurrentTimestamp(),
  234. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  235. if err != nil {
  236. return fmt.Errorf("error decoding embedded server list: %s", err)
  237. }
  238. err = psiphon.StoreServerEntries(config, serverEntries, false)
  239. if err != nil {
  240. return fmt.Errorf("error storing embedded server list: %s", err)
  241. }
  242. }
  243. return nil
  244. }
  245. type mutexPsiphonProvider struct {
  246. sync.Mutex
  247. p PsiphonProvider
  248. }
  249. func newMutexPsiphonProvider(p PsiphonProvider) *mutexPsiphonProvider {
  250. return &mutexPsiphonProvider{p: p}
  251. }
  252. func (p *mutexPsiphonProvider) Notice(noticeJSON string) {
  253. p.Lock()
  254. defer p.Unlock()
  255. p.p.Notice(noticeJSON)
  256. }
  257. func (p *mutexPsiphonProvider) HasNetworkConnectivity() int {
  258. p.Lock()
  259. defer p.Unlock()
  260. return p.p.HasNetworkConnectivity()
  261. }
  262. func (p *mutexPsiphonProvider) BindToDevice(fileDescriptor int) (string, error) {
  263. p.Lock()
  264. defer p.Unlock()
  265. return p.p.BindToDevice(fileDescriptor)
  266. }
  267. func (p *mutexPsiphonProvider) IPv6Synthesize(IPv4Addr string) string {
  268. p.Lock()
  269. defer p.Unlock()
  270. return p.p.IPv6Synthesize(IPv4Addr)
  271. }
  272. func (p *mutexPsiphonProvider) GetPrimaryDnsServer() string {
  273. p.Lock()
  274. defer p.Unlock()
  275. return p.p.GetPrimaryDnsServer()
  276. }
  277. func (p *mutexPsiphonProvider) GetSecondaryDnsServer() string {
  278. p.Lock()
  279. defer p.Unlock()
  280. return p.p.GetSecondaryDnsServer()
  281. }
  282. func (p *mutexPsiphonProvider) GetNetworkID() string {
  283. p.Lock()
  284. defer p.Unlock()
  285. return p.p.GetNetworkID()
  286. }