main.go 14 KB

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