psi.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. psiphon.CloseDataStore()
  158. return fmt.Errorf("error initializing controller: %s", err)
  159. }
  160. controllerCtx, stopController = context.WithCancel(context.Background())
  161. controllerWaitGroup = new(sync.WaitGroup)
  162. controllerWaitGroup.Add(1)
  163. go func() {
  164. defer controllerWaitGroup.Done()
  165. controller.Run(controllerCtx)
  166. }()
  167. return nil
  168. }
  169. func Stop() {
  170. controllerMutex.Lock()
  171. defer controllerMutex.Unlock()
  172. if controller != nil {
  173. stopController()
  174. controllerWaitGroup.Wait()
  175. psiphon.CloseDataStore()
  176. controller = nil
  177. controllerCtx = nil
  178. stopController = nil
  179. controllerWaitGroup = nil
  180. }
  181. }
  182. // ReconnectTunnel initiates a reconnect of the current tunnel, if one is
  183. // running.
  184. func ReconnectTunnel() {
  185. controllerMutex.Lock()
  186. defer controllerMutex.Unlock()
  187. if controller != nil {
  188. controller.TerminateNextActiveTunnel()
  189. }
  190. }
  191. // SetDynamicConfig overrides the sponsor ID and authorizations fields set in
  192. // the config passed to Start. SetDynamicConfig has no effect if no Controller
  193. // is started.
  194. //
  195. // The input newAuthorizationsList is a space-delimited list of base64
  196. // authorizations. This is a workaround for gobind type limitations.
  197. func SetDynamicConfig(newSponsorID, newAuthorizationsList string) {
  198. controllerMutex.Lock()
  199. defer controllerMutex.Unlock()
  200. if controller != nil {
  201. var authorizations []string
  202. if len(newAuthorizationsList) > 0 {
  203. authorizations = strings.Split(newAuthorizationsList, " ")
  204. }
  205. controller.SetDynamicConfig(
  206. newSponsorID,
  207. authorizations)
  208. }
  209. }
  210. // ExportExchangePayload creates a payload for client-to-client server
  211. // connection info exchange.
  212. //
  213. // ExportExchangePayload will succeed only when Psiphon is running, between
  214. // Start and Stop.
  215. //
  216. // The return value is a payload that may be exchanged with another client;
  217. // when "", the export failed and a diagnostic has been logged.
  218. func ExportExchangePayload() string {
  219. controllerMutex.Lock()
  220. defer controllerMutex.Unlock()
  221. if controller == nil {
  222. return ""
  223. }
  224. return controller.ExportExchangePayload()
  225. }
  226. // ImportExchangePayload imports a payload generated by ExportExchangePayload.
  227. //
  228. // If an import occurs when Psiphon is working to establsh a tunnel, the newly
  229. // imported server entry is prioritized.
  230. //
  231. // The return value indicates a successful import. If the import failed, a a
  232. // diagnostic notice has been logged.
  233. func ImportExchangePayload(payload string) bool {
  234. controllerMutex.Lock()
  235. defer controllerMutex.Unlock()
  236. if controller == nil {
  237. return false
  238. }
  239. return controller.ImportExchangePayload(payload)
  240. }
  241. // Encrypt and upload feedback.
  242. func SendFeedback(configJson, diagnosticsJson, b64EncodedPublicKey, uploadServer, uploadPath, uploadServerHeaders string) error {
  243. return psiphon.SendFeedback(configJson, diagnosticsJson, b64EncodedPublicKey, uploadServer, uploadPath, uploadServerHeaders)
  244. }
  245. // Get build info from tunnel-core
  246. func GetBuildInfo() string {
  247. buildInfo, err := json.Marshal(buildinfo.GetBuildInfo())
  248. if err != nil {
  249. return ""
  250. }
  251. return string(buildInfo)
  252. }
  253. func GetPacketTunnelMTU() int {
  254. return tun.DEFAULT_MTU
  255. }
  256. func GetPacketTunnelDNSResolverIPv4Address() string {
  257. return tun.GetTransparentDNSResolverIPv4Address().String()
  258. }
  259. func GetPacketTunnelDNSResolverIPv6Address() string {
  260. return tun.GetTransparentDNSResolverIPv6Address().String()
  261. }
  262. // WriteRuntimeProfiles writes Go runtime profile information to a set of
  263. // files in the specified output directory. See common.WriteRuntimeProfiles
  264. // for more details.
  265. //
  266. // If called before Start, log notices will emit to stderr.
  267. func WriteRuntimeProfiles(outputDirectory string, cpuSampleDurationSeconds, blockSampleDurationSeconds int) {
  268. common.WriteRuntimeProfiles(
  269. psiphon.NoticeCommonLogger(),
  270. outputDirectory,
  271. "",
  272. cpuSampleDurationSeconds,
  273. blockSampleDurationSeconds)
  274. }
  275. // Helper function to store a list of server entries.
  276. // if embeddedServerEntryListFilename is not empty, embeddedServerEntryList will be ignored.
  277. func storeServerEntries(
  278. config *psiphon.Config,
  279. embeddedServerEntryListFilename, embeddedServerEntryList string) error {
  280. if embeddedServerEntryListFilename != "" {
  281. file, err := os.Open(embeddedServerEntryListFilename)
  282. if err != nil {
  283. return fmt.Errorf("error reading embedded server list file: %s", err)
  284. }
  285. defer file.Close()
  286. err = psiphon.StreamingStoreServerEntries(
  287. config,
  288. protocol.NewStreamingServerEntryDecoder(
  289. file,
  290. common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  291. protocol.SERVER_ENTRY_SOURCE_EMBEDDED),
  292. false)
  293. if err != nil {
  294. return fmt.Errorf("error storing embedded server list: %s", err)
  295. }
  296. } else {
  297. serverEntries, err := protocol.DecodeServerEntryList(
  298. embeddedServerEntryList,
  299. common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  300. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  301. if err != nil {
  302. return fmt.Errorf("error decoding embedded server list: %s", err)
  303. }
  304. err = psiphon.StoreServerEntries(config, serverEntries, false)
  305. if err != nil {
  306. return fmt.Errorf("error storing embedded server list: %s", err)
  307. }
  308. }
  309. return nil
  310. }
  311. type mutexPsiphonProvider struct {
  312. sync.Mutex
  313. p PsiphonProvider
  314. }
  315. func newMutexPsiphonProvider(p PsiphonProvider) *mutexPsiphonProvider {
  316. return &mutexPsiphonProvider{p: p}
  317. }
  318. func (p *mutexPsiphonProvider) Notice(noticeJSON string) {
  319. p.Lock()
  320. defer p.Unlock()
  321. p.p.Notice(noticeJSON)
  322. }
  323. func (p *mutexPsiphonProvider) HasNetworkConnectivity() int {
  324. p.Lock()
  325. defer p.Unlock()
  326. return p.p.HasNetworkConnectivity()
  327. }
  328. func (p *mutexPsiphonProvider) BindToDevice(fileDescriptor int) (string, error) {
  329. p.Lock()
  330. defer p.Unlock()
  331. return p.p.BindToDevice(fileDescriptor)
  332. }
  333. func (p *mutexPsiphonProvider) IPv6Synthesize(IPv4Addr string) string {
  334. p.Lock()
  335. defer p.Unlock()
  336. return p.p.IPv6Synthesize(IPv4Addr)
  337. }
  338. func (p *mutexPsiphonProvider) GetPrimaryDnsServer() string {
  339. p.Lock()
  340. defer p.Unlock()
  341. return p.p.GetPrimaryDnsServer()
  342. }
  343. func (p *mutexPsiphonProvider) GetSecondaryDnsServer() string {
  344. p.Lock()
  345. defer p.Unlock()
  346. return p.p.GetSecondaryDnsServer()
  347. }
  348. func (p *mutexPsiphonProvider) GetNetworkID() string {
  349. p.Lock()
  350. defer p.Unlock()
  351. return p.p.GetNetworkID()
  352. }