main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. "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/buildinfo"
  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 interfaceName string
  47. flag.StringVar(&interfaceName, "listenInterface", "", "bind local proxies to specified interface")
  48. var versionDetails bool
  49. flag.BoolVar(&versionDetails, "version", false, "print build information and exit")
  50. flag.BoolVar(&versionDetails, "v", false, "print build information and exit")
  51. var tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS string
  52. if tun.IsSupported() {
  53. // When tunDevice is specified, a packet tunnel is run and packets are relayed between
  54. // the specified tun device and the server.
  55. //
  56. // The tun device is expected to exist and should be configured with an IP address and
  57. // routing.
  58. //
  59. // The tunBindInterface/tunPrimaryDNS/tunSecondaryDNS parameters are used to bypass any
  60. // tun device routing when connecting to Psiphon servers.
  61. //
  62. // For transparent tunneled DNS, set the host or DNS clients to use the address specfied
  63. // in tun.GetTransparentDNSResolverIPv4Address().
  64. //
  65. // Packet tunnel mode is supported only on certains platforms.
  66. flag.StringVar(&tunDevice, "tunDevice", "", "run packet tunnel for specified tun device")
  67. flag.StringVar(&tunBindInterface, "tunBindInterface", tun.DEFAULT_PUBLIC_INTERFACE_NAME, "bypass tun device via specified interface")
  68. flag.StringVar(&tunPrimaryDNS, "tunPrimaryDNS", "8.8.8.8", "primary DNS resolver for bypass")
  69. flag.StringVar(&tunSecondaryDNS, "tunSecondaryDNS", "8.8.4.4", "secondary DNS resolver for bypass")
  70. }
  71. var noticeFilename string
  72. flag.StringVar(&noticeFilename, "notices", "", "notices output file (defaults to stderr)")
  73. var homepageFilename string
  74. flag.StringVar(&homepageFilename, "homepages", "", "homepages notices output file")
  75. var rotatingFilename string
  76. flag.StringVar(&rotatingFilename, "rotating", "", "rotating notices output file")
  77. var rotatingFileSize int
  78. flag.IntVar(&rotatingFileSize, "rotatingFileSize", 1<<20, "rotating notices file size")
  79. var rotatingSyncFrequency int
  80. flag.IntVar(&rotatingSyncFrequency, "rotatingSyncFrequency", 100, "rotating notices file sync frequency")
  81. flag.Parse()
  82. if versionDetails {
  83. b := buildinfo.GetBuildInfo()
  84. var printableDependencies bytes.Buffer
  85. var dependencyMap map[string]string
  86. longestRepoUrl := 0
  87. json.Unmarshal(b.Dependencies, &dependencyMap)
  88. sortedRepoUrls := make([]string, 0, len(dependencyMap))
  89. for repoUrl := range dependencyMap {
  90. repoUrlLength := len(repoUrl)
  91. if repoUrlLength > longestRepoUrl {
  92. longestRepoUrl = repoUrlLength
  93. }
  94. sortedRepoUrls = append(sortedRepoUrls, repoUrl)
  95. }
  96. sort.Strings(sortedRepoUrls)
  97. for repoUrl := range sortedRepoUrls {
  98. printableDependencies.WriteString(fmt.Sprintf(" %s ", sortedRepoUrls[repoUrl]))
  99. for i := 0; i < (longestRepoUrl - len(sortedRepoUrls[repoUrl])); i++ {
  100. printableDependencies.WriteString(" ")
  101. }
  102. printableDependencies.WriteString(fmt.Sprintf("%s\n", dependencyMap[sortedRepoUrls[repoUrl]]))
  103. }
  104. 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())
  105. os.Exit(0)
  106. }
  107. // Initialize notice output
  108. var noticeWriter io.Writer
  109. noticeWriter = os.Stderr
  110. if noticeFilename != "" {
  111. noticeFile, err := os.OpenFile(noticeFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  112. if err != nil {
  113. fmt.Printf("error opening notice file: %s\n", err)
  114. os.Exit(1)
  115. }
  116. defer noticeFile.Close()
  117. noticeWriter = noticeFile
  118. }
  119. if formatNotices {
  120. noticeWriter = psiphon.NewNoticeConsoleRewriter(noticeWriter)
  121. }
  122. psiphon.SetNoticeWriter(noticeWriter)
  123. err := psiphon.SetNoticeFiles(
  124. homepageFilename,
  125. rotatingFilename,
  126. rotatingFileSize,
  127. rotatingSyncFrequency)
  128. if err != nil {
  129. fmt.Printf("error initializing notice files: %s\n", err)
  130. os.Exit(1)
  131. }
  132. // Handle required config file parameter
  133. // EmitDiagnosticNotices is set by LoadConfig; force to true
  134. // and emit diagnostics when LoadConfig-related errors occur.
  135. if configFilename == "" {
  136. psiphon.SetEmitDiagnosticNotices(true, false)
  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, false)
  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, false)
  149. psiphon.NoticeError("error processing configuration file: %s", err)
  150. os.Exit(1)
  151. }
  152. if interfaceName != "" {
  153. config.ListenInterface = interfaceName
  154. }
  155. // Configure packet tunnel, including updating the config.
  156. if tun.IsSupported() && tunDevice != "" {
  157. tunDeviceFile, err := configurePacketTunnel(
  158. config, tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS)
  159. if err != nil {
  160. psiphon.SetEmitDiagnosticNotices(true, false)
  161. psiphon.NoticeError("error configuring packet tunnel: %s", err)
  162. os.Exit(1)
  163. }
  164. defer tunDeviceFile.Close()
  165. }
  166. // All config fields should be set before calling Commit.
  167. err = config.Commit()
  168. if err != nil {
  169. psiphon.SetEmitDiagnosticNotices(true, false)
  170. psiphon.NoticeError("error loading configuration file: %s", err)
  171. os.Exit(1)
  172. }
  173. // BuildInfo is a diagnostic notice, so emit only after config.Commit
  174. // sets EmitDiagnosticNotices.
  175. psiphon.NoticeBuildInfo()
  176. // Initialize data store
  177. err = psiphon.OpenDataStore(config)
  178. if err != nil {
  179. psiphon.NoticeError("error initializing datastore: %s", err)
  180. os.Exit(1)
  181. }
  182. defer psiphon.CloseDataStore()
  183. // Handle optional embedded server list file parameter
  184. // If specified, the embedded server list is loaded and stored. When there
  185. // are no server candidates at all, we wait for this import to complete
  186. // before starting the Psiphon controller. Otherwise, we import while
  187. // concurrently starting the controller to minimize delay before attempting
  188. // to connect to existing candidate servers.
  189. // If the import fails, an error notice is emitted, but the controller is
  190. // still started: either existing candidate servers may suffice, or the
  191. // remote server list fetch may obtain candidate servers.
  192. if embeddedServerEntryListFilename != "" {
  193. embeddedServerListWaitGroup := new(sync.WaitGroup)
  194. embeddedServerListWaitGroup.Add(1)
  195. go func() {
  196. defer embeddedServerListWaitGroup.Done()
  197. serverEntryList, err := ioutil.ReadFile(embeddedServerEntryListFilename)
  198. if err != nil {
  199. psiphon.NoticeError("error loading embedded server entry list file: %s", err)
  200. return
  201. }
  202. // TODO: stream embedded server list data? also, the cast makes an unnecessary copy of a large buffer?
  203. serverEntries, err := protocol.DecodeServerEntryList(
  204. string(serverEntryList),
  205. common.GetCurrentTimestamp(),
  206. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  207. if err != nil {
  208. psiphon.NoticeError("error decoding embedded server entry list file: %s", err)
  209. return
  210. }
  211. // Since embedded server list entries may become stale, they will not
  212. // overwrite existing stored entries for the same server.
  213. err = psiphon.StoreServerEntries(config, serverEntries, false)
  214. if err != nil {
  215. psiphon.NoticeError("error storing embedded server entry list data: %s", err)
  216. return
  217. }
  218. }()
  219. if psiphon.CountServerEntries() == 0 {
  220. embeddedServerListWaitGroup.Wait()
  221. } else {
  222. defer embeddedServerListWaitGroup.Wait()
  223. }
  224. }
  225. // Run Psiphon
  226. controller, err := psiphon.NewController(config)
  227. if err != nil {
  228. psiphon.NoticeError("error creating controller: %s", err)
  229. os.Exit(1)
  230. }
  231. controllerCtx, stopController := context.WithCancel(context.Background())
  232. defer stopController()
  233. controllerWaitGroup := new(sync.WaitGroup)
  234. controllerWaitGroup.Add(1)
  235. go func() {
  236. defer controllerWaitGroup.Done()
  237. controller.Run(controllerCtx)
  238. // Signal the <-controllerCtx.Done() case below. If the <-systemStopSignal
  239. // case already called stopController, this is a noop.
  240. stopController()
  241. }()
  242. systemStopSignal := make(chan os.Signal, 1)
  243. signal.Notify(systemStopSignal, os.Interrupt, os.Kill)
  244. // writeProfilesSignal is nil and non-functional on Windows
  245. writeProfilesSignal := makeSIGUSR2Channel()
  246. // Wait for an OS signal or a Run stop signal, then stop Psiphon and exit
  247. for exit := false; !exit; {
  248. select {
  249. case <-writeProfilesSignal:
  250. psiphon.NoticeInfo("write profiles")
  251. profileSampleDurationSeconds := 5
  252. common.WriteRuntimeProfiles(
  253. psiphon.NoticeCommonLogger(),
  254. config.DataStoreDirectory,
  255. "",
  256. profileSampleDurationSeconds,
  257. profileSampleDurationSeconds)
  258. case <-systemStopSignal:
  259. psiphon.NoticeInfo("shutdown by system")
  260. stopController()
  261. controllerWaitGroup.Wait()
  262. exit = true
  263. case <-controllerCtx.Done():
  264. psiphon.NoticeInfo("shutdown by controller")
  265. exit = true
  266. }
  267. }
  268. }
  269. func configurePacketTunnel(
  270. config *psiphon.Config,
  271. tunDevice, tunBindInterface, tunPrimaryDNS, tunSecondaryDNS string) (*os.File, error) {
  272. file, _, err := tun.OpenTunDevice(tunDevice)
  273. if err != nil {
  274. return nil, common.ContextError(err)
  275. }
  276. provider := &tunProvider{
  277. bindInterface: tunBindInterface,
  278. primaryDNS: tunPrimaryDNS,
  279. secondaryDNS: tunSecondaryDNS,
  280. }
  281. config.PacketTunnelTunFileDescriptor = int(file.Fd())
  282. config.DeviceBinder = provider
  283. config.DnsServerGetter = provider
  284. return file, nil
  285. }
  286. type tunProvider struct {
  287. bindInterface string
  288. primaryDNS string
  289. secondaryDNS string
  290. }
  291. // BindToDevice implements the psiphon.DeviceBinder interface.
  292. func (p *tunProvider) BindToDevice(fileDescriptor int) (string, error) {
  293. return p.bindInterface, tun.BindToDevice(fileDescriptor, p.bindInterface)
  294. }
  295. // GetPrimaryDnsServer implements the psiphon.DnsServerGetter interface.
  296. func (p *tunProvider) GetPrimaryDnsServer() string {
  297. return p.primaryDNS
  298. }
  299. // GetSecondaryDnsServer implements the psiphon.DnsServerGetter interface.
  300. func (p *tunProvider) GetSecondaryDnsServer() string {
  301. return p.secondaryDNS
  302. }