main.go 11 KB

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