main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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/protocol"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  37. )
  38. func main() {
  39. // Define command-line parameters
  40. var configFilename string
  41. flag.StringVar(&configFilename, "config", "", "configuration input file")
  42. var embeddedServerEntryListFilename string
  43. flag.StringVar(&embeddedServerEntryListFilename, "serverList", "", "embedded server entry list input file")
  44. var formatNotices bool
  45. flag.BoolVar(&formatNotices, "formatNotices", false, "emit notices in human-readable format")
  46. var profileFilename string
  47. flag.StringVar(&profileFilename, "profile", "", "CPU profile output file")
  48. var interfaceName string
  49. flag.StringVar(&interfaceName, "listenInterface", "", "bind local proxies to specified interface")
  50. var versionDetails bool
  51. flag.BoolVar(&versionDetails, "version", false, "print build information and exit")
  52. flag.BoolVar(&versionDetails, "v", false, "print build information and exit")
  53. var tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS string
  54. if tun.IsSupported() {
  55. // When tunDevice is specified, a packet tunnel is run and packets are relayed between
  56. // the specified tun device and the server.
  57. //
  58. // The tun device is expected to exist and should be configured with an IP address and
  59. // routing.
  60. //
  61. // The tunBindInterface/tunPrimaryDNS/tunSecondaryDNS parameters are used to bypass any
  62. // tun device routing when connecting to Psiphon servers.
  63. //
  64. // For transparent tunneled DNS, set the host or DNS clients to use the address specfied
  65. // in tun.GetTransparentDNSResolverIPv4Address().
  66. //
  67. // Packet tunnel mode is supported only on certains platforms.
  68. flag.StringVar(&tunDevice, "tunDevice", "", "run packet tunnel for specified tun device")
  69. flag.StringVar(&tunBindInterface, "tunBindInterface", tun.DEFAULT_PUBLIC_INTERFACE_NAME, "bypass tun device via specified interface")
  70. flag.StringVar(&tunPrimaryDNS, "tunPrimaryDNS", "8.8.8.8", "primary DNS resolver for bypass")
  71. flag.StringVar(&tunSecondaryDNS, "tunSecondaryDNS", "8.8.4.4", "secondary DNS resolver for bypass")
  72. }
  73. var noticeFilename string
  74. flag.StringVar(&noticeFilename, "notices", "", "notices output file (defaults to stderr)")
  75. var homepageFilename string
  76. flag.StringVar(&homepageFilename, "homepages", "", "homepages notices output file")
  77. var rotatingFilename string
  78. flag.StringVar(&rotatingFilename, "rotating", "", "rotating notices output file")
  79. var rotatingFileSize int
  80. flag.IntVar(&rotatingFileSize, "rotatingFileSize", 1<<20, "rotating notices file size")
  81. var rotatingSyncFrequency int
  82. flag.IntVar(&rotatingSyncFrequency, "rotatingSyncFrequency", 100, "rotating notices file sync frequency")
  83. flag.Parse()
  84. if versionDetails {
  85. b := common.GetBuildInfo()
  86. var printableDependencies bytes.Buffer
  87. var dependencyMap map[string]string
  88. longestRepoUrl := 0
  89. json.Unmarshal(b.Dependencies, &dependencyMap)
  90. sortedRepoUrls := make([]string, 0, len(dependencyMap))
  91. for repoUrl := range dependencyMap {
  92. repoUrlLength := len(repoUrl)
  93. if repoUrlLength > longestRepoUrl {
  94. longestRepoUrl = repoUrlLength
  95. }
  96. sortedRepoUrls = append(sortedRepoUrls, repoUrl)
  97. }
  98. sort.Strings(sortedRepoUrls)
  99. for repoUrl := range sortedRepoUrls {
  100. printableDependencies.WriteString(fmt.Sprintf(" %s ", sortedRepoUrls[repoUrl]))
  101. for i := 0; i < (longestRepoUrl - len(sortedRepoUrls[repoUrl])); i++ {
  102. printableDependencies.WriteString(" ")
  103. }
  104. printableDependencies.WriteString(fmt.Sprintf("%s\n", dependencyMap[sortedRepoUrls[repoUrl]]))
  105. }
  106. 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())
  107. os.Exit(0)
  108. }
  109. // Initialize notice output
  110. var noticeWriter io.Writer
  111. noticeWriter = os.Stderr
  112. if noticeFilename != "" {
  113. noticeFile, err := os.OpenFile(noticeFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  114. if err != nil {
  115. fmt.Printf("error opening notice file: %s\n", err)
  116. os.Exit(1)
  117. }
  118. defer noticeFile.Close()
  119. noticeWriter = noticeFile
  120. }
  121. if formatNotices {
  122. noticeWriter = psiphon.NewNoticeConsoleRewriter(noticeWriter)
  123. }
  124. psiphon.SetNoticeWriter(noticeWriter)
  125. err := psiphon.SetNoticeFiles(
  126. homepageFilename,
  127. rotatingFilename,
  128. rotatingFileSize,
  129. rotatingSyncFrequency)
  130. if err != nil {
  131. fmt.Printf("error initializing notice files: %s\n", err)
  132. os.Exit(1)
  133. }
  134. // Handle required config file parameter
  135. // EmitDiagnosticNotices is set by LoadConfig; force to true
  136. // an emit diagnostics when LoadConfig-related errors occur.
  137. if configFilename == "" {
  138. psiphon.SetEmitDiagnosticNotices(true)
  139. psiphon.NoticeError("configuration file is required")
  140. os.Exit(1)
  141. }
  142. configFileContents, err := ioutil.ReadFile(configFilename)
  143. if err != nil {
  144. psiphon.SetEmitDiagnosticNotices(true)
  145. psiphon.NoticeError("error loading configuration file: %s", err)
  146. os.Exit(1)
  147. }
  148. config, err := psiphon.LoadConfig(configFileContents)
  149. if err != nil {
  150. psiphon.SetEmitDiagnosticNotices(true)
  151. psiphon.NoticeError("error processing configuration file: %s", err)
  152. os.Exit(1)
  153. }
  154. if interfaceName != "" {
  155. config.ListenInterface = interfaceName
  156. }
  157. // Configure packet tunnel, including updating the config.
  158. if tun.IsSupported() && tunDevice != "" {
  159. tunDeviceFile, err := configurePacketTunnel(
  160. config, tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS)
  161. if err != nil {
  162. psiphon.SetEmitDiagnosticNotices(true)
  163. psiphon.NoticeError("error configuring packet tunnel: %s", err)
  164. os.Exit(1)
  165. }
  166. defer tunDeviceFile.Close()
  167. }
  168. // All config fields should be set before calling Commit.
  169. err = config.Commit()
  170. if err != nil {
  171. psiphon.SetEmitDiagnosticNotices(true)
  172. psiphon.NoticeError("error loading configuration file: %s", err)
  173. os.Exit(1)
  174. }
  175. // BuildInfo is a diagnostic notice, so emit only after config.Commit
  176. // sets EmitDiagnosticNotices.
  177. psiphon.NoticeBuildInfo()
  178. // Handle optional profiling parameter
  179. if profileFilename != "" {
  180. profileFile, err := os.Create(profileFilename)
  181. if err != nil {
  182. psiphon.NoticeError("error opening profile file: %s", err)
  183. os.Exit(1)
  184. }
  185. pprof.StartCPUProfile(profileFile)
  186. defer pprof.StopCPUProfile()
  187. }
  188. // Initialize data store
  189. err = psiphon.OpenDataStore(config)
  190. if err != nil {
  191. psiphon.NoticeError("error initializing datastore: %s", err)
  192. os.Exit(1)
  193. }
  194. defer psiphon.CloseDataStore()
  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. if psiphon.CountServerEntries() == 0 {
  232. embeddedServerListWaitGroup.Wait()
  233. } else {
  234. defer embeddedServerListWaitGroup.Wait()
  235. }
  236. }
  237. // Run Psiphon
  238. controller, err := psiphon.NewController(config)
  239. if err != nil {
  240. psiphon.NoticeError("error creating controller: %s", err)
  241. os.Exit(1)
  242. }
  243. controllerCtx, stopController := context.WithCancel(context.Background())
  244. defer stopController()
  245. controllerWaitGroup := new(sync.WaitGroup)
  246. controllerWaitGroup.Add(1)
  247. go func() {
  248. defer controllerWaitGroup.Done()
  249. controller.Run(controllerCtx)
  250. // Signal the <-controllerCtx.Done() case below. If the <-systemStopSignal
  251. // case already called stopController, this is a noop.
  252. stopController()
  253. }()
  254. systemStopSignal := make(chan os.Signal, 1)
  255. signal.Notify(systemStopSignal, os.Interrupt, os.Kill)
  256. // Wait for an OS signal or a Run stop signal, then stop Psiphon and exit
  257. select {
  258. case <-systemStopSignal:
  259. psiphon.NoticeInfo("shutdown by system")
  260. stopController()
  261. controllerWaitGroup.Wait()
  262. case <-controllerCtx.Done():
  263. psiphon.NoticeInfo("shutdown by controller")
  264. }
  265. }
  266. func configurePacketTunnel(
  267. config *psiphon.Config,
  268. tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS string) (*os.File, error) {
  269. file, _, err := tun.OpenTunDevice(tunDevice)
  270. if err != nil {
  271. return nil, common.ContextError(err)
  272. }
  273. provider := &tunProvider{
  274. bindInterface: tunBindInterface,
  275. primaryDNS: tunPrimaryDNS,
  276. secondaryDNS: tunSecondaryDNS,
  277. }
  278. config.PacketTunnelTunFileDescriptor = int(file.Fd())
  279. config.DeviceBinder = provider
  280. config.DnsServerGetter = provider
  281. return file, nil
  282. }
  283. type tunProvider struct {
  284. bindInterface string
  285. primaryDNS string
  286. secondaryDNS string
  287. }
  288. // BindToDevice implements the psiphon.DeviceBinder interface.
  289. func (p *tunProvider) BindToDevice(fileDescriptor int) (string, error) {
  290. return p.bindInterface, tun.BindToDevice(fileDescriptor, p.bindInterface)
  291. }
  292. // GetPrimaryDnsServer implements the psiphon.DnsServerGetter interface.
  293. func (p *tunProvider) GetPrimaryDnsServer() string {
  294. return p.primaryDNS
  295. }
  296. // GetSecondaryDnsServer implements the psiphon.DnsServerGetter interface.
  297. func (p *tunProvider) GetSecondaryDnsServer() string {
  298. return p.secondaryDNS
  299. }