main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. psiphon.SetNoticeWriter(noticeWriter)
  116. // Handle required config file parameter
  117. // EmitDiagnosticNotices is set by LoadConfig; force to true
  118. // and emit diagnostics when LoadConfig-related errors occur.
  119. if configFilename == "" {
  120. psiphon.SetEmitDiagnosticNotices(true, false)
  121. psiphon.NoticeError("configuration file is required")
  122. os.Exit(1)
  123. }
  124. configFileContents, err := ioutil.ReadFile(configFilename)
  125. if err != nil {
  126. psiphon.SetEmitDiagnosticNotices(true, false)
  127. psiphon.NoticeError("error loading configuration file: %s", err)
  128. os.Exit(1)
  129. }
  130. config, err := psiphon.LoadConfig(configFileContents)
  131. if err != nil {
  132. psiphon.SetEmitDiagnosticNotices(true, false)
  133. psiphon.NoticeError("error processing configuration file: %s", err)
  134. os.Exit(1)
  135. }
  136. // Set data root directory
  137. if dataRootDirectory != "" {
  138. config.DataRootDirectory = dataRootDirectory
  139. }
  140. if interfaceName != "" {
  141. config.ListenInterface = interfaceName
  142. }
  143. // Configure notice files
  144. if useNoticeFiles {
  145. config.UseNoticeFiles = &psiphon.UseNoticeFiles{
  146. RotatingFileSize: rotatingFileSize,
  147. RotatingSyncFrequency: rotatingSyncFrequency,
  148. }
  149. }
  150. // Configure packet tunnel, including updating the config.
  151. if tun.IsSupported() && tunDevice != "" {
  152. tunDeviceFile, err := configurePacketTunnel(
  153. config, tunDevice, tunBindInterface, strings.Split(tunDNSServers, ","))
  154. if err != nil {
  155. psiphon.SetEmitDiagnosticNotices(true, false)
  156. psiphon.NoticeError("error configuring packet tunnel: %s", err)
  157. os.Exit(1)
  158. }
  159. defer tunDeviceFile.Close()
  160. }
  161. // All config fields should be set before calling Commit.
  162. err = config.Commit(true)
  163. if err != nil {
  164. psiphon.SetEmitDiagnosticNotices(true, false)
  165. psiphon.NoticeError("error loading configuration file: %s", err)
  166. os.Exit(1)
  167. }
  168. // BuildInfo is a diagnostic notice, so emit only after config.Commit
  169. // sets EmitDiagnosticNotices.
  170. psiphon.NoticeBuildInfo()
  171. var worker Worker
  172. if feedbackUpload {
  173. // Feedback upload mode
  174. worker = &FeedbackWorker{
  175. feedbackUploadPath: feedbackUploadPath,
  176. }
  177. } else {
  178. // Tunnel mode
  179. worker = &TunnelWorker{
  180. embeddedServerEntryListFilename: embeddedServerEntryListFilename,
  181. }
  182. }
  183. workCtx, stopWork := context.WithCancel(context.Background())
  184. defer stopWork()
  185. err = worker.Init(workCtx, config)
  186. if err != nil {
  187. psiphon.NoticeError("error in init: %s", err)
  188. os.Exit(1)
  189. }
  190. workWaitGroup := new(sync.WaitGroup)
  191. workWaitGroup.Add(1)
  192. go func() {
  193. defer workWaitGroup.Done()
  194. err := worker.Run(workCtx)
  195. if err != nil {
  196. psiphon.NoticeError("%s", err)
  197. stopWork()
  198. os.Exit(1)
  199. }
  200. // Signal the <-controllerCtx.Done() case below. If the <-systemStopSignal
  201. // case already called stopController, this is a noop.
  202. stopWork()
  203. }()
  204. systemStopSignal := make(chan os.Signal, 1)
  205. signal.Notify(systemStopSignal, os.Interrupt, syscall.SIGTERM)
  206. // writeProfilesSignal is nil and non-functional on Windows
  207. writeProfilesSignal := makeSIGUSR2Channel()
  208. // Wait for an OS signal or a Run stop signal, then stop Psiphon and exit
  209. for exit := false; !exit; {
  210. select {
  211. case <-writeProfilesSignal:
  212. psiphon.NoticeInfo("write profiles")
  213. profileSampleDurationSeconds := 5
  214. common.WriteRuntimeProfiles(
  215. psiphon.NoticeCommonLogger(),
  216. config.DataRootDirectory,
  217. "",
  218. profileSampleDurationSeconds,
  219. profileSampleDurationSeconds)
  220. case <-systemStopSignal:
  221. psiphon.NoticeInfo("shutdown by system")
  222. stopWork()
  223. workWaitGroup.Wait()
  224. exit = true
  225. case <-workCtx.Done():
  226. psiphon.NoticeInfo("shutdown by controller")
  227. exit = true
  228. }
  229. }
  230. }
  231. func configurePacketTunnel(
  232. config *psiphon.Config,
  233. tunDevice string,
  234. tunBindInterface string,
  235. tunDNSServers []string) (*os.File, error) {
  236. file, _, err := tun.OpenTunDevice(tunDevice)
  237. if err != nil {
  238. return nil, errors.Trace(err)
  239. }
  240. provider := &tunProvider{
  241. bindInterface: tunBindInterface,
  242. dnsServers: tunDNSServers,
  243. }
  244. config.PacketTunnelTunFileDescriptor = int(file.Fd())
  245. config.DeviceBinder = provider
  246. config.DNSServerGetter = provider
  247. return file, nil
  248. }
  249. type tunProvider struct {
  250. bindInterface string
  251. dnsServers []string
  252. }
  253. // BindToDevice implements the psiphon.DeviceBinder interface.
  254. func (p *tunProvider) BindToDevice(fileDescriptor int) (string, error) {
  255. return p.bindInterface, tun.BindToDevice(fileDescriptor, p.bindInterface)
  256. }
  257. // GetDNSServers implements the psiphon.DNSServerGetter interface.
  258. func (p *tunProvider) GetDNSServers() []string {
  259. return p.dnsServers
  260. }
  261. // Worker creates a protocol around the different run modes provided by the
  262. // compiled executable.
  263. type Worker interface {
  264. // Init is called once for the worker to perform any initialization.
  265. Init(ctx context.Context, config *psiphon.Config) error
  266. // Run is called once, after Init(..), for the worker to perform its
  267. // work. The provided context should control the lifetime of the work
  268. // being performed.
  269. Run(ctx context.Context) error
  270. }
  271. // TunnelWorker is the Worker protocol implementation used for tunnel mode.
  272. type TunnelWorker struct {
  273. embeddedServerEntryListFilename string
  274. embeddedServerListWaitGroup *sync.WaitGroup
  275. controller *psiphon.Controller
  276. }
  277. // Init implements the Worker interface.
  278. func (w *TunnelWorker) Init(ctx context.Context, config *psiphon.Config) error {
  279. // Initialize data store
  280. err := psiphon.OpenDataStore(config)
  281. if err != nil {
  282. psiphon.NoticeError("error initializing datastore: %s", err)
  283. os.Exit(1)
  284. }
  285. // If specified, the embedded server list is loaded and stored. When there
  286. // are no server candidates at all, we wait for this import to complete
  287. // before starting the Psiphon controller. Otherwise, we import while
  288. // concurrently starting the controller to minimize delay before attempting
  289. // to connect to existing candidate servers.
  290. //
  291. // If the import fails, an error notice is emitted, but the controller is
  292. // still started: either existing candidate servers may suffice, or the
  293. // remote server list fetch may obtain candidate servers.
  294. //
  295. // The import will be interrupted if it's still running when the controller
  296. // is stopped.
  297. if w.embeddedServerEntryListFilename != "" {
  298. w.embeddedServerListWaitGroup = new(sync.WaitGroup)
  299. w.embeddedServerListWaitGroup.Add(1)
  300. go func() {
  301. defer w.embeddedServerListWaitGroup.Done()
  302. err := psiphon.ImportEmbeddedServerEntries(
  303. ctx,
  304. config,
  305. w.embeddedServerEntryListFilename,
  306. "")
  307. if err != nil {
  308. psiphon.NoticeError("error importing embedded server entry list: %s", err)
  309. return
  310. }
  311. }()
  312. if !psiphon.HasServerEntries() {
  313. psiphon.NoticeInfo("awaiting embedded server entry list import")
  314. w.embeddedServerListWaitGroup.Wait()
  315. }
  316. }
  317. controller, err := psiphon.NewController(config)
  318. if err != nil {
  319. psiphon.NoticeError("error creating controller: %s", err)
  320. return errors.Trace(err)
  321. }
  322. w.controller = controller
  323. return nil
  324. }
  325. // Run implements the Worker interface.
  326. func (w *TunnelWorker) Run(ctx context.Context) error {
  327. defer psiphon.CloseDataStore()
  328. if w.embeddedServerListWaitGroup != nil {
  329. defer w.embeddedServerListWaitGroup.Wait()
  330. }
  331. w.controller.Run(ctx)
  332. return nil
  333. }
  334. // FeedbackWorker is the Worker protocol implementation used for feedback
  335. // upload mode.
  336. type FeedbackWorker struct {
  337. config *psiphon.Config
  338. feedbackUploadPath string
  339. }
  340. // Init implements the Worker interface.
  341. func (f *FeedbackWorker) Init(ctx context.Context, config *psiphon.Config) error {
  342. // The datastore is not opened here, with psiphon.OpenDatastore,
  343. // because it is opened/closed transiently in the psiphon.SendFeedback
  344. // operation. We do not want to contest database access incase another
  345. // process needs to use the database. E.g. a process running in tunnel
  346. // mode, which will fail if it cannot aquire a lock on the database
  347. // within a short period of time.
  348. f.config = config
  349. return nil
  350. }
  351. // Run implements the Worker interface.
  352. func (f *FeedbackWorker) Run(ctx context.Context) error {
  353. // TODO: cancel blocking read when worker context cancelled?
  354. diagnostics, err := ioutil.ReadAll(os.Stdin)
  355. if err != nil {
  356. return errors.TraceMsg(err, "FeedbackUpload: read stdin failed")
  357. }
  358. if len(diagnostics) == 0 {
  359. return errors.TraceNew("FeedbackUpload: error zero bytes of diagnostics read from stdin")
  360. }
  361. err = psiphon.SendFeedback(ctx, f.config, string(diagnostics), f.feedbackUploadPath)
  362. if err != nil {
  363. return errors.TraceMsg(err, "FeedbackUpload: upload failed")
  364. }
  365. psiphon.NoticeInfo("FeedbackUpload: upload succeeded")
  366. return nil
  367. }