main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS string
  56. if tun.IsSupported() {
  57. // When tunDevice is specified, a packet tunnel is run and packets are relayed between
  58. // the specified tun device and the server.
  59. //
  60. // The tun device is expected to exist and should be configured with an IP address and
  61. // routing.
  62. //
  63. // The tunBindInterface/tunPrimaryDNS/tunSecondaryDNS parameters are used to bypass any
  64. // tun device routing when connecting to Psiphon servers.
  65. //
  66. // For transparent tunneled DNS, set the host or DNS clients to use the address specfied
  67. // in tun.GetTransparentDNSResolverIPv4Address().
  68. //
  69. // Packet tunnel mode is supported only on certains platforms.
  70. flag.StringVar(&tunDevice, "tunDevice", "", "run packet tunnel for specified tun device")
  71. flag.StringVar(&tunBindInterface, "tunBindInterface", tun.DEFAULT_PUBLIC_INTERFACE_NAME, "bypass tun device via specified interface")
  72. flag.StringVar(&tunPrimaryDNS, "tunPrimaryDNS", "8.8.8.8", "primary DNS resolver for bypass")
  73. flag.StringVar(&tunSecondaryDNS, "tunSecondaryDNS", "8.8.4.4", "secondary DNS resolver for bypass")
  74. }
  75. var noticeFilename string
  76. flag.StringVar(&noticeFilename, "notices", "", "notices output file (defaults to stderr)")
  77. var useNoticeFiles bool
  78. useNoticeFilesUsage := fmt.Sprintf("output homepage notices and rotating notices to <dataRootDirectory>/%s and <dataRootDirectory>/%s respectively", psiphon.HomepageFilename, psiphon.NoticesFilename)
  79. flag.BoolVar(&useNoticeFiles, "useNoticeFiles", false, useNoticeFilesUsage)
  80. var rotatingFileSize int
  81. flag.IntVar(&rotatingFileSize, "rotatingFileSize", 1<<20, "rotating notices file size")
  82. var rotatingSyncFrequency int
  83. flag.IntVar(&rotatingSyncFrequency, "rotatingSyncFrequency", 100, "rotating notices file sync frequency")
  84. flag.Parse()
  85. if versionDetails {
  86. b := buildinfo.GetBuildInfo()
  87. var printableDependencies bytes.Buffer
  88. var dependencyMap map[string]string
  89. longestRepoUrl := 0
  90. json.Unmarshal(b.Dependencies, &dependencyMap)
  91. sortedRepoUrls := make([]string, 0, len(dependencyMap))
  92. for repoUrl := range dependencyMap {
  93. repoUrlLength := len(repoUrl)
  94. if repoUrlLength > longestRepoUrl {
  95. longestRepoUrl = repoUrlLength
  96. }
  97. sortedRepoUrls = append(sortedRepoUrls, repoUrl)
  98. }
  99. sort.Strings(sortedRepoUrls)
  100. for repoUrl := range sortedRepoUrls {
  101. printableDependencies.WriteString(fmt.Sprintf(" %s ", sortedRepoUrls[repoUrl]))
  102. for i := 0; i < (longestRepoUrl - len(sortedRepoUrls[repoUrl])); i++ {
  103. printableDependencies.WriteString(" ")
  104. }
  105. printableDependencies.WriteString(fmt.Sprintf("%s\n", dependencyMap[sortedRepoUrls[repoUrl]]))
  106. }
  107. 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())
  108. os.Exit(0)
  109. }
  110. // Initialize notice output
  111. var noticeWriter io.Writer
  112. noticeWriter = os.Stderr
  113. if noticeFilename != "" {
  114. noticeFile, err := os.OpenFile(noticeFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  115. if err != nil {
  116. fmt.Printf("error opening notice file: %s\n", err)
  117. os.Exit(1)
  118. }
  119. defer noticeFile.Close()
  120. noticeWriter = noticeFile
  121. }
  122. if formatNotices {
  123. noticeWriter = psiphon.NewNoticeConsoleRewriter(noticeWriter)
  124. }
  125. psiphon.SetNoticeWriter(noticeWriter)
  126. // Handle required config file parameter
  127. // EmitDiagnosticNotices is set by LoadConfig; force to true
  128. // and emit diagnostics when LoadConfig-related errors occur.
  129. if configFilename == "" {
  130. psiphon.SetEmitDiagnosticNotices(true, false)
  131. psiphon.NoticeError("configuration file is required")
  132. os.Exit(1)
  133. }
  134. configFileContents, err := ioutil.ReadFile(configFilename)
  135. if err != nil {
  136. psiphon.SetEmitDiagnosticNotices(true, false)
  137. psiphon.NoticeError("error loading configuration file: %s", err)
  138. os.Exit(1)
  139. }
  140. config, err := psiphon.LoadConfig(configFileContents)
  141. if err != nil {
  142. psiphon.SetEmitDiagnosticNotices(true, false)
  143. psiphon.NoticeError("error processing configuration file: %s", err)
  144. os.Exit(1)
  145. }
  146. // Set data root directory
  147. if dataRootDirectory != "" {
  148. config.DataRootDirectory = dataRootDirectory
  149. }
  150. if interfaceName != "" {
  151. config.ListenInterface = interfaceName
  152. }
  153. // Configure notice files
  154. if useNoticeFiles {
  155. config.UseNoticeFiles = &psiphon.UseNoticeFiles{
  156. RotatingFileSize: rotatingFileSize,
  157. RotatingSyncFrequency: rotatingSyncFrequency,
  158. }
  159. }
  160. // Configure packet tunnel, including updating the config.
  161. if tun.IsSupported() && tunDevice != "" {
  162. tunDeviceFile, err := configurePacketTunnel(
  163. config, tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS)
  164. if err != nil {
  165. psiphon.SetEmitDiagnosticNotices(true, false)
  166. psiphon.NoticeError("error configuring packet tunnel: %s", err)
  167. os.Exit(1)
  168. }
  169. defer tunDeviceFile.Close()
  170. }
  171. // All config fields should be set before calling Commit.
  172. err = config.Commit(true)
  173. if err != nil {
  174. psiphon.SetEmitDiagnosticNotices(true, false)
  175. psiphon.NoticeError("error loading configuration file: %s", err)
  176. os.Exit(1)
  177. }
  178. // BuildInfo is a diagnostic notice, so emit only after config.Commit
  179. // sets EmitDiagnosticNotices.
  180. psiphon.NoticeBuildInfo()
  181. // Initialize data store
  182. err = psiphon.OpenDataStore(config)
  183. if err != nil {
  184. psiphon.NoticeError("error initializing datastore: %s", err)
  185. os.Exit(1)
  186. }
  187. defer psiphon.CloseDataStore()
  188. // Handle optional embedded server list file parameter
  189. // If specified, the embedded server list is loaded and stored. When there
  190. // are no server candidates at all, we wait for this import to complete
  191. // before starting the Psiphon controller. Otherwise, we import while
  192. // concurrently starting the controller to minimize delay before attempting
  193. // to connect to existing candidate servers.
  194. // If the import fails, an error notice is emitted, but the controller is
  195. // still started: either existing candidate servers may suffice, or the
  196. // remote server list fetch may obtain candidate servers.
  197. if embeddedServerEntryListFilename != "" {
  198. embeddedServerListWaitGroup := new(sync.WaitGroup)
  199. embeddedServerListWaitGroup.Add(1)
  200. go func() {
  201. defer embeddedServerListWaitGroup.Done()
  202. serverEntryList, err := ioutil.ReadFile(embeddedServerEntryListFilename)
  203. if err != nil {
  204. psiphon.NoticeError("error loading embedded server entry list file: %s", err)
  205. return
  206. }
  207. // TODO: stream embedded server list data? also, the cast makes an unnecessary copy of a large buffer?
  208. serverEntries, err := protocol.DecodeServerEntryList(
  209. string(serverEntryList),
  210. common.GetCurrentTimestamp(),
  211. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  212. if err != nil {
  213. psiphon.NoticeError("error decoding embedded server entry list file: %s", err)
  214. return
  215. }
  216. // Since embedded server list entries may become stale, they will not
  217. // overwrite existing stored entries for the same server.
  218. err = psiphon.StoreServerEntries(config, serverEntries, false)
  219. if err != nil {
  220. psiphon.NoticeError("error storing embedded server entry list data: %s", err)
  221. return
  222. }
  223. }()
  224. if psiphon.CountServerEntries() == 0 {
  225. embeddedServerListWaitGroup.Wait()
  226. } else {
  227. defer embeddedServerListWaitGroup.Wait()
  228. }
  229. }
  230. // Run Psiphon
  231. controller, err := psiphon.NewController(config)
  232. if err != nil {
  233. psiphon.NoticeError("error creating controller: %s", err)
  234. os.Exit(1)
  235. }
  236. controllerCtx, stopController := context.WithCancel(context.Background())
  237. defer stopController()
  238. controllerWaitGroup := new(sync.WaitGroup)
  239. controllerWaitGroup.Add(1)
  240. go func() {
  241. defer controllerWaitGroup.Done()
  242. controller.Run(controllerCtx)
  243. // Signal the <-controllerCtx.Done() case below. If the <-systemStopSignal
  244. // case already called stopController, this is a noop.
  245. stopController()
  246. }()
  247. systemStopSignal := make(chan os.Signal, 1)
  248. signal.Notify(systemStopSignal, os.Interrupt, syscall.SIGTERM)
  249. // writeProfilesSignal is nil and non-functional on Windows
  250. writeProfilesSignal := makeSIGUSR2Channel()
  251. // Wait for an OS signal or a Run stop signal, then stop Psiphon and exit
  252. for exit := false; !exit; {
  253. select {
  254. case <-writeProfilesSignal:
  255. psiphon.NoticeInfo("write profiles")
  256. profileSampleDurationSeconds := 5
  257. common.WriteRuntimeProfiles(
  258. psiphon.NoticeCommonLogger(),
  259. config.DataRootDirectory,
  260. "",
  261. profileSampleDurationSeconds,
  262. profileSampleDurationSeconds)
  263. case <-systemStopSignal:
  264. psiphon.NoticeInfo("shutdown by system")
  265. stopController()
  266. controllerWaitGroup.Wait()
  267. exit = true
  268. case <-controllerCtx.Done():
  269. psiphon.NoticeInfo("shutdown by controller")
  270. exit = true
  271. }
  272. }
  273. }
  274. func configurePacketTunnel(
  275. config *psiphon.Config,
  276. tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS string) (*os.File, error) {
  277. file, _, err := tun.OpenTunDevice(tunDevice)
  278. if err != nil {
  279. return nil, errors.Trace(err)
  280. }
  281. provider := &tunProvider{
  282. bindInterface: tunBindInterface,
  283. primaryDNS: tunPrimaryDNS,
  284. secondaryDNS: tunSecondaryDNS,
  285. }
  286. config.PacketTunnelTunFileDescriptor = int(file.Fd())
  287. config.DeviceBinder = provider
  288. config.DnsServerGetter = provider
  289. return file, nil
  290. }
  291. type tunProvider struct {
  292. bindInterface string
  293. primaryDNS string
  294. secondaryDNS string
  295. }
  296. // BindToDevice implements the psiphon.DeviceBinder interface.
  297. func (p *tunProvider) BindToDevice(fileDescriptor int) (string, error) {
  298. return p.bindInterface, tun.BindToDevice(fileDescriptor, p.bindInterface)
  299. }
  300. // GetPrimaryDnsServer implements the psiphon.DnsServerGetter interface.
  301. func (p *tunProvider) GetPrimaryDnsServer() string {
  302. return p.primaryDNS
  303. }
  304. // GetSecondaryDnsServer implements the psiphon.DnsServerGetter interface.
  305. func (p *tunProvider) GetSecondaryDnsServer() string {
  306. return p.secondaryDNS
  307. }