psi.go 10 KB

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