psi.go 17 KB

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