psi.go 17 KB

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