main.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. /*
  2. * Copyright (c) 2016, 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. "encoding/json"
  22. "flag"
  23. "fmt"
  24. "io"
  25. "io/ioutil"
  26. "os"
  27. "strconv"
  28. "strings"
  29. "syscall"
  30. "time"
  31. "github.com/Psiphon-Inc/rotate-safe-writer"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server"
  35. "github.com/mitchellh/panicwrap"
  36. )
  37. var loadedConfigJSON []byte
  38. func main() {
  39. var configFilename string
  40. var generateServerIPaddress string
  41. var generateServerNetworkInterface string
  42. var generateProtocolPorts stringListFlag
  43. var generateWebServerPort int
  44. var generateLogFilename string
  45. var generateTrafficRulesConfigFilename string
  46. var generateOSLConfigFilename string
  47. var generateTacticsConfigFilename string
  48. var generateServerEntryFilename string
  49. flag.StringVar(
  50. &configFilename,
  51. "config",
  52. server.SERVER_CONFIG_FILENAME,
  53. "run or generate with this config `filename`")
  54. flag.StringVar(
  55. &generateServerIPaddress,
  56. "ipaddress",
  57. server.DEFAULT_SERVER_IP_ADDRESS,
  58. "generate with this server `IP address`")
  59. flag.StringVar(
  60. &generateServerNetworkInterface,
  61. "interface",
  62. "",
  63. "generate with server IP address from this `network-interface`")
  64. flag.Var(
  65. &generateProtocolPorts,
  66. "protocol",
  67. "generate with `protocol:port`; flag may be repeated to enable multiple protocols")
  68. flag.IntVar(
  69. &generateWebServerPort,
  70. "web",
  71. 0,
  72. "generate with web server `port`; 0 for no web server")
  73. flag.StringVar(
  74. &generateLogFilename,
  75. "logFilename",
  76. "",
  77. "set application log file name and path; blank for stderr")
  78. flag.StringVar(
  79. &generateTrafficRulesConfigFilename,
  80. "trafficRules",
  81. server.SERVER_TRAFFIC_RULES_CONFIG_FILENAME,
  82. "generate with this traffic rules config `filename`")
  83. flag.StringVar(
  84. &generateOSLConfigFilename,
  85. "osl",
  86. server.SERVER_OSL_CONFIG_FILENAME,
  87. "generate with this OSL config `filename`")
  88. flag.StringVar(
  89. &generateTacticsConfigFilename,
  90. "tactics",
  91. server.SERVER_TACTICS_CONFIG_FILENAME,
  92. "generate with this tactics config `filename`")
  93. flag.StringVar(
  94. &generateServerEntryFilename,
  95. "serverEntry",
  96. server.SERVER_ENTRY_FILENAME,
  97. "generate with this server entry `filename`")
  98. flag.Usage = func() {
  99. fmt.Fprintf(os.Stderr,
  100. "Usage:\n\n"+
  101. "%s <flags> generate generates configuration files\n"+
  102. "%s <flags> run runs configured services\n\n",
  103. os.Args[0], os.Args[0])
  104. flag.PrintDefaults()
  105. }
  106. flag.Parse()
  107. args := flag.Args()
  108. if len(args) < 1 {
  109. flag.Usage()
  110. os.Exit(1)
  111. } else if args[0] == "generate" {
  112. serverIPaddress := generateServerIPaddress
  113. if generateServerNetworkInterface != "" {
  114. // TODO: IPv6 support
  115. serverIPv4Address, _, err := common.GetInterfaceIPAddresses(generateServerNetworkInterface)
  116. if err == nil && serverIPv4Address == nil {
  117. err = fmt.Errorf("no IPv4 address for interface %s", generateServerNetworkInterface)
  118. }
  119. if err != nil {
  120. fmt.Printf("generate failed: %s\n", err)
  121. os.Exit(1)
  122. }
  123. serverIPaddress = serverIPv4Address.String()
  124. }
  125. tunnelProtocolPorts := make(map[string]int)
  126. marionetteFormat := ""
  127. for _, protocolPort := range generateProtocolPorts {
  128. parts := strings.Split(protocolPort, ":")
  129. if len(parts) == 2 {
  130. if protocol.TunnelProtocolUsesMarionette(parts[0]) {
  131. tunnelProtocolPorts[parts[0]] = 0
  132. marionetteFormat = parts[1]
  133. } else {
  134. port, err := strconv.Atoi(parts[1])
  135. if err != nil {
  136. fmt.Printf("generate failed: %s\n", err)
  137. os.Exit(1)
  138. }
  139. tunnelProtocolPorts[parts[0]] = port
  140. }
  141. }
  142. }
  143. configJSON, trafficRulesConfigJSON, OSLConfigJSON,
  144. tacticsConfigJSON, encodedServerEntry, err :=
  145. server.GenerateConfig(
  146. &server.GenerateConfigParams{
  147. LogFilename: generateLogFilename,
  148. ServerIPAddress: serverIPaddress,
  149. EnableSSHAPIRequests: true,
  150. WebServerPort: generateWebServerPort,
  151. TunnelProtocolPorts: tunnelProtocolPorts,
  152. MarionetteFormat: marionetteFormat,
  153. TrafficRulesConfigFilename: generateTrafficRulesConfigFilename,
  154. OSLConfigFilename: generateOSLConfigFilename,
  155. TacticsConfigFilename: generateTacticsConfigFilename,
  156. })
  157. if err != nil {
  158. fmt.Printf("generate failed: %s\n", err)
  159. os.Exit(1)
  160. }
  161. err = ioutil.WriteFile(configFilename, configJSON, 0600)
  162. if err != nil {
  163. fmt.Printf("error writing configuration file: %s\n", err)
  164. os.Exit(1)
  165. }
  166. err = ioutil.WriteFile(generateTrafficRulesConfigFilename, trafficRulesConfigJSON, 0600)
  167. if err != nil {
  168. fmt.Printf("error writing traffic rule config file: %s\n", err)
  169. os.Exit(1)
  170. }
  171. err = ioutil.WriteFile(generateOSLConfigFilename, OSLConfigJSON, 0600)
  172. if err != nil {
  173. fmt.Printf("error writing OSL config file: %s\n", err)
  174. os.Exit(1)
  175. }
  176. err = ioutil.WriteFile(generateTacticsConfigFilename, tacticsConfigJSON, 0600)
  177. if err != nil {
  178. fmt.Printf("error writing tactics config file: %s\n", err)
  179. os.Exit(1)
  180. }
  181. err = ioutil.WriteFile(generateServerEntryFilename, encodedServerEntry, 0600)
  182. if err != nil {
  183. fmt.Printf("error writing server entry file: %s\n", err)
  184. os.Exit(1)
  185. }
  186. } else if args[0] == "run" {
  187. configJSON, err := ioutil.ReadFile(configFilename)
  188. if err != nil {
  189. fmt.Printf("error loading configuration file: %s\n", err)
  190. os.Exit(1)
  191. }
  192. loadedConfigJSON = configJSON
  193. // The initial call to panicwrap.Wrap will spawn a child process
  194. // running the same program.
  195. //
  196. // The parent process waits for the child to terminate and
  197. // panicHandler logs any panics from the child.
  198. //
  199. // The child will return immediately from Wrap without spawning
  200. // and fall through to server.RunServices.
  201. // Unhandled panic wrapper. Logs it, then re-executes the current executable
  202. exitStatus, err := panicwrap.Wrap(&panicwrap.WrapConfig{
  203. Handler: panicHandler,
  204. ForwardSignals: []os.Signal{os.Interrupt, os.Kill, syscall.SIGTERM, syscall.SIGUSR1, syscall.SIGUSR2, syscall.SIGTSTP, syscall.SIGCONT},
  205. })
  206. if err != nil {
  207. fmt.Printf("failed to set up the panic wrapper: %s\n", err)
  208. os.Exit(1)
  209. }
  210. // Note: panicwrap.Wrap documentation states that exitStatus == -1
  211. // should be used to determine whether the process is the child.
  212. // However, we have found that this exitStatus is returned even when
  213. // the process is the parent. Likely due to panicwrap returning
  214. // syscall.WaitStatus.ExitStatus() as the exitStatus, which _can_ be
  215. // -1. Checking panicwrap.Wrapped(nil) is more reliable.
  216. if !panicwrap.Wrapped(nil) {
  217. os.Exit(exitStatus)
  218. }
  219. // Else, this is the child process.
  220. err = server.RunServices(configJSON)
  221. if err != nil {
  222. fmt.Printf("run failed: %s\n", err)
  223. os.Exit(1)
  224. }
  225. }
  226. }
  227. type stringListFlag []string
  228. func (list *stringListFlag) String() string {
  229. return strings.Join(*list, ", ")
  230. }
  231. func (list *stringListFlag) Set(flagValue string) error {
  232. *list = append(*list, flagValue)
  233. return nil
  234. }
  235. func panicHandler(output string) {
  236. if len(loadedConfigJSON) > 0 {
  237. config, err := server.LoadConfig([]byte(loadedConfigJSON))
  238. if err != nil {
  239. fmt.Printf("error parsing configuration file: %s\n%s\n", err, output)
  240. os.Exit(1)
  241. }
  242. logEvent := make(map[string]string)
  243. logEvent["host_id"] = config.HostID
  244. logEvent["build_rev"] = common.GetBuildInfo().BuildRev
  245. logEvent["timestamp"] = time.Now().Format(time.RFC3339)
  246. logEvent["event_name"] = "panic"
  247. logEvent["panic"] = output
  248. // Logs are written to the configured file name. If no name is specified, logs are written to stderr
  249. var jsonWriter io.Writer
  250. if config.LogFilename != "" {
  251. panicLog, err := rotate.NewRotatableFileWriter(config.LogFilename, 0666)
  252. if err != nil {
  253. fmt.Printf("unable to set panic log output: %s\n%s\n", err, output)
  254. os.Exit(1)
  255. }
  256. defer panicLog.Close()
  257. jsonWriter = panicLog
  258. } else {
  259. jsonWriter = os.Stderr
  260. }
  261. enc := json.NewEncoder(jsonWriter)
  262. err = enc.Encode(logEvent)
  263. if err != nil {
  264. fmt.Printf("unable to serialize panic message to JSON: %s\n%s\n", err, output)
  265. os.Exit(1)
  266. }
  267. } else {
  268. fmt.Printf("no configuration JSON was loaded, cannot continue\n%s\n", output)
  269. os.Exit(1)
  270. }
  271. os.Exit(1)
  272. }