main.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package main
  2. //go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg main -path Main
  3. import (
  4. "flag"
  5. "fmt"
  6. "io"
  7. "os"
  8. "os/signal"
  9. "path/filepath"
  10. "strings"
  11. "syscall"
  12. "v2ray.com/core"
  13. _ "v2ray.com/core/main/distro/all"
  14. )
  15. var (
  16. configFile string
  17. version = flag.Bool("version", false, "Show current version of V2Ray.")
  18. test = flag.Bool("test", false, "Test config file only, without launching V2Ray server.")
  19. format = flag.String("format", "json", "Format of input file.")
  20. )
  21. func init() {
  22. defaultConfigFile := ""
  23. workingDir, err := filepath.Abs(filepath.Dir(os.Args[0]))
  24. if err == nil {
  25. defaultConfigFile = filepath.Join(workingDir, "config.json")
  26. }
  27. flag.StringVar(&configFile, "config", defaultConfigFile, "Config file for this Point server.")
  28. }
  29. func GetConfigFormat() core.ConfigFormat {
  30. switch strings.ToLower(*format) {
  31. case "json":
  32. return core.ConfigFormat_JSON
  33. case "pb", "protobuf":
  34. return core.ConfigFormat_Protobuf
  35. default:
  36. return core.ConfigFormat_JSON
  37. }
  38. }
  39. func startV2Ray() (core.Server, error) {
  40. if len(configFile) == 0 {
  41. return nil, newError("config file is not set")
  42. }
  43. var configInput io.Reader
  44. if configFile == "stdin:" {
  45. configInput = os.Stdin
  46. } else {
  47. fixedFile := os.ExpandEnv(configFile)
  48. file, err := os.Open(fixedFile)
  49. if err != nil {
  50. return nil, newError("config file not readable").Base(err)
  51. }
  52. defer file.Close()
  53. configInput = file
  54. }
  55. config, err := core.LoadConfig(GetConfigFormat(), configInput)
  56. if err != nil {
  57. return nil, newError("failed to read config file: ", configFile).Base(err)
  58. }
  59. server, err := core.New(config)
  60. if err != nil {
  61. return nil, newError("failed to create initialize").Base(err)
  62. }
  63. return server, nil
  64. }
  65. func main() {
  66. flag.Parse()
  67. core.PrintVersion()
  68. if *version {
  69. return
  70. }
  71. server, err := startV2Ray()
  72. if err != nil {
  73. fmt.Println(err.Error())
  74. return
  75. }
  76. if *test {
  77. fmt.Println("Configuration OK.")
  78. return
  79. }
  80. if err := server.Start(); err != nil {
  81. fmt.Println("Failed to start", err)
  82. }
  83. osSignals := make(chan os.Signal, 1)
  84. signal.Notify(osSignals, os.Interrupt, os.Kill, syscall.SIGTERM)
  85. <-osSignals
  86. server.Close()
  87. }