main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. psiphon.NoticeBuildInfo()
  135. // Handle required config file parameter
  136. if configFilename == "" {
  137. psiphon.SetEmitDiagnosticNotices(true)
  138. psiphon.NoticeError("configuration file is required")
  139. os.Exit(1)
  140. }
  141. configFileContents, err := ioutil.ReadFile(configFilename)
  142. if err != nil {
  143. psiphon.SetEmitDiagnosticNotices(true)
  144. psiphon.NoticeError("error loading configuration file: %s", err)
  145. os.Exit(1)
  146. }
  147. config, err := psiphon.LoadConfig(configFileContents)
  148. if err != nil {
  149. psiphon.SetEmitDiagnosticNotices(true)
  150. psiphon.NoticeError("error processing configuration file: %s", err)
  151. os.Exit(1)
  152. }
  153. // Handle optional profiling parameter
  154. if profileFilename != "" {
  155. profileFile, err := os.Create(profileFilename)
  156. if err != nil {
  157. psiphon.NoticeError("error opening profile file: %s", err)
  158. os.Exit(1)
  159. }
  160. pprof.StartCPUProfile(profileFile)
  161. defer pprof.StopCPUProfile()
  162. }
  163. // Initialize data store
  164. err = psiphon.InitDataStore(config)
  165. if err != nil {
  166. psiphon.NoticeError("error initializing datastore: %s", err)
  167. os.Exit(1)
  168. }
  169. // Handle optional embedded server list file parameter
  170. // If specified, the embedded server list is loaded and stored. When there
  171. // are no server candidates at all, we wait for this import to complete
  172. // before starting the Psiphon controller. Otherwise, we import while
  173. // concurrently starting the controller to minimize delay before attempting
  174. // to connect to existing candidate servers.
  175. // If the import fails, an error notice is emitted, but the controller is
  176. // still started: either existing candidate servers may suffice, or the
  177. // remote server list fetch may obtain candidate servers.
  178. if embeddedServerEntryListFilename != "" {
  179. embeddedServerListWaitGroup := new(sync.WaitGroup)
  180. embeddedServerListWaitGroup.Add(1)
  181. go func() {
  182. defer embeddedServerListWaitGroup.Done()
  183. serverEntryList, err := ioutil.ReadFile(embeddedServerEntryListFilename)
  184. if err != nil {
  185. psiphon.NoticeError("error loading embedded server entry list file: %s", err)
  186. return
  187. }
  188. // TODO: stream embedded server list data? also, the cast makes an unnecessary copy of a large buffer?
  189. serverEntries, err := protocol.DecodeServerEntryList(
  190. string(serverEntryList),
  191. common.GetCurrentTimestamp(),
  192. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  193. if err != nil {
  194. psiphon.NoticeError("error decoding embedded server entry list file: %s", err)
  195. return
  196. }
  197. // Since embedded server list entries may become stale, they will not
  198. // overwrite existing stored entries for the same server.
  199. err = psiphon.StoreServerEntries(serverEntries, false)
  200. if err != nil {
  201. psiphon.NoticeError("error storing embedded server entry list data: %s", err)
  202. return
  203. }
  204. }()
  205. if psiphon.CountServerEntries(config.EgressRegion, config.TunnelProtocol) == 0 {
  206. embeddedServerListWaitGroup.Wait()
  207. } else {
  208. defer embeddedServerListWaitGroup.Wait()
  209. }
  210. }
  211. if interfaceName != "" {
  212. config.ListenInterface = interfaceName
  213. }
  214. // Configure packet tunnel
  215. if tun.IsSupported() && tunDevice != "" {
  216. tunDeviceFile, err := configurePacketTunnel(
  217. config, tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS)
  218. if err != nil {
  219. psiphon.NoticeError("error configuring packet tunnel: %s", err)
  220. os.Exit(1)
  221. }
  222. defer tunDeviceFile.Close()
  223. }
  224. // Run Psiphon
  225. controller, err := psiphon.NewController(config)
  226. if err != nil {
  227. psiphon.NoticeError("error creating controller: %s", err)
  228. os.Exit(1)
  229. }
  230. controllerCtx, stopController := context.WithCancel(context.Background())
  231. defer stopController()
  232. controllerWaitGroup := new(sync.WaitGroup)
  233. controllerWaitGroup.Add(1)
  234. go func() {
  235. defer controllerWaitGroup.Done()
  236. controller.Run(controllerCtx)
  237. // Signal the <-controllerCtx.Done() case below. If the <-systemStopSignal
  238. // case already called stopController, this is a noop.
  239. stopController()
  240. }()
  241. systemStopSignal := make(chan os.Signal, 1)
  242. signal.Notify(systemStopSignal, os.Interrupt, os.Kill)
  243. // Wait for an OS signal or a Run stop signal, then stop Psiphon and exit
  244. select {
  245. case <-systemStopSignal:
  246. psiphon.NoticeInfo("shutdown by system")
  247. stopController()
  248. controllerWaitGroup.Wait()
  249. case <-controllerCtx.Done():
  250. psiphon.NoticeInfo("shutdown by controller")
  251. }
  252. }
  253. func configurePacketTunnel(
  254. config *psiphon.Config,
  255. tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS string) (*os.File, error) {
  256. file, _, err := tun.OpenTunDevice(tunDevice)
  257. if err != nil {
  258. return nil, common.ContextError(err)
  259. }
  260. provider := &tunProvider{
  261. bindInterface: tunBindInterface,
  262. primaryDNS: tunPrimaryDNS,
  263. secondaryDNS: tunSecondaryDNS,
  264. }
  265. config.PacketTunnelTunFileDescriptor = int(file.Fd())
  266. config.DeviceBinder = provider
  267. config.DnsServerGetter = provider
  268. return file, nil
  269. }
  270. type tunProvider struct {
  271. bindInterface string
  272. primaryDNS string
  273. secondaryDNS string
  274. }
  275. // BindToDevice implements the psiphon.DeviceBinder interface.
  276. func (p *tunProvider) BindToDevice(fileDescriptor int) error {
  277. return tun.BindToDevice(fileDescriptor, p.bindInterface)
  278. }
  279. // GetPrimaryDnsServer implements the psiphon.DnsServerGetter interface.
  280. func (p *tunProvider) GetPrimaryDnsServer() string {
  281. return p.primaryDNS
  282. }
  283. // GetSecondaryDnsServer implements the psiphon.DnsServerGetter interface.
  284. func (p *tunProvider) GetSecondaryDnsServer() string {
  285. return p.secondaryDNS
  286. }