main.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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 main
  20. import (
  21. "bytes"
  22. "context"
  23. "encoding/json"
  24. "flag"
  25. "fmt"
  26. "io"
  27. "io/ioutil"
  28. "os"
  29. "os/signal"
  30. "sort"
  31. "sync"
  32. "syscall"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/buildinfo"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  39. )
  40. func main() {
  41. // Define command-line parameters
  42. var configFilename string
  43. flag.StringVar(&configFilename, "config", "", "configuration input file")
  44. var dataRootDirectory string
  45. flag.StringVar(&dataRootDirectory, "dataRootDirectory", "", "directory where persistent files will be stored")
  46. var embeddedServerEntryListFilename string
  47. flag.StringVar(&embeddedServerEntryListFilename, "serverList", "", "embedded server entry list input file")
  48. var formatNotices bool
  49. flag.BoolVar(&formatNotices, "formatNotices", false, "emit notices in human-readable format")
  50. var interfaceName string
  51. flag.StringVar(&interfaceName, "listenInterface", "", "bind local proxies to specified interface")
  52. var versionDetails bool
  53. flag.BoolVar(&versionDetails, "version", false, "print build information and exit")
  54. flag.BoolVar(&versionDetails, "v", false, "print build information and exit")
  55. var feedbackUpload bool
  56. flag.BoolVar(&feedbackUpload, "feedbackUpload", false,
  57. "Run in feedback upload mode to send a feedback package to Psiphon Inc.\n"+
  58. "The feedback package will be read as a UTF-8 encoded string from stdin.\n"+
  59. "Informational notices will be written to stdout. If the upload succeeds,\n"+
  60. "the process will exit with status code 0; otherwise, the process will\n"+
  61. "exit with status code 1. A feedback compatible config must be specified\n"+
  62. "with the \"-config\" flag. Config must be provided by Psiphon Inc.")
  63. var feedbackUploadPath string
  64. flag.StringVar(&feedbackUploadPath, "feedbackUploadPath", "",
  65. "The path at which to upload the feedback package when the \"-feedbackUpload\"\n"+
  66. "flag is provided. Must be provided by Psiphon Inc.")
  67. var tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS string
  68. if tun.IsSupported() {
  69. // When tunDevice is specified, a packet tunnel is run and packets are relayed between
  70. // the specified tun device and the server.
  71. //
  72. // The tun device is expected to exist and should be configured with an IP address and
  73. // routing.
  74. //
  75. // The tunBindInterface/tunPrimaryDNS/tunSecondaryDNS parameters are used to bypass any
  76. // tun device routing when connecting to Psiphon servers.
  77. //
  78. // For transparent tunneled DNS, set the host or DNS clients to use the address specfied
  79. // in tun.GetTransparentDNSResolverIPv4Address().
  80. //
  81. // Packet tunnel mode is supported only on certains platforms.
  82. flag.StringVar(&tunDevice, "tunDevice", "", "run packet tunnel for specified tun device")
  83. flag.StringVar(&tunBindInterface, "tunBindInterface", tun.DEFAULT_PUBLIC_INTERFACE_NAME, "bypass tun device via specified interface")
  84. flag.StringVar(&tunPrimaryDNS, "tunPrimaryDNS", "8.8.8.8", "primary DNS resolver for bypass")
  85. flag.StringVar(&tunSecondaryDNS, "tunSecondaryDNS", "8.8.4.4", "secondary DNS resolver for bypass")
  86. }
  87. var noticeFilename string
  88. flag.StringVar(&noticeFilename, "notices", "", "notices output file (defaults to stderr)")
  89. var useNoticeFiles bool
  90. useNoticeFilesUsage := fmt.Sprintf("output homepage notices and rotating notices to <dataRootDirectory>/%s and <dataRootDirectory>/%s respectively", psiphon.HomepageFilename, psiphon.NoticesFilename)
  91. flag.BoolVar(&useNoticeFiles, "useNoticeFiles", false, useNoticeFilesUsage)
  92. var rotatingFileSize int
  93. flag.IntVar(&rotatingFileSize, "rotatingFileSize", 1<<20, "rotating notices file size")
  94. var rotatingSyncFrequency int
  95. flag.IntVar(&rotatingSyncFrequency, "rotatingSyncFrequency", 100, "rotating notices file sync frequency")
  96. flag.Parse()
  97. if versionDetails {
  98. b := buildinfo.GetBuildInfo()
  99. var printableDependencies bytes.Buffer
  100. var dependencyMap map[string]string
  101. longestRepoUrl := 0
  102. json.Unmarshal(b.Dependencies, &dependencyMap)
  103. sortedRepoUrls := make([]string, 0, len(dependencyMap))
  104. for repoUrl := range dependencyMap {
  105. repoUrlLength := len(repoUrl)
  106. if repoUrlLength > longestRepoUrl {
  107. longestRepoUrl = repoUrlLength
  108. }
  109. sortedRepoUrls = append(sortedRepoUrls, repoUrl)
  110. }
  111. sort.Strings(sortedRepoUrls)
  112. for repoUrl := range sortedRepoUrls {
  113. printableDependencies.WriteString(fmt.Sprintf(" %s ", sortedRepoUrls[repoUrl]))
  114. for i := 0; i < (longestRepoUrl - len(sortedRepoUrls[repoUrl])); i++ {
  115. printableDependencies.WriteString(" ")
  116. }
  117. printableDependencies.WriteString(fmt.Sprintf("%s\n", dependencyMap[sortedRepoUrls[repoUrl]]))
  118. }
  119. fmt.Printf("Psiphon Console Client\n Build Date: %s\n Built With: %s\n Repository: %s\n Revision: %s\n Dependencies:\n%s\n", b.BuildDate, b.GoVersion, b.BuildRepo, b.BuildRev, printableDependencies.String())
  120. os.Exit(0)
  121. }
  122. // Initialize notice output
  123. var noticeWriter io.Writer
  124. noticeWriter = os.Stderr
  125. if noticeFilename != "" {
  126. noticeFile, err := os.OpenFile(noticeFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  127. if err != nil {
  128. fmt.Printf("error opening notice file: %s\n", err)
  129. os.Exit(1)
  130. }
  131. defer noticeFile.Close()
  132. noticeWriter = noticeFile
  133. }
  134. if formatNotices {
  135. noticeWriter = psiphon.NewNoticeConsoleRewriter(noticeWriter)
  136. }
  137. psiphon.SetNoticeWriter(noticeWriter)
  138. // Handle required config file parameter
  139. // EmitDiagnosticNotices is set by LoadConfig; force to true
  140. // and emit diagnostics when LoadConfig-related errors occur.
  141. if configFilename == "" {
  142. psiphon.SetEmitDiagnosticNotices(true, false)
  143. psiphon.NoticeError("configuration file is required")
  144. os.Exit(1)
  145. }
  146. configFileContents, err := ioutil.ReadFile(configFilename)
  147. if err != nil {
  148. psiphon.SetEmitDiagnosticNotices(true, false)
  149. psiphon.NoticeError("error loading configuration file: %s", err)
  150. os.Exit(1)
  151. }
  152. config, err := psiphon.LoadConfig(configFileContents)
  153. if err != nil {
  154. psiphon.SetEmitDiagnosticNotices(true, false)
  155. psiphon.NoticeError("error processing configuration file: %s", err)
  156. os.Exit(1)
  157. }
  158. // Set data root directory
  159. if dataRootDirectory != "" {
  160. config.DataRootDirectory = dataRootDirectory
  161. }
  162. if interfaceName != "" {
  163. config.ListenInterface = interfaceName
  164. }
  165. // Configure notice files
  166. if useNoticeFiles {
  167. config.UseNoticeFiles = &psiphon.UseNoticeFiles{
  168. RotatingFileSize: rotatingFileSize,
  169. RotatingSyncFrequency: rotatingSyncFrequency,
  170. }
  171. }
  172. // Configure packet tunnel, including updating the config.
  173. if tun.IsSupported() && tunDevice != "" {
  174. tunDeviceFile, err := configurePacketTunnel(
  175. config, tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS)
  176. if err != nil {
  177. psiphon.SetEmitDiagnosticNotices(true, false)
  178. psiphon.NoticeError("error configuring packet tunnel: %s", err)
  179. os.Exit(1)
  180. }
  181. defer tunDeviceFile.Close()
  182. }
  183. // All config fields should be set before calling Commit.
  184. err = config.Commit(true)
  185. if err != nil {
  186. psiphon.SetEmitDiagnosticNotices(true, false)
  187. psiphon.NoticeError("error loading configuration file: %s", err)
  188. os.Exit(1)
  189. }
  190. // BuildInfo is a diagnostic notice, so emit only after config.Commit
  191. // sets EmitDiagnosticNotices.
  192. psiphon.NoticeBuildInfo()
  193. var worker Worker
  194. if feedbackUpload {
  195. // Feedback upload mode
  196. worker = &FeedbackWorker{
  197. feedbackUploadPath: feedbackUploadPath,
  198. }
  199. } else {
  200. // Tunnel mode
  201. worker = &TunnelWorker{
  202. embeddedServerEntryListFilename: embeddedServerEntryListFilename,
  203. }
  204. }
  205. err = worker.Init(config)
  206. if err != nil {
  207. psiphon.NoticeError("error in init: %s", err)
  208. os.Exit(1)
  209. }
  210. workCtx, stopWork := context.WithCancel(context.Background())
  211. defer stopWork()
  212. workWaitGroup := new(sync.WaitGroup)
  213. workWaitGroup.Add(1)
  214. go func() {
  215. defer workWaitGroup.Done()
  216. err := worker.Run(workCtx)
  217. if err != nil {
  218. psiphon.NoticeError("%s", err)
  219. stopWork()
  220. os.Exit(1)
  221. }
  222. // Signal the <-controllerCtx.Done() case below. If the <-systemStopSignal
  223. // case already called stopController, this is a noop.
  224. stopWork()
  225. }()
  226. systemStopSignal := make(chan os.Signal, 1)
  227. signal.Notify(systemStopSignal, os.Interrupt, syscall.SIGTERM)
  228. // writeProfilesSignal is nil and non-functional on Windows
  229. writeProfilesSignal := makeSIGUSR2Channel()
  230. // Wait for an OS signal or a Run stop signal, then stop Psiphon and exit
  231. for exit := false; !exit; {
  232. select {
  233. case <-writeProfilesSignal:
  234. psiphon.NoticeInfo("write profiles")
  235. profileSampleDurationSeconds := 5
  236. common.WriteRuntimeProfiles(
  237. psiphon.NoticeCommonLogger(),
  238. config.DataRootDirectory,
  239. "",
  240. profileSampleDurationSeconds,
  241. profileSampleDurationSeconds)
  242. case <-systemStopSignal:
  243. psiphon.NoticeInfo("shutdown by system")
  244. stopWork()
  245. workWaitGroup.Wait()
  246. exit = true
  247. case <-workCtx.Done():
  248. psiphon.NoticeInfo("shutdown by controller")
  249. exit = true
  250. }
  251. }
  252. }
  253. func configurePacketTunnel(
  254. config *psiphon.Config,
  255. tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS string) (*os.File, error) {
  256. file, _, err := tun.OpenTunDevice(tunDevice)
  257. if err != nil {
  258. return nil, errors.Trace(err)
  259. }
  260. provider := &tunProvider{
  261. bindInterface: tunBindInterface,
  262. primaryDNS: tunPrimaryDNS,
  263. secondaryDNS: tunSecondaryDNS,
  264. }
  265. config.PacketTunnelTunFileDescriptor = int(file.Fd())
  266. config.DeviceBinder = provider
  267. config.DnsServerGetter = provider
  268. return file, nil
  269. }
  270. type tunProvider struct {
  271. bindInterface string
  272. primaryDNS string
  273. secondaryDNS string
  274. }
  275. // BindToDevice implements the psiphon.DeviceBinder interface.
  276. func (p *tunProvider) BindToDevice(fileDescriptor int) (string, error) {
  277. return p.bindInterface, tun.BindToDevice(fileDescriptor, p.bindInterface)
  278. }
  279. // GetPrimaryDnsServer implements the psiphon.DnsServerGetter interface.
  280. func (p *tunProvider) GetPrimaryDnsServer() string {
  281. return p.primaryDNS
  282. }
  283. // GetSecondaryDnsServer implements the psiphon.DnsServerGetter interface.
  284. func (p *tunProvider) GetSecondaryDnsServer() string {
  285. return p.secondaryDNS
  286. }
  287. // Worker creates a protocol around the different run modes provided by the
  288. // compiled executable.
  289. type Worker interface {
  290. // Init is called once for the worker to perform any initialization.
  291. Init(config *psiphon.Config) error
  292. // Run is called once, after Init(..), for the worker to perform its
  293. // work. The provided context should control the lifetime of the work
  294. // being performed.
  295. Run(ctx context.Context) error
  296. }
  297. // TunnelWorker is the Worker protocol implementation used for tunnel mode.
  298. type TunnelWorker struct {
  299. embeddedServerEntryListFilename string
  300. controller *psiphon.Controller
  301. }
  302. // Init implements the Worker interface.
  303. func (w *TunnelWorker) Init(config *psiphon.Config) error {
  304. // Initialize data store
  305. err := psiphon.OpenDataStore(config)
  306. if err != nil {
  307. psiphon.NoticeError("error initializing datastore: %s", err)
  308. os.Exit(1)
  309. }
  310. // Handle optional embedded server list file parameter
  311. // If specified, the embedded server list is loaded and stored. When there
  312. // are no server candidates at all, we wait for this import to complete
  313. // before starting the Psiphon controller. Otherwise, we import while
  314. // concurrently starting the controller to minimize delay before attempting
  315. // to connect to existing candidate servers.
  316. // If the import fails, an error notice is emitted, but the controller is
  317. // still started: either existing candidate servers may suffice, or the
  318. // remote server list fetch may obtain candidate servers.
  319. if w.embeddedServerEntryListFilename != "" {
  320. embeddedServerListWaitGroup := new(sync.WaitGroup)
  321. embeddedServerListWaitGroup.Add(1)
  322. go func() {
  323. defer embeddedServerListWaitGroup.Done()
  324. serverEntryList, err := ioutil.ReadFile(w.embeddedServerEntryListFilename)
  325. if err != nil {
  326. psiphon.NoticeError("error loading embedded server entry list file: %s", err)
  327. return
  328. }
  329. // TODO: stream embedded server list data? also, the cast makes an unnecessary copy of a large buffer?
  330. serverEntries, err := protocol.DecodeServerEntryList(
  331. string(serverEntryList),
  332. common.GetCurrentTimestamp(),
  333. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  334. if err != nil {
  335. psiphon.NoticeError("error decoding embedded server entry list file: %s", err)
  336. return
  337. }
  338. // Since embedded server list entries may become stale, they will not
  339. // overwrite existing stored entries for the same server.
  340. err = psiphon.StoreServerEntries(config, serverEntries, false)
  341. if err != nil {
  342. psiphon.NoticeError("error storing embedded server entry list data: %s", err)
  343. return
  344. }
  345. }()
  346. if psiphon.CountServerEntries() == 0 {
  347. embeddedServerListWaitGroup.Wait()
  348. } else {
  349. defer embeddedServerListWaitGroup.Wait()
  350. }
  351. }
  352. controller, err := psiphon.NewController(config)
  353. if err != nil {
  354. psiphon.NoticeError("error creating controller: %s", err)
  355. return errors.Trace(err)
  356. }
  357. w.controller = controller
  358. return nil
  359. }
  360. // Run implements the Worker interface.
  361. func (w *TunnelWorker) Run(ctx context.Context) error {
  362. defer psiphon.CloseDataStore()
  363. w.controller.Run(ctx)
  364. return nil
  365. }
  366. // FeedbackWorker is the Worker protocol implementation used for feedback
  367. // upload mode.
  368. type FeedbackWorker struct {
  369. config *psiphon.Config
  370. feedbackUploadPath string
  371. }
  372. // Init implements the Worker interface.
  373. func (f *FeedbackWorker) Init(config *psiphon.Config) error {
  374. // The datastore is not opened here, with psiphon.OpenDatastore,
  375. // because it is opened/closed transiently in the psiphon.SendFeedback
  376. // operation. We do not want to contest database access incase another
  377. // process needs to use the database. E.g. a process running in tunnel
  378. // mode, which will fail if it cannot aquire a lock on the database
  379. // within a short period of time.
  380. f.config = config
  381. return nil
  382. }
  383. // Run implements the Worker interface.
  384. func (f *FeedbackWorker) Run(ctx context.Context) error {
  385. // TODO: cancel blocking read when worker context cancelled?
  386. diagnostics, err := ioutil.ReadAll(os.Stdin)
  387. if err != nil {
  388. return errors.TraceMsg(err, "FeedbackUpload: read stdin failed")
  389. }
  390. if len(diagnostics) == 0 {
  391. return errors.TraceNew("FeedbackUpload: error zero bytes of diagnostics read from stdin")
  392. }
  393. err = psiphon.SendFeedback(ctx, f.config, string(diagnostics), f.feedbackUploadPath)
  394. if err != nil {
  395. return errors.TraceMsg(err, "FeedbackUpload: upload failed")
  396. }
  397. psiphon.NoticeInfo("FeedbackUpload: upload succeeded")
  398. return nil
  399. }