main.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. flag.Parse()
  73. if versionDetails {
  74. b := common.GetBuildInfo()
  75. var printableDependencies bytes.Buffer
  76. var dependencyMap map[string]string
  77. longestRepoUrl := 0
  78. json.Unmarshal(b.Dependencies, &dependencyMap)
  79. sortedRepoUrls := make([]string, 0, len(dependencyMap))
  80. for repoUrl := range dependencyMap {
  81. repoUrlLength := len(repoUrl)
  82. if repoUrlLength > longestRepoUrl {
  83. longestRepoUrl = repoUrlLength
  84. }
  85. sortedRepoUrls = append(sortedRepoUrls, repoUrl)
  86. }
  87. sort.Strings(sortedRepoUrls)
  88. for repoUrl := range sortedRepoUrls {
  89. printableDependencies.WriteString(fmt.Sprintf(" %s ", sortedRepoUrls[repoUrl]))
  90. for i := 0; i < (longestRepoUrl - len(sortedRepoUrls[repoUrl])); i++ {
  91. printableDependencies.WriteString(" ")
  92. }
  93. printableDependencies.WriteString(fmt.Sprintf("%s\n", dependencyMap[sortedRepoUrls[repoUrl]]))
  94. }
  95. 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())
  96. os.Exit(0)
  97. }
  98. // Initialize default Notice output (stderr)
  99. var noticeWriter io.Writer
  100. noticeWriter = os.Stderr
  101. if formatNotices {
  102. noticeWriter = psiphon.NewNoticeConsoleRewriter(noticeWriter)
  103. }
  104. psiphon.SetNoticeOutput(noticeWriter)
  105. psiphon.NoticeBuildInfo()
  106. // Handle required config file parameter
  107. if configFilename == "" {
  108. psiphon.SetEmitDiagnosticNotices(true)
  109. psiphon.NoticeError("configuration file is required")
  110. os.Exit(1)
  111. }
  112. configFileContents, err := ioutil.ReadFile(configFilename)
  113. if err != nil {
  114. psiphon.SetEmitDiagnosticNotices(true)
  115. psiphon.NoticeError("error loading configuration file: %s", err)
  116. os.Exit(1)
  117. }
  118. config, err := psiphon.LoadConfig(configFileContents)
  119. if err != nil {
  120. psiphon.SetEmitDiagnosticNotices(true)
  121. psiphon.NoticeError("error processing configuration file: %s", err)
  122. os.Exit(1)
  123. }
  124. // When a logfile is configured, reinitialize Notice output
  125. if config.LogFilename != "" {
  126. logFile, err := os.OpenFile(config.LogFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  127. if err != nil {
  128. psiphon.NoticeError("error opening log file: %s", err)
  129. os.Exit(1)
  130. }
  131. defer logFile.Close()
  132. var noticeWriter io.Writer
  133. noticeWriter = logFile
  134. if formatNotices {
  135. noticeWriter = psiphon.NewNoticeConsoleRewriter(noticeWriter)
  136. }
  137. psiphon.SetNoticeOutput(noticeWriter)
  138. }
  139. // Handle optional profiling parameter
  140. if profileFilename != "" {
  141. profileFile, err := os.Create(profileFilename)
  142. if err != nil {
  143. psiphon.NoticeError("error opening profile file: %s", err)
  144. os.Exit(1)
  145. }
  146. pprof.StartCPUProfile(profileFile)
  147. defer pprof.StopCPUProfile()
  148. }
  149. // Initialize data store
  150. err = psiphon.InitDataStore(config)
  151. if err != nil {
  152. psiphon.NoticeError("error initializing datastore: %s", err)
  153. os.Exit(1)
  154. }
  155. // Handle optional embedded server list file parameter
  156. // If specified, the embedded server list is loaded and stored. When there
  157. // are no server candidates at all, we wait for this import to complete
  158. // before starting the Psiphon controller. Otherwise, we import while
  159. // concurrently starting the controller to minimize delay before attempting
  160. // to connect to existing candidate servers.
  161. // If the import fails, an error notice is emitted, but the controller is
  162. // still started: either existing candidate servers may suffice, or the
  163. // remote server list fetch may obtain candidate servers.
  164. if embeddedServerEntryListFilename != "" {
  165. embeddedServerListWaitGroup := new(sync.WaitGroup)
  166. embeddedServerListWaitGroup.Add(1)
  167. go func() {
  168. defer embeddedServerListWaitGroup.Done()
  169. serverEntryList, err := ioutil.ReadFile(embeddedServerEntryListFilename)
  170. if err != nil {
  171. psiphon.NoticeError("error loading embedded server entry list file: %s", err)
  172. return
  173. }
  174. // TODO: stream embedded server list data? also, the cast makes an unnecessary copy of a large buffer?
  175. serverEntries, err := protocol.DecodeServerEntryList(
  176. string(serverEntryList),
  177. common.GetCurrentTimestamp(),
  178. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  179. if err != nil {
  180. psiphon.NoticeError("error decoding embedded server entry list file: %s", err)
  181. return
  182. }
  183. // Since embedded server list entries may become stale, they will not
  184. // overwrite existing stored entries for the same server.
  185. err = psiphon.StoreServerEntries(serverEntries, false)
  186. if err != nil {
  187. psiphon.NoticeError("error storing embedded server entry list data: %s", err)
  188. return
  189. }
  190. }()
  191. if psiphon.CountServerEntries(config.EgressRegion, config.TunnelProtocol) == 0 {
  192. embeddedServerListWaitGroup.Wait()
  193. } else {
  194. defer embeddedServerListWaitGroup.Wait()
  195. }
  196. }
  197. if interfaceName != "" {
  198. config.ListenInterface = interfaceName
  199. }
  200. // Configure packet tunnel
  201. if tun.IsSupported() && tunDevice != "" {
  202. tunDeviceFile, err := configurePacketTunnel(
  203. config, tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS)
  204. if err != nil {
  205. psiphon.NoticeError("error configuring packet tunnel: %s", err)
  206. os.Exit(1)
  207. }
  208. defer tunDeviceFile.Close()
  209. }
  210. // Run Psiphon
  211. controller, err := psiphon.NewController(config)
  212. if err != nil {
  213. psiphon.NoticeError("error creating controller: %s", err)
  214. os.Exit(1)
  215. }
  216. controllerStopSignal := make(chan struct{}, 1)
  217. shutdownBroadcast := make(chan struct{})
  218. controllerWaitGroup := new(sync.WaitGroup)
  219. controllerWaitGroup.Add(1)
  220. go func() {
  221. defer controllerWaitGroup.Done()
  222. controller.Run(shutdownBroadcast)
  223. controllerStopSignal <- *new(struct{})
  224. }()
  225. // Wait for an OS signal or a Run stop signal, then stop Psiphon and exit
  226. systemStopSignal := make(chan os.Signal, 1)
  227. signal.Notify(systemStopSignal, os.Interrupt, os.Kill)
  228. select {
  229. case <-systemStopSignal:
  230. psiphon.NoticeInfo("shutdown by system")
  231. close(shutdownBroadcast)
  232. controllerWaitGroup.Wait()
  233. case <-controllerStopSignal:
  234. psiphon.NoticeInfo("shutdown by controller")
  235. }
  236. }
  237. func configurePacketTunnel(
  238. config *psiphon.Config,
  239. tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS string) (*os.File, error) {
  240. file, _, err := tun.OpenTunDevice(tunDevice)
  241. if err != nil {
  242. return nil, common.ContextError(err)
  243. }
  244. provider := &tunProvider{
  245. bindInterface: tunBindInterface,
  246. primaryDNS: tunPrimaryDNS,
  247. secondaryDNS: tunSecondaryDNS,
  248. }
  249. config.PacketTunnelTunFileDescriptor = int(file.Fd())
  250. config.DeviceBinder = provider
  251. config.DnsServerGetter = provider
  252. return file, nil
  253. }
  254. type tunProvider struct {
  255. bindInterface string
  256. primaryDNS string
  257. secondaryDNS string
  258. }
  259. // BindToDevice implements the psiphon.DeviceBinder interface.
  260. func (p *tunProvider) BindToDevice(fileDescriptor int) error {
  261. return tun.BindToDevice(fileDescriptor, p.bindInterface)
  262. }
  263. // GetPrimaryDnsServer implements the psiphon.DnsServerGetter interface.
  264. func (p *tunProvider) GetPrimaryDnsServer() string {
  265. return p.primaryDNS
  266. }
  267. // GetSecondaryDnsServer implements the psiphon.DnsServerGetter interface.
  268. func (p *tunProvider) GetSecondaryDnsServer() string {
  269. return p.secondaryDNS
  270. }