json.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package json
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "os"
  6. "github.com/v2ray/v2ray-core/common/log"
  7. "github.com/v2ray/v2ray-core/config"
  8. )
  9. type ConnectionConfig struct {
  10. ProtocolString string `json:"protocol"`
  11. SettingsMessage json.RawMessage `json:"settings"`
  12. Type config.Type `json:"-"`
  13. }
  14. func (config *ConnectionConfig) Protocol() string {
  15. return config.ProtocolString
  16. }
  17. func (config *ConnectionConfig) Settings() interface{} {
  18. creator, found := configCache[getConfigKey(config.Protocol(), config.Type)]
  19. if !found {
  20. panic("Unknown protocol " + config.Protocol())
  21. }
  22. configObj := creator()
  23. err := json.Unmarshal(config.SettingsMessage, configObj)
  24. if err != nil {
  25. log.Error("Unable to parse connection config: %v", err)
  26. panic("Failed to parse connection config.")
  27. }
  28. return configObj
  29. }
  30. type LogConfig struct {
  31. AccessLogValue string `json:"access"`
  32. }
  33. func (config *LogConfig) AccessLog() string {
  34. return config.AccessLogValue
  35. }
  36. // Config is the config for Point server.
  37. type Config struct {
  38. PortValue uint16 `json:"port"` // Port of this Point server.
  39. LogConfigValue *LogConfig `json:"log"`
  40. InboundConfigValue *ConnectionConfig `json:"inbound"`
  41. OutboundConfigValue *ConnectionConfig `json:"outbound"`
  42. }
  43. func (config *Config) Port() uint16 {
  44. return config.PortValue
  45. }
  46. func (config *Config) LogConfig() config.LogConfig {
  47. if config.LogConfigValue == nil {
  48. return nil
  49. }
  50. return config.LogConfigValue
  51. }
  52. func (config *Config) InboundConfig() config.ConnectionConfig {
  53. if config.InboundConfigValue == nil {
  54. return nil
  55. }
  56. return config.InboundConfigValue
  57. }
  58. func (config *Config) OutboundConfig() config.ConnectionConfig {
  59. if config.OutboundConfigValue == nil {
  60. return nil
  61. }
  62. return config.OutboundConfigValue
  63. }
  64. func LoadConfig(file string) (*Config, error) {
  65. fixedFile := os.ExpandEnv(file)
  66. rawConfig, err := ioutil.ReadFile(fixedFile)
  67. if err != nil {
  68. log.Error("Failed to read server config file (%s): %v", file, err)
  69. return nil, err
  70. }
  71. jsonConfig := &Config{}
  72. err = json.Unmarshal(rawConfig, jsonConfig)
  73. if err != nil {
  74. log.Error("Failed to load server config: %v", err)
  75. return nil, err
  76. }
  77. jsonConfig.InboundConfigValue.Type = config.TypeInbound
  78. jsonConfig.OutboundConfigValue.Type = config.TypeOutbound
  79. return jsonConfig, err
  80. }