main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. "sort"
  31. "sync"
  32. "syscall"
  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/buildinfo"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  39. )
  40. func main() {
  41. // Define command-line parameters
  42. var configFilename string
  43. flag.StringVar(&configFilename, "config", "", "configuration input file")
  44. var embeddedServerEntryListFilename string
  45. flag.StringVar(&embeddedServerEntryListFilename, "serverList", "", "embedded server entry list input file")
  46. var formatNotices bool
  47. flag.BoolVar(&formatNotices, "formatNotices", false, "emit notices in human-readable format")
  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 := buildinfo.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. // and emit diagnostics when LoadConfig-related errors occur.
  137. if configFilename == "" {
  138. psiphon.SetEmitDiagnosticNotices(true, false)
  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, false)
  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, false)
  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, false)
  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, false)
  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. // Initialize data store
  179. err = psiphon.OpenDataStore(config)
  180. if err != nil {
  181. psiphon.NoticeError("error initializing datastore: %s", err)
  182. os.Exit(1)
  183. }
  184. defer psiphon.CloseDataStore()
  185. // Handle optional embedded server list file parameter
  186. // If specified, the embedded server list is loaded and stored. When there
  187. // are no server candidates at all, we wait for this import to complete
  188. // before starting the Psiphon controller. Otherwise, we import while
  189. // concurrently starting the controller to minimize delay before attempting
  190. // to connect to existing candidate servers.
  191. // If the import fails, an error notice is emitted, but the controller is
  192. // still started: either existing candidate servers may suffice, or the
  193. // remote server list fetch may obtain candidate servers.
  194. if embeddedServerEntryListFilename != "" {
  195. embeddedServerListWaitGroup := new(sync.WaitGroup)
  196. embeddedServerListWaitGroup.Add(1)
  197. go func() {
  198. defer embeddedServerListWaitGroup.Done()
  199. serverEntryList, err := ioutil.ReadFile(embeddedServerEntryListFilename)
  200. if err != nil {
  201. psiphon.NoticeError("error loading embedded server entry list file: %s", err)
  202. return
  203. }
  204. // TODO: stream embedded server list data? also, the cast makes an unnecessary copy of a large buffer?
  205. serverEntries, err := protocol.DecodeServerEntryList(
  206. string(serverEntryList),
  207. common.GetCurrentTimestamp(),
  208. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  209. if err != nil {
  210. psiphon.NoticeError("error decoding embedded server entry list file: %s", err)
  211. return
  212. }
  213. // Since embedded server list entries may become stale, they will not
  214. // overwrite existing stored entries for the same server.
  215. err = psiphon.StoreServerEntries(config, serverEntries, false)
  216. if err != nil {
  217. psiphon.NoticeError("error storing embedded server entry list data: %s", err)
  218. return
  219. }
  220. }()
  221. if psiphon.CountServerEntries() == 0 {
  222. embeddedServerListWaitGroup.Wait()
  223. } else {
  224. defer embeddedServerListWaitGroup.Wait()
  225. }
  226. }
  227. // Run Psiphon
  228. controller, err := psiphon.NewController(config)
  229. if err != nil {
  230. psiphon.NoticeError("error creating controller: %s", err)
  231. os.Exit(1)
  232. }
  233. controllerCtx, stopController := context.WithCancel(context.Background())
  234. defer stopController()
  235. controllerWaitGroup := new(sync.WaitGroup)
  236. controllerWaitGroup.Add(1)
  237. go func() {
  238. defer controllerWaitGroup.Done()
  239. controller.Run(controllerCtx)
  240. // Signal the <-controllerCtx.Done() case below. If the <-systemStopSignal
  241. // case already called stopController, this is a noop.
  242. stopController()
  243. }()
  244. systemStopSignal := make(chan os.Signal, 1)
  245. signal.Notify(systemStopSignal, os.Interrupt, syscall.SIGTERM)
  246. // writeProfilesSignal is nil and non-functional on Windows
  247. writeProfilesSignal := makeSIGUSR2Channel()
  248. // Wait for an OS signal or a Run stop signal, then stop Psiphon and exit
  249. for exit := false; !exit; {
  250. select {
  251. case <-writeProfilesSignal:
  252. psiphon.NoticeInfo("write profiles")
  253. profileSampleDurationSeconds := 5
  254. common.WriteRuntimeProfiles(
  255. psiphon.NoticeCommonLogger(),
  256. config.DataStoreDirectory,
  257. "",
  258. profileSampleDurationSeconds,
  259. profileSampleDurationSeconds)
  260. case <-systemStopSignal:
  261. psiphon.NoticeInfo("shutdown by system")
  262. stopController()
  263. controllerWaitGroup.Wait()
  264. exit = true
  265. case <-controllerCtx.Done():
  266. psiphon.NoticeInfo("shutdown by controller")
  267. exit = true
  268. }
  269. }
  270. }
  271. func configurePacketTunnel(
  272. config *psiphon.Config,
  273. tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS string) (*os.File, error) {
  274. file, _, err := tun.OpenTunDevice(tunDevice)
  275. if err != nil {
  276. return nil, errors.Trace(err)
  277. }
  278. provider := &tunProvider{
  279. bindInterface: tunBindInterface,
  280. primaryDNS: tunPrimaryDNS,
  281. secondaryDNS: tunSecondaryDNS,
  282. }
  283. config.PacketTunnelTunFileDescriptor = int(file.Fd())
  284. config.DeviceBinder = provider
  285. config.DnsServerGetter = provider
  286. return file, nil
  287. }
  288. type tunProvider struct {
  289. bindInterface string
  290. primaryDNS string
  291. secondaryDNS string
  292. }
  293. // BindToDevice implements the psiphon.DeviceBinder interface.
  294. func (p *tunProvider) BindToDevice(fileDescriptor int) (string, error) {
  295. return p.bindInterface, tun.BindToDevice(fileDescriptor, p.bindInterface)
  296. }
  297. // GetPrimaryDnsServer implements the psiphon.DnsServerGetter interface.
  298. func (p *tunProvider) GetPrimaryDnsServer() string {
  299. return p.primaryDNS
  300. }
  301. // GetSecondaryDnsServer implements the psiphon.DnsServerGetter interface.
  302. func (p *tunProvider) GetSecondaryDnsServer() string {
  303. return p.secondaryDNS
  304. }