main.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. )
  36. func main() {
  37. // Define command-line parameters
  38. var configFilename string
  39. flag.StringVar(&configFilename, "config", "", "configuration input file")
  40. var embeddedServerEntryListFilename string
  41. flag.StringVar(&embeddedServerEntryListFilename, "serverList", "", "embedded server entry list input file")
  42. var formatNotices bool
  43. flag.BoolVar(&formatNotices, "formatNotices", false, "emit notices in human-readable format")
  44. var profileFilename string
  45. flag.StringVar(&profileFilename, "profile", "", "CPU profile output file")
  46. var interfaceName string
  47. flag.StringVar(&interfaceName, "listenInterface", "", "Interface Name")
  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. flag.Parse()
  52. if versionDetails {
  53. b := common.GetBuildInfo()
  54. var builtWith bytes.Buffer
  55. builtWith.WriteString(b.GoVersion)
  56. if b.GomobileVersion != "" {
  57. builtWith.WriteString(" (")
  58. builtWith.WriteString(b.GomobileVersion)
  59. builtWith.WriteString(")")
  60. }
  61. var printableDependencies bytes.Buffer
  62. var dependencyMap map[string]string
  63. longestRepoUrl := 0
  64. json.Unmarshal(b.Dependencies, &dependencyMap)
  65. sortedRepoUrls := make([]string, 0, len(dependencyMap))
  66. for repoUrl := range dependencyMap {
  67. repoUrlLength := len(repoUrl)
  68. if repoUrlLength > longestRepoUrl {
  69. longestRepoUrl = repoUrlLength
  70. }
  71. sortedRepoUrls = append(sortedRepoUrls, repoUrl)
  72. }
  73. sort.Strings(sortedRepoUrls)
  74. for repoUrl := range sortedRepoUrls {
  75. printableDependencies.WriteString(fmt.Sprintf(" %s ", sortedRepoUrls[repoUrl]))
  76. for i := 0; i < (longestRepoUrl - len(sortedRepoUrls[repoUrl])); i++ {
  77. printableDependencies.WriteString(" ")
  78. }
  79. printableDependencies.WriteString(fmt.Sprintf("%s\n", dependencyMap[sortedRepoUrls[repoUrl]]))
  80. }
  81. 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, builtWith.String(), b.BuildRepo, b.BuildRev, printableDependencies.String())
  82. os.Exit(0)
  83. }
  84. // Initialize default Notice output (stderr)
  85. var noticeWriter io.Writer
  86. noticeWriter = os.Stderr
  87. if formatNotices {
  88. noticeWriter = psiphon.NewNoticeConsoleRewriter(noticeWriter)
  89. }
  90. psiphon.SetNoticeOutput(noticeWriter)
  91. psiphon.NoticeBuildInfo()
  92. // Handle required config file parameter
  93. if configFilename == "" {
  94. psiphon.SetEmitDiagnosticNotices(true)
  95. psiphon.NoticeError("configuration file is required")
  96. os.Exit(1)
  97. }
  98. configFileContents, err := ioutil.ReadFile(configFilename)
  99. if err != nil {
  100. psiphon.SetEmitDiagnosticNotices(true)
  101. psiphon.NoticeError("error loading configuration file: %s", err)
  102. os.Exit(1)
  103. }
  104. config, err := psiphon.LoadConfig(configFileContents)
  105. if err != nil {
  106. psiphon.SetEmitDiagnosticNotices(true)
  107. psiphon.NoticeError("error processing configuration file: %s", err)
  108. os.Exit(1)
  109. }
  110. // When a logfile is configured, reinitialize Notice output
  111. if config.LogFilename != "" {
  112. logFile, err := os.OpenFile(config.LogFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  113. if err != nil {
  114. psiphon.NoticeError("error opening log file: %s", err)
  115. os.Exit(1)
  116. }
  117. defer logFile.Close()
  118. var noticeWriter io.Writer
  119. noticeWriter = logFile
  120. if formatNotices {
  121. noticeWriter = psiphon.NewNoticeConsoleRewriter(noticeWriter)
  122. }
  123. psiphon.SetNoticeOutput(noticeWriter)
  124. }
  125. // Handle optional profiling parameter
  126. if profileFilename != "" {
  127. profileFile, err := os.Create(profileFilename)
  128. if err != nil {
  129. psiphon.NoticeError("error opening profile file: %s", err)
  130. os.Exit(1)
  131. }
  132. pprof.StartCPUProfile(profileFile)
  133. defer pprof.StopCPUProfile()
  134. }
  135. // Initialize data store
  136. err = psiphon.InitDataStore(config)
  137. if err != nil {
  138. psiphon.NoticeError("error initializing datastore: %s", err)
  139. os.Exit(1)
  140. }
  141. // Handle optional embedded server list file parameter
  142. // If specified, the embedded server list is loaded and stored. When there
  143. // are no server candidates at all, we wait for this import to complete
  144. // before starting the Psiphon controller. Otherwise, we import while
  145. // concurrently starting the controller to minimize delay before attempting
  146. // to connect to existing candidate servers.
  147. // If the import fails, an error notice is emitted, but the controller is
  148. // still started: either existing candidate servers may suffice, or the
  149. // remote server list fetch may obtain candidate servers.
  150. if embeddedServerEntryListFilename != "" {
  151. embeddedServerListWaitGroup := new(sync.WaitGroup)
  152. embeddedServerListWaitGroup.Add(1)
  153. go func() {
  154. defer embeddedServerListWaitGroup.Done()
  155. serverEntryList, err := ioutil.ReadFile(embeddedServerEntryListFilename)
  156. if err != nil {
  157. psiphon.NoticeError("error loading embedded server entry list file: %s", err)
  158. return
  159. }
  160. // TODO: stream embedded server list data? also, the cast makes an unnecessary copy of a large buffer?
  161. serverEntries, err := protocol.DecodeAndValidateServerEntryList(
  162. string(serverEntryList),
  163. common.GetCurrentTimestamp(),
  164. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  165. if err != nil {
  166. psiphon.NoticeError("error decoding embedded server entry list file: %s", err)
  167. return
  168. }
  169. // Since embedded server list entries may become stale, they will not
  170. // overwrite existing stored entries for the same server.
  171. err = psiphon.StoreServerEntries(serverEntries, false)
  172. if err != nil {
  173. psiphon.NoticeError("error storing embedded server entry list data: %s", err)
  174. return
  175. }
  176. }()
  177. if psiphon.CountServerEntries(config.EgressRegion, config.TunnelProtocol) == 0 {
  178. embeddedServerListWaitGroup.Wait()
  179. } else {
  180. defer embeddedServerListWaitGroup.Wait()
  181. }
  182. }
  183. if interfaceName != "" {
  184. config.ListenInterface = interfaceName
  185. }
  186. // Run Psiphon
  187. controller, err := psiphon.NewController(config)
  188. if err != nil {
  189. psiphon.NoticeError("error creating controller: %s", err)
  190. os.Exit(1)
  191. }
  192. controllerStopSignal := make(chan struct{}, 1)
  193. shutdownBroadcast := make(chan struct{})
  194. controllerWaitGroup := new(sync.WaitGroup)
  195. controllerWaitGroup.Add(1)
  196. go func() {
  197. defer controllerWaitGroup.Done()
  198. controller.Run(shutdownBroadcast)
  199. controllerStopSignal <- *new(struct{})
  200. }()
  201. // Wait for an OS signal or a Run stop signal, then stop Psiphon and exit
  202. systemStopSignal := make(chan os.Signal, 1)
  203. signal.Notify(systemStopSignal, os.Interrupt, os.Kill)
  204. select {
  205. case <-systemStopSignal:
  206. psiphon.NoticeInfo("shutdown by system")
  207. close(shutdownBroadcast)
  208. controllerWaitGroup.Wait()
  209. case <-controllerStopSignal:
  210. psiphon.NoticeInfo("shutdown by controller")
  211. }
  212. }