psi.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 PsiphonProvider interface {
  39. Notice(noticeJSON string)
  40. HasNetworkConnectivity() int
  41. BindToDevice(fileDescriptor int) (string, error)
  42. IPv6Synthesize(IPv4Addr string) string
  43. GetPrimaryDnsServer() string
  44. GetSecondaryDnsServer() string
  45. GetNetworkID() string
  46. }
  47. func NoticeUserLog(message string) {
  48. psiphon.NoticeUserLog(message)
  49. }
  50. // HomepageFilePath returns the path where homepage files will be paved.
  51. //
  52. // rootDataDirectoryPath is the configured data root directory.
  53. //
  54. // Note: homepage files will only be paved if UseNoticeFiles is set in the
  55. // config passed to Start().
  56. func HomepageFilePath(rootDataDirectoryPath string) string {
  57. return filepath.Join(rootDataDirectoryPath, psiphon.PsiphonDataDirectoryName, psiphon.HomepageFilename)
  58. }
  59. // NoticesFilePath returns the path where the notices file will be paved.
  60. //
  61. // rootDataDirectoryPath is the configured data root directory.
  62. //
  63. // Note: notices will only be paved if UseNoticeFiles is set in the config
  64. // passed to Start().
  65. func NoticesFilePath(rootDataDirectoryPath string) string {
  66. return filepath.Join(rootDataDirectoryPath, psiphon.PsiphonDataDirectoryName, psiphon.NoticesFilename)
  67. }
  68. // OldNoticesFilePath returns the path where the notices file is moved to when
  69. // file rotation occurs.
  70. //
  71. // rootDataDirectoryPath is the configured data root directory.
  72. //
  73. // Note: notices will only be paved if UseNoticeFiles is set in the config
  74. // passed to Start().
  75. func OldNoticesFilePath(rootDataDirectoryPath string) string {
  76. return filepath.Join(rootDataDirectoryPath, psiphon.PsiphonDataDirectoryName, psiphon.OldNoticesFilename)
  77. }
  78. // UpgradeDownloadFilePath returns the path where the downloaded upgrade file
  79. // will be paved.
  80. //
  81. // rootDataDirectoryPath is the configured data root directory.
  82. //
  83. // Note: upgrades will only be paved if UpgradeDownloadURLs is set in the config
  84. // passed to Start() and there are upgrades available.
  85. func UpgradeDownloadFilePath(rootDataDirectoryPath string) string {
  86. return filepath.Join(rootDataDirectoryPath, psiphon.PsiphonDataDirectoryName, psiphon.UpgradeDownloadFilename)
  87. }
  88. var controllerMutex sync.Mutex
  89. var controller *psiphon.Controller
  90. var controllerCtx context.Context
  91. var stopController context.CancelFunc
  92. var controllerWaitGroup *sync.WaitGroup
  93. func Start(
  94. configJson,
  95. embeddedServerEntryList,
  96. embeddedServerEntryListFilename string,
  97. provider PsiphonProvider,
  98. useDeviceBinder,
  99. useIPv6Synthesizer bool) error {
  100. controllerMutex.Lock()
  101. defer controllerMutex.Unlock()
  102. if controller != nil {
  103. return fmt.Errorf("already started")
  104. }
  105. // Clients may toggle Stop/Start immediately to apply new config settings
  106. // such as EgressRegion or Authorizations. When this restart is within the
  107. // same process and in a memory contrained environment, it is useful to
  108. // force garbage collection here to reclaim memory used by the previous
  109. // Controller.
  110. psiphon.DoGarbageCollection()
  111. // Wrap the provider in a layer that locks a mutex before calling a provider function.
  112. // As the provider callbacks are Java/Obj-C via gomobile, they are cgo calls that
  113. // can cause OS threads to be spawned. The mutex prevents many calling goroutines from
  114. // causing unbounded numbers of OS threads to be spawned.
  115. // TODO: replace the mutex with a semaphore, to allow a larger but still bounded concurrent
  116. // number of calls to the provider?
  117. provider = newMutexPsiphonProvider(provider)
  118. config, err := psiphon.LoadConfig([]byte(configJson))
  119. if err != nil {
  120. return fmt.Errorf("error loading configuration file: %s", err)
  121. }
  122. config.NetworkConnectivityChecker = provider
  123. config.NetworkIDGetter = provider
  124. if useDeviceBinder {
  125. config.DeviceBinder = provider
  126. config.DnsServerGetter = provider
  127. }
  128. if useIPv6Synthesizer {
  129. config.IPv6Synthesizer = provider
  130. }
  131. // All config fields should be set before calling Commit.
  132. err = config.Commit(true)
  133. if err != nil {
  134. return fmt.Errorf("error committing configuration file: %s", err)
  135. }
  136. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  137. func(notice []byte) {
  138. provider.Notice(string(notice))
  139. }))
  140. // BuildInfo is a diagnostic notice, so emit only after config.Commit
  141. // sets EmitDiagnosticNotices.
  142. psiphon.NoticeBuildInfo()
  143. err = psiphon.OpenDataStore(config)
  144. if err != nil {
  145. return fmt.Errorf("error initializing datastore: %s", err)
  146. }
  147. // Stores list of server entries.
  148. err = storeServerEntries(
  149. config,
  150. embeddedServerEntryListFilename,
  151. embeddedServerEntryList)
  152. if err != nil {
  153. return err
  154. }
  155. controller, err = psiphon.NewController(config)
  156. if err != nil {
  157. return fmt.Errorf("error initializing controller: %s", err)
  158. }
  159. controllerCtx, stopController = context.WithCancel(context.Background())
  160. controllerWaitGroup = new(sync.WaitGroup)
  161. controllerWaitGroup.Add(1)
  162. go func() {
  163. defer controllerWaitGroup.Done()
  164. controller.Run(controllerCtx)
  165. }()
  166. return nil
  167. }
  168. func Stop() {
  169. controllerMutex.Lock()
  170. defer controllerMutex.Unlock()
  171. if controller != nil {
  172. stopController()
  173. controllerWaitGroup.Wait()
  174. psiphon.CloseDataStore()
  175. controller = nil
  176. controllerCtx = nil
  177. stopController = nil
  178. controllerWaitGroup = nil
  179. }
  180. }
  181. // ReconnectTunnel initiates a reconnect of the current tunnel, if one is
  182. // running.
  183. func ReconnectTunnel() {
  184. controllerMutex.Lock()
  185. defer controllerMutex.Unlock()
  186. if controller != nil {
  187. controller.TerminateNextActiveTunnel()
  188. }
  189. }
  190. // SetDynamicConfig overrides the sponsor ID and authorizations fields set in
  191. // the config passed to Start. SetDynamicConfig has no effect if no Controller
  192. // is started.
  193. //
  194. // The input newAuthorizationsList is a space-delimited list of base64
  195. // authorizations. This is a workaround for gobind type limitations.
  196. func SetDynamicConfig(newSponsorID, newAuthorizationsList string) {
  197. controllerMutex.Lock()
  198. defer controllerMutex.Unlock()
  199. if controller != nil {
  200. var authorizations []string
  201. if len(newAuthorizationsList) > 0 {
  202. authorizations = strings.Split(newAuthorizationsList, " ")
  203. }
  204. controller.SetDynamicConfig(
  205. newSponsorID,
  206. authorizations)
  207. }
  208. }
  209. // ExportExchangePayload creates a payload for client-to-client server
  210. // connection info exchange.
  211. //
  212. // ExportExchangePayload will succeed only when Psiphon is running, between
  213. // Start and Stop.
  214. //
  215. // The return value is a payload that may be exchanged with another client;
  216. // when "", the export failed and a diagnostic has been logged.
  217. func ExportExchangePayload() string {
  218. controllerMutex.Lock()
  219. defer controllerMutex.Unlock()
  220. if controller == nil {
  221. return ""
  222. }
  223. return controller.ExportExchangePayload()
  224. }
  225. // ImportExchangePayload imports a payload generated by ExportExchangePayload.
  226. //
  227. // If an import occurs when Psiphon is working to establsh a tunnel, the newly
  228. // imported server entry is prioritized.
  229. //
  230. // The return value indicates a successful import. If the import failed, a a
  231. // diagnostic notice has been logged.
  232. func ImportExchangePayload(payload string) bool {
  233. controllerMutex.Lock()
  234. defer controllerMutex.Unlock()
  235. if controller == nil {
  236. return false
  237. }
  238. return controller.ImportExchangePayload(payload)
  239. }
  240. // Encrypt and upload feedback.
  241. func SendFeedback(configJson, diagnosticsJson, b64EncodedPublicKey, uploadServer, uploadPath, uploadServerHeaders string) error {
  242. return psiphon.SendFeedback(configJson, diagnosticsJson, b64EncodedPublicKey, uploadServer, uploadPath, uploadServerHeaders)
  243. }
  244. // Get build info from tunnel-core
  245. func GetBuildInfo() string {
  246. buildInfo, err := json.Marshal(buildinfo.GetBuildInfo())
  247. if err != nil {
  248. return ""
  249. }
  250. return string(buildInfo)
  251. }
  252. func GetPacketTunnelMTU() int {
  253. return tun.DEFAULT_MTU
  254. }
  255. func GetPacketTunnelDNSResolverIPv4Address() string {
  256. return tun.GetTransparentDNSResolverIPv4Address().String()
  257. }
  258. func GetPacketTunnelDNSResolverIPv6Address() string {
  259. return tun.GetTransparentDNSResolverIPv6Address().String()
  260. }
  261. // WriteRuntimeProfiles writes Go runtime profile information to a set of
  262. // files in the specified output directory. See common.WriteRuntimeProfiles
  263. // for more details.
  264. //
  265. // If called before Start, log notices will emit to stderr.
  266. func WriteRuntimeProfiles(outputDirectory string, cpuSampleDurationSeconds, blockSampleDurationSeconds int) {
  267. common.WriteRuntimeProfiles(
  268. psiphon.NoticeCommonLogger(),
  269. outputDirectory,
  270. "",
  271. cpuSampleDurationSeconds,
  272. blockSampleDurationSeconds)
  273. }
  274. // Helper function to store a list of server entries.
  275. // if embeddedServerEntryListFilename is not empty, embeddedServerEntryList will be ignored.
  276. func storeServerEntries(
  277. config *psiphon.Config,
  278. embeddedServerEntryListFilename, embeddedServerEntryList string) error {
  279. if embeddedServerEntryListFilename != "" {
  280. file, err := os.Open(embeddedServerEntryListFilename)
  281. if err != nil {
  282. return fmt.Errorf("error reading embedded server list file: %s", err)
  283. }
  284. defer file.Close()
  285. err = psiphon.StreamingStoreServerEntries(
  286. config,
  287. protocol.NewStreamingServerEntryDecoder(
  288. file,
  289. common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  290. protocol.SERVER_ENTRY_SOURCE_EMBEDDED),
  291. false)
  292. if err != nil {
  293. return fmt.Errorf("error storing embedded server list: %s", err)
  294. }
  295. } else {
  296. serverEntries, err := protocol.DecodeServerEntryList(
  297. embeddedServerEntryList,
  298. common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  299. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  300. if err != nil {
  301. return fmt.Errorf("error decoding embedded server list: %s", err)
  302. }
  303. err = psiphon.StoreServerEntries(config, serverEntries, false)
  304. if err != nil {
  305. return fmt.Errorf("error storing embedded server list: %s", err)
  306. }
  307. }
  308. return nil
  309. }
  310. type mutexPsiphonProvider struct {
  311. sync.Mutex
  312. p PsiphonProvider
  313. }
  314. func newMutexPsiphonProvider(p PsiphonProvider) *mutexPsiphonProvider {
  315. return &mutexPsiphonProvider{p: p}
  316. }
  317. func (p *mutexPsiphonProvider) Notice(noticeJSON string) {
  318. p.Lock()
  319. defer p.Unlock()
  320. p.p.Notice(noticeJSON)
  321. }
  322. func (p *mutexPsiphonProvider) HasNetworkConnectivity() int {
  323. p.Lock()
  324. defer p.Unlock()
  325. return p.p.HasNetworkConnectivity()
  326. }
  327. func (p *mutexPsiphonProvider) BindToDevice(fileDescriptor int) (string, error) {
  328. p.Lock()
  329. defer p.Unlock()
  330. return p.p.BindToDevice(fileDescriptor)
  331. }
  332. func (p *mutexPsiphonProvider) IPv6Synthesize(IPv4Addr string) string {
  333. p.Lock()
  334. defer p.Unlock()
  335. return p.p.IPv6Synthesize(IPv4Addr)
  336. }
  337. func (p *mutexPsiphonProvider) GetPrimaryDnsServer() string {
  338. p.Lock()
  339. defer p.Unlock()
  340. return p.p.GetPrimaryDnsServer()
  341. }
  342. func (p *mutexPsiphonProvider) GetSecondaryDnsServer() string {
  343. p.Lock()
  344. defer p.Unlock()
  345. return p.p.GetSecondaryDnsServer()
  346. }
  347. func (p *mutexPsiphonProvider) GetNetworkID() string {
  348. p.Lock()
  349. defer p.Unlock()
  350. return p.p.GetNetworkID()
  351. }