psi.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. "path/filepath"
  30. "strings"
  31. "sync"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/buildinfo"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  37. )
  38. type PsiphonProviderNoticeHandler interface {
  39. Notice(noticeJSON string)
  40. }
  41. type PsiphonProvider interface {
  42. PsiphonProviderNoticeHandler
  43. HasNetworkConnectivity() int
  44. BindToDevice(fileDescriptor int) (string, error)
  45. IPv6Synthesize(IPv4Addr string) string
  46. GetPrimaryDnsServer() string
  47. GetSecondaryDnsServer() string
  48. GetNetworkID() string
  49. }
  50. type PsiphonProviderFeedbackHandler interface {
  51. SendFeedbackCompleted(err error)
  52. }
  53. func NoticeUserLog(message string) {
  54. psiphon.NoticeUserLog(message)
  55. }
  56. // HomepageFilePath returns the path where homepage files will be paved.
  57. //
  58. // rootDataDirectoryPath is the configured data root directory.
  59. //
  60. // Note: homepage files will only be paved if UseNoticeFiles is set in the
  61. // config passed to Start().
  62. func HomepageFilePath(rootDataDirectoryPath string) string {
  63. return filepath.Join(rootDataDirectoryPath, psiphon.PsiphonDataDirectoryName, psiphon.HomepageFilename)
  64. }
  65. // NoticesFilePath returns the path where the notices file will be paved.
  66. //
  67. // rootDataDirectoryPath is the configured data root directory.
  68. //
  69. // Note: notices will only be paved if UseNoticeFiles is set in the config
  70. // passed to Start().
  71. func NoticesFilePath(rootDataDirectoryPath string) string {
  72. return filepath.Join(rootDataDirectoryPath, psiphon.PsiphonDataDirectoryName, psiphon.NoticesFilename)
  73. }
  74. // OldNoticesFilePath returns the path where the notices file is moved to when
  75. // file rotation occurs.
  76. //
  77. // rootDataDirectoryPath is the configured data root directory.
  78. //
  79. // Note: notices will only be paved if UseNoticeFiles is set in the config
  80. // passed to Start().
  81. func OldNoticesFilePath(rootDataDirectoryPath string) string {
  82. return filepath.Join(rootDataDirectoryPath, psiphon.PsiphonDataDirectoryName, psiphon.OldNoticesFilename)
  83. }
  84. // UpgradeDownloadFilePath returns the path where the downloaded upgrade file
  85. // will be paved.
  86. //
  87. // rootDataDirectoryPath is the configured data root directory.
  88. //
  89. // Note: upgrades will only be paved if UpgradeDownloadURLs is set in the config
  90. // passed to Start() and there are upgrades available.
  91. func UpgradeDownloadFilePath(rootDataDirectoryPath string) string {
  92. return filepath.Join(rootDataDirectoryPath, psiphon.PsiphonDataDirectoryName, psiphon.UpgradeDownloadFilename)
  93. }
  94. var controllerMutex sync.Mutex
  95. var controller *psiphon.Controller
  96. var controllerCtx context.Context
  97. var stopController context.CancelFunc
  98. var controllerWaitGroup *sync.WaitGroup
  99. func Start(
  100. configJson,
  101. embeddedServerEntryList,
  102. embeddedServerEntryListFilename string,
  103. provider PsiphonProvider,
  104. useDeviceBinder,
  105. useIPv6Synthesizer bool) error {
  106. controllerMutex.Lock()
  107. defer controllerMutex.Unlock()
  108. if controller != nil {
  109. return fmt.Errorf("already started")
  110. }
  111. // Clients may toggle Stop/Start immediately to apply new config settings
  112. // such as EgressRegion or Authorizations. When this restart is within the
  113. // same process and in a memory contrained environment, it is useful to
  114. // force garbage collection here to reclaim memory used by the previous
  115. // Controller.
  116. psiphon.DoGarbageCollection()
  117. // Wrap the provider in a layer that locks a mutex before calling a provider function.
  118. // As the provider callbacks are Java/Obj-C via gomobile, they are cgo calls that
  119. // can cause OS threads to be spawned. The mutex prevents many calling goroutines from
  120. // causing unbounded numbers of OS threads to be spawned.
  121. // TODO: replace the mutex with a semaphore, to allow a larger but still bounded concurrent
  122. // number of calls to the provider?
  123. provider = newMutexPsiphonProvider(provider)
  124. config, err := psiphon.LoadConfig([]byte(configJson))
  125. if err != nil {
  126. return fmt.Errorf("error loading configuration file: %s", err)
  127. }
  128. config.NetworkConnectivityChecker = provider
  129. config.NetworkIDGetter = provider
  130. if useDeviceBinder {
  131. config.DeviceBinder = provider
  132. config.DnsServerGetter = provider
  133. }
  134. if useIPv6Synthesizer {
  135. config.IPv6Synthesizer = provider
  136. }
  137. // All config fields should be set before calling Commit.
  138. err = config.Commit(true)
  139. if err != nil {
  140. return fmt.Errorf("error committing configuration file: %s", err)
  141. }
  142. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  143. func(notice []byte) {
  144. provider.Notice(string(notice))
  145. }))
  146. // BuildInfo is a diagnostic notice, so emit only after config.Commit
  147. // sets EmitDiagnosticNotices.
  148. psiphon.NoticeBuildInfo()
  149. err = psiphon.OpenDataStore(config)
  150. if err != nil {
  151. return fmt.Errorf("error initializing datastore: %s", err)
  152. }
  153. // Stores list of server entries.
  154. err = storeServerEntries(
  155. config,
  156. embeddedServerEntryListFilename,
  157. embeddedServerEntryList)
  158. if err != nil {
  159. return err
  160. }
  161. controller, err = psiphon.NewController(config)
  162. if err != nil {
  163. psiphon.CloseDataStore()
  164. return fmt.Errorf("error initializing controller: %s", err)
  165. }
  166. controllerCtx, stopController = context.WithCancel(context.Background())
  167. controllerWaitGroup = new(sync.WaitGroup)
  168. controllerWaitGroup.Add(1)
  169. go func() {
  170. defer controllerWaitGroup.Done()
  171. controller.Run(controllerCtx)
  172. }()
  173. return nil
  174. }
  175. func Stop() {
  176. controllerMutex.Lock()
  177. defer controllerMutex.Unlock()
  178. if controller != nil {
  179. stopController()
  180. controllerWaitGroup.Wait()
  181. psiphon.CloseDataStore()
  182. controller = nil
  183. controllerCtx = nil
  184. stopController = nil
  185. controllerWaitGroup = nil
  186. }
  187. }
  188. // ReconnectTunnel initiates a reconnect of the current tunnel, if one is
  189. // running.
  190. func ReconnectTunnel() {
  191. controllerMutex.Lock()
  192. defer controllerMutex.Unlock()
  193. if controller != nil {
  194. controller.TerminateNextActiveTunnel()
  195. }
  196. }
  197. // SetDynamicConfig overrides the sponsor ID and authorizations fields set in
  198. // the config passed to Start. SetDynamicConfig has no effect if no Controller
  199. // is started.
  200. //
  201. // The input newAuthorizationsList is a space-delimited list of base64
  202. // authorizations. This is a workaround for gobind type limitations.
  203. func SetDynamicConfig(newSponsorID, newAuthorizationsList string) {
  204. controllerMutex.Lock()
  205. defer controllerMutex.Unlock()
  206. if controller != nil {
  207. var authorizations []string
  208. if len(newAuthorizationsList) > 0 {
  209. authorizations = strings.Split(newAuthorizationsList, " ")
  210. }
  211. controller.SetDynamicConfig(
  212. newSponsorID,
  213. authorizations)
  214. }
  215. }
  216. // ExportExchangePayload creates a payload for client-to-client server
  217. // connection info exchange.
  218. //
  219. // ExportExchangePayload will succeed only when Psiphon is running, between
  220. // Start and Stop.
  221. //
  222. // The return value is a payload that may be exchanged with another client;
  223. // when "", the export failed and a diagnostic has been logged.
  224. func ExportExchangePayload() string {
  225. controllerMutex.Lock()
  226. defer controllerMutex.Unlock()
  227. if controller == nil {
  228. return ""
  229. }
  230. return controller.ExportExchangePayload()
  231. }
  232. // ImportExchangePayload imports a payload generated by ExportExchangePayload.
  233. //
  234. // If an import occurs when Psiphon is working to establsh a tunnel, the newly
  235. // imported server entry is prioritized.
  236. //
  237. // The return value indicates a successful import. If the import failed, a a
  238. // diagnostic notice has been logged.
  239. func ImportExchangePayload(payload string) bool {
  240. controllerMutex.Lock()
  241. defer controllerMutex.Unlock()
  242. if controller == nil {
  243. return false
  244. }
  245. return controller.ImportExchangePayload(payload)
  246. }
  247. var sendFeedbackMutex sync.Mutex
  248. var sendFeedbackCtx context.Context
  249. var stopSendFeedback context.CancelFunc
  250. var sendFeedbackWaitGroup *sync.WaitGroup
  251. // StartSendFeedback encrypts the provided diagnostics and then attempts to
  252. // upload the encrypted diagnostics to one of the feedback upload locations
  253. // supplied by the provided config or tactics.
  254. //
  255. // Returns immediately after starting the operation in a goroutine. The
  256. // operation has completed when SendFeedbackCompleted(error) is called on the
  257. // provided PsiphonProviderFeedbackHandler; if error is non-nil, then the
  258. // operation failed.
  259. //
  260. // Only one active upload is supported at a time. An ongoing upload will be
  261. // cancelled if this function is called again before it completes.
  262. //
  263. // Warnings:
  264. // - Should not be used with Start concurrently in the same process
  265. // - An ongoing feedback upload started with StartSendFeedback should be
  266. // stopped with StopSendFeedback before the process exists. This ensures that
  267. // any underlying resources are cleaned up; failing to do so may result in
  268. // data store corruption or other undefined behavior.
  269. // - Start and StartSendFeedback both make an attempt to migrate persistent
  270. // files from legacy locations in a one-time operation. If these functions
  271. // are called in parallel, then there is a chance that the migration attempts
  272. // could execute at the same time and result in non-fatal errors in one, or
  273. // both, of the migration operations.
  274. // - Calling StartSendFeedback or StopSendFeedback on the same call stack
  275. // that the PsiphonProviderFeedbackHandler.SendFeedbackCompleted() callback
  276. // is delivered on can cause a deadlock. I.E. the callback code must return
  277. // so the wait group can complete and the lock acquired in StopSendFeedback
  278. // can be released.
  279. func StartSendFeedback(
  280. configJson,
  281. diagnosticsJson,
  282. uploadPath string,
  283. feedbackHandler PsiphonProviderFeedbackHandler,
  284. noticeHandler PsiphonProviderNoticeHandler) {
  285. // Cancel any ongoing uploads.
  286. StopSendFeedback()
  287. sendFeedbackMutex.Lock()
  288. defer sendFeedbackMutex.Unlock()
  289. sendFeedbackCtx, stopSendFeedback = context.WithCancel(context.Background())
  290. // Unlike in Start, the provider is not wrapped in a newMutexPsiphonProvider
  291. // or equivilent, as SendFeedback is not expected to be used in a memory
  292. // constrained environment.
  293. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  294. func(notice []byte) {
  295. noticeHandler.Notice(string(notice))
  296. }))
  297. sendFeedbackWaitGroup = new(sync.WaitGroup)
  298. sendFeedbackWaitGroup.Add(1)
  299. go func() {
  300. defer sendFeedbackWaitGroup.Done()
  301. err := psiphon.SendFeedback(sendFeedbackCtx, configJson, diagnosticsJson, uploadPath)
  302. feedbackHandler.SendFeedbackCompleted(err)
  303. }()
  304. }
  305. // StopSendFeedback interrupts an in-progress feedback upload operation
  306. // started with `StartSendFeedback`.
  307. //
  308. // Warning: should not be used with Start concurrently in the same process.
  309. func StopSendFeedback() {
  310. sendFeedbackMutex.Lock()
  311. defer sendFeedbackMutex.Unlock()
  312. if stopSendFeedback != nil {
  313. stopSendFeedback()
  314. sendFeedbackWaitGroup.Wait()
  315. sendFeedbackCtx = nil
  316. stopSendFeedback = nil
  317. sendFeedbackWaitGroup = nil
  318. // Allow the notice receiver to be deallocated.
  319. psiphon.SetNoticeWriter(os.Stderr)
  320. }
  321. }
  322. // Get build info from tunnel-core
  323. func GetBuildInfo() string {
  324. buildInfo, err := json.Marshal(buildinfo.GetBuildInfo())
  325. if err != nil {
  326. return ""
  327. }
  328. return string(buildInfo)
  329. }
  330. func GetPacketTunnelMTU() int {
  331. return tun.DEFAULT_MTU
  332. }
  333. func GetPacketTunnelDNSResolverIPv4Address() string {
  334. return tun.GetTransparentDNSResolverIPv4Address().String()
  335. }
  336. func GetPacketTunnelDNSResolverIPv6Address() string {
  337. return tun.GetTransparentDNSResolverIPv6Address().String()
  338. }
  339. // WriteRuntimeProfiles writes Go runtime profile information to a set of
  340. // files in the specified output directory. See common.WriteRuntimeProfiles
  341. // for more details.
  342. //
  343. // If called before Start, log notices will emit to stderr.
  344. func WriteRuntimeProfiles(outputDirectory string, cpuSampleDurationSeconds, blockSampleDurationSeconds int) {
  345. common.WriteRuntimeProfiles(
  346. psiphon.NoticeCommonLogger(),
  347. outputDirectory,
  348. "",
  349. cpuSampleDurationSeconds,
  350. blockSampleDurationSeconds)
  351. }
  352. // Helper function to store a list of server entries.
  353. // if embeddedServerEntryListFilename is not empty, embeddedServerEntryList will be ignored.
  354. func storeServerEntries(
  355. config *psiphon.Config,
  356. embeddedServerEntryListFilename, embeddedServerEntryList string) error {
  357. if embeddedServerEntryListFilename != "" {
  358. file, err := os.Open(embeddedServerEntryListFilename)
  359. if err != nil {
  360. return fmt.Errorf("error reading embedded server list file: %s", err)
  361. }
  362. defer file.Close()
  363. err = psiphon.StreamingStoreServerEntries(
  364. config,
  365. protocol.NewStreamingServerEntryDecoder(
  366. file,
  367. common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  368. protocol.SERVER_ENTRY_SOURCE_EMBEDDED),
  369. false)
  370. if err != nil {
  371. return fmt.Errorf("error storing embedded server list: %s", err)
  372. }
  373. } else {
  374. serverEntries, err := protocol.DecodeServerEntryList(
  375. embeddedServerEntryList,
  376. common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  377. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  378. if err != nil {
  379. return fmt.Errorf("error decoding embedded server list: %s", err)
  380. }
  381. err = psiphon.StoreServerEntries(config, serverEntries, false)
  382. if err != nil {
  383. return fmt.Errorf("error storing embedded server list: %s", err)
  384. }
  385. }
  386. return nil
  387. }
  388. type mutexPsiphonProvider struct {
  389. sync.Mutex
  390. p PsiphonProvider
  391. }
  392. func newMutexPsiphonProvider(p PsiphonProvider) *mutexPsiphonProvider {
  393. return &mutexPsiphonProvider{p: p}
  394. }
  395. func (p *mutexPsiphonProvider) Notice(noticeJSON string) {
  396. p.Lock()
  397. defer p.Unlock()
  398. p.p.Notice(noticeJSON)
  399. }
  400. func (p *mutexPsiphonProvider) HasNetworkConnectivity() int {
  401. p.Lock()
  402. defer p.Unlock()
  403. return p.p.HasNetworkConnectivity()
  404. }
  405. func (p *mutexPsiphonProvider) BindToDevice(fileDescriptor int) (string, error) {
  406. p.Lock()
  407. defer p.Unlock()
  408. return p.p.BindToDevice(fileDescriptor)
  409. }
  410. func (p *mutexPsiphonProvider) IPv6Synthesize(IPv4Addr string) string {
  411. p.Lock()
  412. defer p.Unlock()
  413. return p.p.IPv6Synthesize(IPv4Addr)
  414. }
  415. func (p *mutexPsiphonProvider) GetPrimaryDnsServer() string {
  416. p.Lock()
  417. defer p.Unlock()
  418. return p.p.GetPrimaryDnsServer()
  419. }
  420. func (p *mutexPsiphonProvider) GetSecondaryDnsServer() string {
  421. p.Lock()
  422. defer p.Unlock()
  423. return p.p.GetSecondaryDnsServer()
  424. }
  425. func (p *mutexPsiphonProvider) GetNetworkID() string {
  426. p.Lock()
  427. defer p.Unlock()
  428. return p.p.GetNetworkID()
  429. }