psi.go 18 KB

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