main.go 15 KB

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