psi.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. "strings"
  29. "sync"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  34. "os"
  35. )
  36. type PsiphonProvider interface {
  37. Notice(noticeJSON string)
  38. HasNetworkConnectivity() int
  39. BindToDevice(fileDescriptor int) (string, error)
  40. IPv6Synthesize(IPv4Addr string) string
  41. GetPrimaryDnsServer() string
  42. GetSecondaryDnsServer() string
  43. GetNetworkID() string
  44. }
  45. func SetNoticeFiles(
  46. homepageFilename,
  47. rotatingFilename string,
  48. rotatingFileSize,
  49. rotatingSyncFrequency int) error {
  50. return psiphon.SetNoticeFiles(
  51. homepageFilename,
  52. rotatingFilename,
  53. rotatingFileSize,
  54. rotatingSyncFrequency)
  55. }
  56. func NoticeUserLog(message string) {
  57. psiphon.NoticeUserLog(message)
  58. }
  59. var controllerMutex sync.Mutex
  60. var controller *psiphon.Controller
  61. var controllerCtx context.Context
  62. var stopController context.CancelFunc
  63. var controllerWaitGroup *sync.WaitGroup
  64. func Start(
  65. configJson,
  66. embeddedServerEntryList,
  67. embeddedServerEntryListFilename string,
  68. provider PsiphonProvider,
  69. useDeviceBinder,
  70. useIPv6Synthesizer bool) error {
  71. controllerMutex.Lock()
  72. defer controllerMutex.Unlock()
  73. if controller != nil {
  74. return fmt.Errorf("already started")
  75. }
  76. // Clients may toggle Stop/Start immediately to apply new config settings
  77. // such as EgressRegion or Authorizations. When this restart is within the
  78. // same process and in a memory contrained environment, it is useful to
  79. // force garbage collection here to reclaim memory used by the previous
  80. // Controller.
  81. psiphon.DoGarbageCollection()
  82. // Wrap the provider in a layer that locks a mutex before calling a provider function.
  83. // The the provider callbacks are Java/Obj-C via gomobile, they are cgo calls that
  84. // can cause OS threads to be spawned. The mutex prevents many calling goroutines from
  85. // causing unbounded numbers of OS threads to be spawned.
  86. // TODO: replace the mutex with a semaphore, to allow a larger but still bounded concurrent
  87. // number of calls to the provider?
  88. provider = newMutexPsiphonProvider(provider)
  89. config, err := psiphon.LoadConfig([]byte(configJson))
  90. if err != nil {
  91. return fmt.Errorf("error loading configuration file: %s", err)
  92. }
  93. config.NetworkConnectivityChecker = provider
  94. config.NetworkIDGetter = provider
  95. if useDeviceBinder {
  96. config.DeviceBinder = newLoggingDeviceBinder(provider)
  97. config.DnsServerGetter = provider
  98. }
  99. if useIPv6Synthesizer {
  100. config.IPv6Synthesizer = provider
  101. }
  102. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  103. func(notice []byte) {
  104. provider.Notice(string(notice))
  105. }))
  106. psiphon.NoticeBuildInfo()
  107. err = psiphon.InitDataStore(config)
  108. if err != nil {
  109. return fmt.Errorf("error initializing datastore: %s", err)
  110. }
  111. // Stores list of server entries.
  112. err = storeServerEntries(
  113. config,
  114. embeddedServerEntryListFilename,
  115. embeddedServerEntryList)
  116. if err != nil {
  117. return err
  118. }
  119. controller, err = psiphon.NewController(config)
  120. if err != nil {
  121. return fmt.Errorf("error initializing controller: %s", err)
  122. }
  123. controllerCtx, stopController = context.WithCancel(context.Background())
  124. controllerWaitGroup = new(sync.WaitGroup)
  125. controllerWaitGroup.Add(1)
  126. go func() {
  127. defer controllerWaitGroup.Done()
  128. controller.Run(controllerCtx)
  129. }()
  130. return nil
  131. }
  132. func Stop() {
  133. controllerMutex.Lock()
  134. defer controllerMutex.Unlock()
  135. if controller != nil {
  136. stopController()
  137. controllerWaitGroup.Wait()
  138. controller = nil
  139. controllerCtx = nil
  140. stopController = nil
  141. controllerWaitGroup = nil
  142. }
  143. }
  144. func ReconnectTunnel() {
  145. controllerMutex.Lock()
  146. defer controllerMutex.Unlock()
  147. if controller != nil {
  148. // TODO: ensure TerminateNextActiveTunnel is safe for use (see godoc)
  149. controller.TerminateNextActiveTunnel()
  150. }
  151. }
  152. // SetClientVerificationPayload is a passthrough to
  153. // Controller.SetClientVerificationPayloadForActiveTunnels.
  154. // Note: should only be called after Start() and before Stop(); otherwise,
  155. // will silently take no action.
  156. func SetClientVerificationPayload(clientVerificationPayload string) {
  157. controllerMutex.Lock()
  158. defer controllerMutex.Unlock()
  159. if controller != nil {
  160. controller.SetClientVerificationPayloadForActiveTunnels(clientVerificationPayload)
  161. }
  162. }
  163. // Encrypt and upload feedback.
  164. func SendFeedback(configJson, diagnosticsJson, b64EncodedPublicKey, uploadServer, uploadPath, uploadServerHeaders string) error {
  165. return psiphon.SendFeedback(configJson, diagnosticsJson, b64EncodedPublicKey, uploadServer, uploadPath, uploadServerHeaders)
  166. }
  167. // Get build info from tunnel-core
  168. func GetBuildInfo() string {
  169. buildInfo, err := json.Marshal(common.GetBuildInfo())
  170. if err != nil {
  171. return ""
  172. }
  173. return string(buildInfo)
  174. }
  175. func GetPacketTunnelMTU() int {
  176. return tun.DEFAULT_MTU
  177. }
  178. func GetPacketTunnelDNSResolverIPv4Address() string {
  179. return tun.GetTransparentDNSResolverIPv4Address().String()
  180. }
  181. func GetPacketTunnelDNSResolverIPv6Address() string {
  182. return tun.GetTransparentDNSResolverIPv6Address().String()
  183. }
  184. // Helper function to store a list of server entries.
  185. // if embeddedServerEntryListFilename is not empty, embeddedServerEntryList will be ignored.
  186. func storeServerEntries(
  187. config *psiphon.Config,
  188. embeddedServerEntryListFilename, embeddedServerEntryList string) error {
  189. if embeddedServerEntryListFilename != "" {
  190. file, err := os.Open(embeddedServerEntryListFilename)
  191. if err != nil {
  192. return fmt.Errorf("error reading embedded server list file: %s", common.ContextError(err))
  193. }
  194. defer file.Close()
  195. err = psiphon.StreamingStoreServerEntries(
  196. config,
  197. protocol.NewStreamingServerEntryDecoder(
  198. file,
  199. common.GetCurrentTimestamp(),
  200. protocol.SERVER_ENTRY_SOURCE_EMBEDDED),
  201. false)
  202. if err != nil {
  203. return fmt.Errorf("error storing embedded server list: %s", common.ContextError(err))
  204. }
  205. } else {
  206. serverEntries, err := protocol.DecodeServerEntryList(
  207. embeddedServerEntryList,
  208. common.GetCurrentTimestamp(),
  209. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  210. if err != nil {
  211. return fmt.Errorf("error decoding embedded server list: %s", err)
  212. }
  213. err = psiphon.StoreServerEntries(config, serverEntries, false)
  214. if err != nil {
  215. return fmt.Errorf("error storing embedded server list: %s", err)
  216. }
  217. }
  218. return nil
  219. }
  220. type mutexPsiphonProvider struct {
  221. sync.Mutex
  222. p PsiphonProvider
  223. }
  224. func newMutexPsiphonProvider(p PsiphonProvider) *mutexPsiphonProvider {
  225. return &mutexPsiphonProvider{p: p}
  226. }
  227. func (p *mutexPsiphonProvider) Notice(noticeJSON string) {
  228. p.Lock()
  229. defer p.Unlock()
  230. p.p.Notice(noticeJSON)
  231. }
  232. func (p *mutexPsiphonProvider) HasNetworkConnectivity() int {
  233. p.Lock()
  234. defer p.Unlock()
  235. return p.p.HasNetworkConnectivity()
  236. }
  237. func (p *mutexPsiphonProvider) BindToDevice(fileDescriptor int) (string, error) {
  238. p.Lock()
  239. defer p.Unlock()
  240. return p.p.BindToDevice(fileDescriptor)
  241. }
  242. func (p *mutexPsiphonProvider) IPv6Synthesize(IPv4Addr string) string {
  243. p.Lock()
  244. defer p.Unlock()
  245. return p.p.IPv6Synthesize(IPv4Addr)
  246. }
  247. func (p *mutexPsiphonProvider) GetPrimaryDnsServer() string {
  248. p.Lock()
  249. defer p.Unlock()
  250. return p.p.GetPrimaryDnsServer()
  251. }
  252. func (p *mutexPsiphonProvider) GetSecondaryDnsServer() string {
  253. p.Lock()
  254. defer p.Unlock()
  255. return p.p.GetSecondaryDnsServer()
  256. }
  257. func (p *mutexPsiphonProvider) GetNetworkID() string {
  258. p.Lock()
  259. defer p.Unlock()
  260. return p.p.GetNetworkID()
  261. }
  262. type loggingDeviceBinder struct {
  263. p PsiphonProvider
  264. }
  265. func newLoggingDeviceBinder(p PsiphonProvider) *loggingDeviceBinder {
  266. return &loggingDeviceBinder{p: p}
  267. }
  268. func (d *loggingDeviceBinder) BindToDevice(fileDescriptor int) error {
  269. deviceInfo, err := d.p.BindToDevice(fileDescriptor)
  270. if err == nil && deviceInfo != "" {
  271. psiphon.NoticeInfo("BindToDevice: %s", deviceInfo)
  272. }
  273. return err
  274. }
  275. type loggingNetworkIDGetter struct {
  276. p PsiphonProvider
  277. }
  278. func newLoggingNetworkIDGetter(p PsiphonProvider) *loggingNetworkIDGetter {
  279. return &loggingNetworkIDGetter{p: p}
  280. }
  281. func (d *loggingNetworkIDGetter) GetNetworkID() string {
  282. networkID := d.p.GetNetworkID()
  283. // All PII must appear after the initial "-"
  284. // See: https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter
  285. logNetworkID := networkID
  286. index := strings.Index(logNetworkID, "-")
  287. if index != -1 {
  288. logNetworkID = logNetworkID[:index]
  289. }
  290. if len(logNetworkID)+1 < len(networkID) {
  291. // Indicate when additional network info was present after the first "-".
  292. logNetworkID += "+<network info>"
  293. }
  294. psiphon.NoticeInfo("GetNetworkID: %s", logNetworkID)
  295. return networkID
  296. }