main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. "runtime/pprof"
  31. "sort"
  32. "sync"
  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/parameters"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  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 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 profileFilename string
  48. flag.StringVar(&profileFilename, "profile", "", "CPU profile output file")
  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 tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS string
  55. if tun.IsSupported() {
  56. // When tunDevice is specified, a packet tunnel is run and packets are relayed between
  57. // the specified tun device and the server.
  58. //
  59. // The tun device is expected to exist and should be configured with an IP address and
  60. // routing.
  61. //
  62. // The tunBindInterface/tunPrimaryDNS/tunSecondaryDNS parameters are used to bypass any
  63. // tun device routing when connecting to Psiphon servers.
  64. //
  65. // For transparent tunneled DNS, set the host or DNS clients to use the address specfied
  66. // in tun.GetTransparentDNSResolverIPv4Address().
  67. //
  68. // Packet tunnel mode is supported only on certains platforms.
  69. flag.StringVar(&tunDevice, "tunDevice", "", "run packet tunnel for specified tun device")
  70. flag.StringVar(&tunBindInterface, "tunBindInterface", tun.DEFAULT_PUBLIC_INTERFACE_NAME, "bypass tun device via specified interface")
  71. flag.StringVar(&tunPrimaryDNS, "tunPrimaryDNS", "8.8.8.8", "primary DNS resolver for bypass")
  72. flag.StringVar(&tunSecondaryDNS, "tunSecondaryDNS", "8.8.4.4", "secondary DNS resolver for bypass")
  73. }
  74. var noticeFilename string
  75. flag.StringVar(&noticeFilename, "notices", "", "notices output file (defaults to stderr)")
  76. var homepageFilename string
  77. flag.StringVar(&homepageFilename, "homepages", "", "homepages notices output file")
  78. var rotatingFilename string
  79. flag.StringVar(&rotatingFilename, "rotating", "", "rotating notices output file")
  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 := common.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. err := psiphon.SetNoticeFiles(
  127. homepageFilename,
  128. rotatingFilename,
  129. rotatingFileSize,
  130. rotatingSyncFrequency)
  131. if err != nil {
  132. fmt.Printf("error initializing notice files: %s\n", err)
  133. os.Exit(1)
  134. }
  135. // Handle required config file parameter
  136. // EmitDiagnosticNotices is set by LoadConfig; force to true
  137. // an emit diagnostics when LoadConfig-related errors occur.
  138. if configFilename == "" {
  139. psiphon.SetEmitDiagnosticNotices(true)
  140. psiphon.NoticeError("configuration file is required")
  141. os.Exit(1)
  142. }
  143. configFileContents, err := ioutil.ReadFile(configFilename)
  144. if err != nil {
  145. psiphon.SetEmitDiagnosticNotices(true)
  146. psiphon.NoticeError("error loading configuration file: %s", err)
  147. os.Exit(1)
  148. }
  149. config, err := psiphon.LoadConfig(configFileContents)
  150. if err != nil {
  151. psiphon.SetEmitDiagnosticNotices(true)
  152. psiphon.NoticeError("error processing configuration file: %s", err)
  153. os.Exit(1)
  154. }
  155. if interfaceName != "" {
  156. config.ListenInterface = interfaceName
  157. }
  158. // Configure packet tunnel, including updating the config.
  159. if tun.IsSupported() && tunDevice != "" {
  160. tunDeviceFile, err := configurePacketTunnel(
  161. config, tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS)
  162. if err != nil {
  163. psiphon.SetEmitDiagnosticNotices(true)
  164. psiphon.NoticeError("error configuring packet tunnel: %s", err)
  165. os.Exit(1)
  166. }
  167. defer tunDeviceFile.Close()
  168. }
  169. // All config fields should be set before calling Commit.
  170. err = config.Commit()
  171. if err != nil {
  172. psiphon.SetEmitDiagnosticNotices(true)
  173. psiphon.NoticeError("error loading configuration file: %s", err)
  174. os.Exit(1)
  175. }
  176. // BuildInfo is a diagnostic notice, so emit only after config.Commit
  177. // sets EmitDiagnosticNotices.
  178. psiphon.NoticeBuildInfo()
  179. // Handle optional profiling parameter
  180. if profileFilename != "" {
  181. profileFile, err := os.Create(profileFilename)
  182. if err != nil {
  183. psiphon.NoticeError("error opening profile file: %s", err)
  184. os.Exit(1)
  185. }
  186. pprof.StartCPUProfile(profileFile)
  187. defer pprof.StopCPUProfile()
  188. }
  189. // Initialize data store
  190. err = psiphon.InitDataStore(config)
  191. if err != nil {
  192. psiphon.NoticeError("error initializing datastore: %s", err)
  193. os.Exit(1)
  194. }
  195. // Handle optional embedded server list file parameter
  196. // If specified, the embedded server list is loaded and stored. When there
  197. // are no server candidates at all, we wait for this import to complete
  198. // before starting the Psiphon controller. Otherwise, we import while
  199. // concurrently starting the controller to minimize delay before attempting
  200. // to connect to existing candidate servers.
  201. // If the import fails, an error notice is emitted, but the controller is
  202. // still started: either existing candidate servers may suffice, or the
  203. // remote server list fetch may obtain candidate servers.
  204. if embeddedServerEntryListFilename != "" {
  205. embeddedServerListWaitGroup := new(sync.WaitGroup)
  206. embeddedServerListWaitGroup.Add(1)
  207. go func() {
  208. defer embeddedServerListWaitGroup.Done()
  209. serverEntryList, err := ioutil.ReadFile(embeddedServerEntryListFilename)
  210. if err != nil {
  211. psiphon.NoticeError("error loading embedded server entry list file: %s", err)
  212. return
  213. }
  214. // TODO: stream embedded server list data? also, the cast makes an unnecessary copy of a large buffer?
  215. serverEntries, err := protocol.DecodeServerEntryList(
  216. string(serverEntryList),
  217. common.GetCurrentTimestamp(),
  218. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  219. if err != nil {
  220. psiphon.NoticeError("error decoding embedded server entry list file: %s", err)
  221. return
  222. }
  223. // Since embedded server list entries may become stale, they will not
  224. // overwrite existing stored entries for the same server.
  225. err = psiphon.StoreServerEntries(config, serverEntries, false)
  226. if err != nil {
  227. psiphon.NoticeError("error storing embedded server entry list data: %s", err)
  228. return
  229. }
  230. }()
  231. limitTunnelProtocols := config.GetClientParameters().TunnelProtocols(parameters.LimitTunnelProtocols)
  232. if psiphon.CountServerEntries(config.EgressRegion, limitTunnelProtocols) == 0 {
  233. embeddedServerListWaitGroup.Wait()
  234. } else {
  235. defer embeddedServerListWaitGroup.Wait()
  236. }
  237. }
  238. // Run Psiphon
  239. controller, err := psiphon.NewController(config)
  240. if err != nil {
  241. psiphon.NoticeError("error creating controller: %s", err)
  242. os.Exit(1)
  243. }
  244. controllerCtx, stopController := context.WithCancel(context.Background())
  245. defer stopController()
  246. controllerWaitGroup := new(sync.WaitGroup)
  247. controllerWaitGroup.Add(1)
  248. go func() {
  249. defer controllerWaitGroup.Done()
  250. controller.Run(controllerCtx)
  251. // Signal the <-controllerCtx.Done() case below. If the <-systemStopSignal
  252. // case already called stopController, this is a noop.
  253. stopController()
  254. }()
  255. systemStopSignal := make(chan os.Signal, 1)
  256. signal.Notify(systemStopSignal, os.Interrupt, os.Kill)
  257. // Wait for an OS signal or a Run stop signal, then stop Psiphon and exit
  258. select {
  259. case <-systemStopSignal:
  260. psiphon.NoticeInfo("shutdown by system")
  261. stopController()
  262. controllerWaitGroup.Wait()
  263. case <-controllerCtx.Done():
  264. psiphon.NoticeInfo("shutdown by controller")
  265. }
  266. }
  267. func configurePacketTunnel(
  268. config *psiphon.Config,
  269. tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS string) (*os.File, error) {
  270. file, _, err := tun.OpenTunDevice(tunDevice)
  271. if err != nil {
  272. return nil, common.ContextError(err)
  273. }
  274. provider := &tunProvider{
  275. bindInterface: tunBindInterface,
  276. primaryDNS: tunPrimaryDNS,
  277. secondaryDNS: tunSecondaryDNS,
  278. }
  279. config.PacketTunnelTunFileDescriptor = int(file.Fd())
  280. config.DeviceBinder = provider
  281. config.DnsServerGetter = provider
  282. return file, nil
  283. }
  284. type tunProvider struct {
  285. bindInterface string
  286. primaryDNS string
  287. secondaryDNS string
  288. }
  289. // BindToDevice implements the psiphon.DeviceBinder interface.
  290. func (p *tunProvider) BindToDevice(fileDescriptor int) (string, error) {
  291. return p.bindInterface, tun.BindToDevice(fileDescriptor, p.bindInterface)
  292. }
  293. // GetPrimaryDnsServer implements the psiphon.DnsServerGetter interface.
  294. func (p *tunProvider) GetPrimaryDnsServer() string {
  295. return p.primaryDNS
  296. }
  297. // GetSecondaryDnsServer implements the psiphon.DnsServerGetter interface.
  298. func (p *tunProvider) GetSecondaryDnsServer() string {
  299. return p.secondaryDNS
  300. }