psi.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. controller.SetDynamicConfig(
  201. newSponsorID,
  202. strings.Split(newAuthorizationsList, " "))
  203. }
  204. }
  205. // ExportExchangePayload creates a payload for client-to-client server
  206. // connection info exchange.
  207. //
  208. // ExportExchangePayload will succeed only when Psiphon is running, between
  209. // Start and Stop.
  210. //
  211. // The return value is a payload that may be exchanged with another client;
  212. // when "", the export failed and a diagnostic has been logged.
  213. func ExportExchangePayload() string {
  214. controllerMutex.Lock()
  215. defer controllerMutex.Unlock()
  216. if controller == nil {
  217. return ""
  218. }
  219. return controller.ExportExchangePayload()
  220. }
  221. // ImportExchangePayload imports a payload generated by ExportExchangePayload.
  222. //
  223. // If an import occurs when Psiphon is working to establsh a tunnel, the newly
  224. // imported server entry is prioritized.
  225. //
  226. // The return value indicates a successful import. If the import failed, a a
  227. // diagnostic notice has been logged.
  228. func ImportExchangePayload(payload string) bool {
  229. controllerMutex.Lock()
  230. defer controllerMutex.Unlock()
  231. if controller == nil {
  232. return false
  233. }
  234. return controller.ImportExchangePayload(payload)
  235. }
  236. // Encrypt and upload feedback.
  237. func SendFeedback(configJson, diagnosticsJson, b64EncodedPublicKey, uploadServer, uploadPath, uploadServerHeaders string) error {
  238. return psiphon.SendFeedback(configJson, diagnosticsJson, b64EncodedPublicKey, uploadServer, uploadPath, uploadServerHeaders)
  239. }
  240. // Get build info from tunnel-core
  241. func GetBuildInfo() string {
  242. buildInfo, err := json.Marshal(buildinfo.GetBuildInfo())
  243. if err != nil {
  244. return ""
  245. }
  246. return string(buildInfo)
  247. }
  248. func GetPacketTunnelMTU() int {
  249. return tun.DEFAULT_MTU
  250. }
  251. func GetPacketTunnelDNSResolverIPv4Address() string {
  252. return tun.GetTransparentDNSResolverIPv4Address().String()
  253. }
  254. func GetPacketTunnelDNSResolverIPv6Address() string {
  255. return tun.GetTransparentDNSResolverIPv6Address().String()
  256. }
  257. // WriteRuntimeProfiles writes Go runtime profile information to a set of
  258. // files in the specified output directory. See common.WriteRuntimeProfiles
  259. // for more details.
  260. //
  261. // If called before Start, log notices will emit to stderr.
  262. func WriteRuntimeProfiles(outputDirectory string, cpuSampleDurationSeconds, blockSampleDurationSeconds int) {
  263. common.WriteRuntimeProfiles(
  264. psiphon.NoticeCommonLogger(),
  265. outputDirectory,
  266. "",
  267. cpuSampleDurationSeconds,
  268. blockSampleDurationSeconds)
  269. }
  270. // Helper function to store a list of server entries.
  271. // if embeddedServerEntryListFilename is not empty, embeddedServerEntryList will be ignored.
  272. func storeServerEntries(
  273. config *psiphon.Config,
  274. embeddedServerEntryListFilename, embeddedServerEntryList string) error {
  275. if embeddedServerEntryListFilename != "" {
  276. file, err := os.Open(embeddedServerEntryListFilename)
  277. if err != nil {
  278. return fmt.Errorf("error reading embedded server list file: %s", err)
  279. }
  280. defer file.Close()
  281. err = psiphon.StreamingStoreServerEntries(
  282. config,
  283. protocol.NewStreamingServerEntryDecoder(
  284. file,
  285. common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  286. protocol.SERVER_ENTRY_SOURCE_EMBEDDED),
  287. false)
  288. if err != nil {
  289. return fmt.Errorf("error storing embedded server list: %s", err)
  290. }
  291. } else {
  292. serverEntries, err := protocol.DecodeServerEntryList(
  293. embeddedServerEntryList,
  294. common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  295. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  296. if err != nil {
  297. return fmt.Errorf("error decoding embedded server list: %s", err)
  298. }
  299. err = psiphon.StoreServerEntries(config, serverEntries, false)
  300. if err != nil {
  301. return fmt.Errorf("error storing embedded server list: %s", err)
  302. }
  303. }
  304. return nil
  305. }
  306. type mutexPsiphonProvider struct {
  307. sync.Mutex
  308. p PsiphonProvider
  309. }
  310. func newMutexPsiphonProvider(p PsiphonProvider) *mutexPsiphonProvider {
  311. return &mutexPsiphonProvider{p: p}
  312. }
  313. func (p *mutexPsiphonProvider) Notice(noticeJSON string) {
  314. p.Lock()
  315. defer p.Unlock()
  316. p.p.Notice(noticeJSON)
  317. }
  318. func (p *mutexPsiphonProvider) HasNetworkConnectivity() int {
  319. p.Lock()
  320. defer p.Unlock()
  321. return p.p.HasNetworkConnectivity()
  322. }
  323. func (p *mutexPsiphonProvider) BindToDevice(fileDescriptor int) (string, error) {
  324. p.Lock()
  325. defer p.Unlock()
  326. return p.p.BindToDevice(fileDescriptor)
  327. }
  328. func (p *mutexPsiphonProvider) IPv6Synthesize(IPv4Addr string) string {
  329. p.Lock()
  330. defer p.Unlock()
  331. return p.p.IPv6Synthesize(IPv4Addr)
  332. }
  333. func (p *mutexPsiphonProvider) GetPrimaryDnsServer() string {
  334. p.Lock()
  335. defer p.Unlock()
  336. return p.p.GetPrimaryDnsServer()
  337. }
  338. func (p *mutexPsiphonProvider) GetSecondaryDnsServer() string {
  339. p.Lock()
  340. defer p.Unlock()
  341. return p.p.GetSecondaryDnsServer()
  342. }
  343. func (p *mutexPsiphonProvider) GetNetworkID() string {
  344. p.Lock()
  345. defer p.Unlock()
  346. return p.p.GetNetworkID()
  347. }