psi.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. // Allow the provider to be garbage collected.
  225. psiphon.SetNoticeWriter(os.Stderr)
  226. }
  227. }
  228. // ReconnectTunnel initiates a reconnect of the current tunnel, if one is
  229. // running.
  230. func ReconnectTunnel() {
  231. controllerMutex.Lock()
  232. defer controllerMutex.Unlock()
  233. if controller != nil {
  234. controller.TerminateNextActiveTunnel()
  235. }
  236. }
  237. // SetDynamicConfig overrides the sponsor ID and authorizations fields set in
  238. // the config passed to Start. SetDynamicConfig has no effect if no Controller
  239. // is started.
  240. //
  241. // The input newAuthorizationsList is a space-delimited list of base64
  242. // authorizations. This is a workaround for gobind type limitations.
  243. func SetDynamicConfig(newSponsorID, newAuthorizationsList string) {
  244. controllerMutex.Lock()
  245. defer controllerMutex.Unlock()
  246. if controller != nil {
  247. var authorizations []string
  248. if len(newAuthorizationsList) > 0 {
  249. authorizations = strings.Split(newAuthorizationsList, " ")
  250. }
  251. controller.SetDynamicConfig(
  252. newSponsorID,
  253. authorizations)
  254. }
  255. }
  256. // ExportExchangePayload creates a payload for client-to-client server
  257. // connection info exchange.
  258. //
  259. // ExportExchangePayload will succeed only when Psiphon is running, between
  260. // Start and Stop.
  261. //
  262. // The return value is a payload that may be exchanged with another client;
  263. // when "", the export failed and a diagnostic has been logged.
  264. func ExportExchangePayload() string {
  265. controllerMutex.Lock()
  266. defer controllerMutex.Unlock()
  267. if controller == nil {
  268. return ""
  269. }
  270. return controller.ExportExchangePayload()
  271. }
  272. // ImportExchangePayload imports a payload generated by ExportExchangePayload.
  273. //
  274. // If an import occurs when Psiphon is working to establsh a tunnel, the newly
  275. // imported server entry is prioritized.
  276. //
  277. // The return value indicates a successful import. If the import failed, a a
  278. // diagnostic notice has been logged.
  279. func ImportExchangePayload(payload string) bool {
  280. controllerMutex.Lock()
  281. defer controllerMutex.Unlock()
  282. if controller == nil {
  283. return false
  284. }
  285. return controller.ImportExchangePayload(payload)
  286. }
  287. var sendFeedbackMutex sync.Mutex
  288. var sendFeedbackCtx context.Context
  289. var stopSendFeedback context.CancelFunc
  290. var sendFeedbackWaitGroup *sync.WaitGroup
  291. // StartSendFeedback encrypts the provided diagnostics and then attempts to
  292. // upload the encrypted diagnostics to one of the feedback upload locations
  293. // supplied by the provided config or tactics.
  294. //
  295. // Returns immediately after starting the operation in a goroutine. The
  296. // operation has completed when SendFeedbackCompleted(error) is called on the
  297. // provided PsiphonProviderFeedbackHandler; if error is non-nil, then the
  298. // operation failed.
  299. //
  300. // Only one active upload is supported at a time. An ongoing upload will be
  301. // cancelled if this function is called again before it completes.
  302. //
  303. // Warnings:
  304. // - Should not be used with Start concurrently in the same process
  305. // - An ongoing feedback upload started with StartSendFeedback should be
  306. // stopped with StopSendFeedback before the process exists. This ensures that
  307. // any underlying resources are cleaned up; failing to do so may result in
  308. // data store corruption or other undefined behavior.
  309. // - Start and StartSendFeedback both make an attempt to migrate persistent
  310. // files from legacy locations in a one-time operation. If these functions
  311. // are called in parallel, then there is a chance that the migration attempts
  312. // could execute at the same time and result in non-fatal errors in one, or
  313. // both, of the migration operations.
  314. // - Calling StartSendFeedback or StopSendFeedback on the same call stack
  315. // that the PsiphonProviderFeedbackHandler.SendFeedbackCompleted() callback
  316. // is delivered on can cause a deadlock. I.E. the callback code must return
  317. // so the wait group can complete and the lock acquired in StopSendFeedback
  318. // can be released.
  319. func StartSendFeedback(
  320. configJson,
  321. diagnosticsJson,
  322. uploadPath string,
  323. feedbackHandler PsiphonProviderFeedbackHandler,
  324. networkInfoProvider PsiphonProviderNetwork,
  325. noticeHandler PsiphonProviderNoticeHandler,
  326. useIPv6Synthesizer bool,
  327. useHasIPv6RouteGetter bool) error {
  328. // Cancel any ongoing uploads.
  329. StopSendFeedback()
  330. sendFeedbackMutex.Lock()
  331. defer sendFeedbackMutex.Unlock()
  332. sendFeedbackCtx, stopSendFeedback = context.WithCancel(context.Background())
  333. // Unlike in Start, the provider is not wrapped in a newMutexPsiphonProvider
  334. // or equivilent, as SendFeedback is not expected to be used in a memory
  335. // constrained environment.
  336. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  337. func(notice []byte) {
  338. noticeHandler.Notice(string(notice))
  339. }))
  340. config, err := psiphon.LoadConfig([]byte(configJson))
  341. if err != nil {
  342. return fmt.Errorf("error loading configuration file: %s", err)
  343. }
  344. // Set up callbacks.
  345. config.NetworkConnectivityChecker = networkInfoProvider
  346. config.NetworkIDGetter = networkInfoProvider
  347. if useIPv6Synthesizer {
  348. config.IPv6Synthesizer = networkInfoProvider
  349. }
  350. if useHasIPv6RouteGetter {
  351. config.HasIPv6RouteGetter = networkInfoProvider
  352. }
  353. // Limitation: config.DNSServerGetter is not set up in the SendFeedback
  354. // case, as we don't currently implement network path and system DNS
  355. // server monitoring for SendFeedback in the platform code. To ensure we
  356. // fallback to the system resolver and don't always use the custom
  357. // resolver with alternate DNS servers, clear that config field (this may
  358. // still be set via tactics).
  359. config.DNSResolverAlternateServers = nil
  360. // All config fields should be set before calling Commit.
  361. err = config.Commit(true)
  362. if err != nil {
  363. return fmt.Errorf("error committing configuration file: %s", err)
  364. }
  365. sendFeedbackWaitGroup = new(sync.WaitGroup)
  366. sendFeedbackWaitGroup.Add(1)
  367. go func() {
  368. defer sendFeedbackWaitGroup.Done()
  369. err := psiphon.SendFeedback(sendFeedbackCtx, config,
  370. diagnosticsJson, uploadPath)
  371. feedbackHandler.SendFeedbackCompleted(err)
  372. }()
  373. return nil
  374. }
  375. // StopSendFeedback interrupts an in-progress feedback upload operation
  376. // started with `StartSendFeedback`.
  377. //
  378. // Warning: should not be used with Start concurrently in the same process.
  379. func StopSendFeedback() {
  380. sendFeedbackMutex.Lock()
  381. defer sendFeedbackMutex.Unlock()
  382. if stopSendFeedback != nil {
  383. stopSendFeedback()
  384. sendFeedbackWaitGroup.Wait()
  385. sendFeedbackCtx = nil
  386. stopSendFeedback = nil
  387. sendFeedbackWaitGroup = nil
  388. // Allow the notice handler to be garbage collected.
  389. psiphon.SetNoticeWriter(os.Stderr)
  390. }
  391. }
  392. // Get build info from tunnel-core
  393. func GetBuildInfo() string {
  394. buildInfo, err := json.Marshal(buildinfo.GetBuildInfo())
  395. if err != nil {
  396. return ""
  397. }
  398. return string(buildInfo)
  399. }
  400. func GetPacketTunnelMTU() int {
  401. return tun.DEFAULT_MTU
  402. }
  403. func GetPacketTunnelDNSResolverIPv4Address() string {
  404. return tun.GetTransparentDNSResolverIPv4Address().String()
  405. }
  406. func GetPacketTunnelDNSResolverIPv6Address() string {
  407. return tun.GetTransparentDNSResolverIPv6Address().String()
  408. }
  409. // WriteRuntimeProfiles writes Go runtime profile information to a set of
  410. // files in the specified output directory. See common.WriteRuntimeProfiles
  411. // for more details.
  412. //
  413. // If called before Start, log notices will emit to stderr.
  414. func WriteRuntimeProfiles(outputDirectory string, cpuSampleDurationSeconds, blockSampleDurationSeconds int) {
  415. common.WriteRuntimeProfiles(
  416. psiphon.NoticeCommonLogger(),
  417. outputDirectory,
  418. "",
  419. cpuSampleDurationSeconds,
  420. blockSampleDurationSeconds)
  421. }
  422. type mutexPsiphonProvider struct {
  423. sync.Mutex
  424. p PsiphonProvider
  425. }
  426. func newMutexPsiphonProvider(p PsiphonProvider) *mutexPsiphonProvider {
  427. return &mutexPsiphonProvider{p: p}
  428. }
  429. func (p *mutexPsiphonProvider) Notice(noticeJSON string) {
  430. p.Lock()
  431. defer p.Unlock()
  432. p.p.Notice(noticeJSON)
  433. }
  434. func (p *mutexPsiphonProvider) HasNetworkConnectivity() int {
  435. p.Lock()
  436. defer p.Unlock()
  437. return p.p.HasNetworkConnectivity()
  438. }
  439. func (p *mutexPsiphonProvider) BindToDevice(fileDescriptor int) (string, error) {
  440. p.Lock()
  441. defer p.Unlock()
  442. return p.p.BindToDevice(fileDescriptor)
  443. }
  444. func (p *mutexPsiphonProvider) IPv6Synthesize(IPv4Addr string) string {
  445. p.Lock()
  446. defer p.Unlock()
  447. return p.p.IPv6Synthesize(IPv4Addr)
  448. }
  449. func (p *mutexPsiphonProvider) HasIPv6Route() int {
  450. p.Lock()
  451. defer p.Unlock()
  452. return p.p.HasIPv6Route()
  453. }
  454. func (p *mutexPsiphonProvider) GetDNSServersAsString() string {
  455. p.Lock()
  456. defer p.Unlock()
  457. return p.p.GetDNSServersAsString()
  458. }
  459. func (p *mutexPsiphonProvider) GetDNSServers() []string {
  460. p.Lock()
  461. defer p.Unlock()
  462. s := p.p.GetDNSServersAsString()
  463. if s == "" {
  464. return []string{}
  465. }
  466. return strings.Split(s, ",")
  467. }
  468. func (p *mutexPsiphonProvider) GetNetworkID() string {
  469. p.Lock()
  470. defer p.Unlock()
  471. return p.p.GetNetworkID()
  472. }