main.go 11 KB

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