main.go 11 KB

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