v2ray.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. package conf
  2. import (
  3. "encoding/json"
  4. "strings"
  5. "v2ray.com/core"
  6. "v2ray.com/core/app/dispatcher"
  7. "v2ray.com/core/app/proxyman"
  8. "v2ray.com/core/app/stats"
  9. "v2ray.com/core/common/serial"
  10. )
  11. var (
  12. inboundConfigLoader = NewJSONConfigLoader(ConfigCreatorCache{
  13. "dokodemo-door": func() interface{} { return new(DokodemoConfig) },
  14. "http": func() interface{} { return new(HttpServerConfig) },
  15. "shadowsocks": func() interface{} { return new(ShadowsocksServerConfig) },
  16. "socks": func() interface{} { return new(SocksServerConfig) },
  17. "vmess": func() interface{} { return new(VMessInboundConfig) },
  18. "mtproto": func() interface{} { return new(MTProtoServerConfig) },
  19. }, "protocol", "settings")
  20. outboundConfigLoader = NewJSONConfigLoader(ConfigCreatorCache{
  21. "blackhole": func() interface{} { return new(BlackholeConfig) },
  22. "freedom": func() interface{} { return new(FreedomConfig) },
  23. "shadowsocks": func() interface{} { return new(ShadowsocksClientConfig) },
  24. "vmess": func() interface{} { return new(VMessOutboundConfig) },
  25. "socks": func() interface{} { return new(SocksClientConfig) },
  26. "mtproto": func() interface{} { return new(MTProtoClientConfig) },
  27. "dns": func() interface{} { return new(DnsOutboundConfig) },
  28. }, "protocol", "settings")
  29. )
  30. func toProtocolList(s []string) ([]proxyman.KnownProtocols, error) {
  31. kp := make([]proxyman.KnownProtocols, 0, 8)
  32. for _, p := range s {
  33. switch strings.ToLower(p) {
  34. case "http":
  35. kp = append(kp, proxyman.KnownProtocols_HTTP)
  36. case "https", "tls", "ssl":
  37. kp = append(kp, proxyman.KnownProtocols_TLS)
  38. default:
  39. return nil, newError("Unknown protocol: ", p)
  40. }
  41. }
  42. return kp, nil
  43. }
  44. type SniffingConfig struct {
  45. Enabled bool `json:"enabled"`
  46. DestOverride *StringList `json:"destOverride"`
  47. }
  48. func (c *SniffingConfig) Build() (*proxyman.SniffingConfig, error) {
  49. var p []string
  50. if c.DestOverride != nil {
  51. for _, domainOverride := range *c.DestOverride {
  52. switch strings.ToLower(domainOverride) {
  53. case "http":
  54. p = append(p, "http")
  55. case "tls", "https", "ssl":
  56. p = append(p, "tls")
  57. default:
  58. return nil, newError("unknown protocol: ", domainOverride)
  59. }
  60. }
  61. }
  62. return &proxyman.SniffingConfig{
  63. Enabled: c.Enabled,
  64. DestinationOverride: p,
  65. }, nil
  66. }
  67. type MuxConfig struct {
  68. Enabled bool `json:"enabled"`
  69. Concurrency uint16 `json:"concurrency"`
  70. }
  71. func (c *MuxConfig) GetConcurrency() uint16 {
  72. if c.Concurrency == 0 {
  73. return 8
  74. }
  75. return c.Concurrency
  76. }
  77. type InboundDetourAllocationConfig struct {
  78. Strategy string `json:"strategy"`
  79. Concurrency *uint32 `json:"concurrency"`
  80. RefreshMin *uint32 `json:"refresh"`
  81. }
  82. // Build implements Buildable.
  83. func (c *InboundDetourAllocationConfig) Build() (*proxyman.AllocationStrategy, error) {
  84. config := new(proxyman.AllocationStrategy)
  85. switch strings.ToLower(c.Strategy) {
  86. case "always":
  87. config.Type = proxyman.AllocationStrategy_Always
  88. case "random":
  89. config.Type = proxyman.AllocationStrategy_Random
  90. case "external":
  91. config.Type = proxyman.AllocationStrategy_External
  92. default:
  93. return nil, newError("unknown allocation strategy: ", c.Strategy)
  94. }
  95. if c.Concurrency != nil {
  96. config.Concurrency = &proxyman.AllocationStrategy_AllocationStrategyConcurrency{
  97. Value: *c.Concurrency,
  98. }
  99. }
  100. if c.RefreshMin != nil {
  101. config.Refresh = &proxyman.AllocationStrategy_AllocationStrategyRefresh{
  102. Value: *c.RefreshMin,
  103. }
  104. }
  105. return config, nil
  106. }
  107. type InboundDetourConfig struct {
  108. Protocol string `json:"protocol"`
  109. PortRange *PortRange `json:"port"`
  110. ListenOn *Address `json:"listen"`
  111. Settings *json.RawMessage `json:"settings"`
  112. Tag string `json:"tag"`
  113. Allocation *InboundDetourAllocationConfig `json:"allocate"`
  114. StreamSetting *StreamConfig `json:"streamSettings"`
  115. DomainOverride *StringList `json:"domainOverride"`
  116. SniffingConfig *SniffingConfig `json:"sniffing"`
  117. }
  118. // Build implements Buildable.
  119. func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
  120. receiverSettings := &proxyman.ReceiverConfig{}
  121. if c.PortRange == nil {
  122. return nil, newError("port range not specified in InboundDetour.")
  123. }
  124. receiverSettings.PortRange = c.PortRange.Build()
  125. if c.ListenOn != nil {
  126. if c.ListenOn.Family().IsDomain() {
  127. return nil, newError("unable to listen on domain address: ", c.ListenOn.Domain())
  128. }
  129. receiverSettings.Listen = c.ListenOn.Build()
  130. }
  131. if c.Allocation != nil {
  132. concurrency := -1
  133. if c.Allocation.Concurrency != nil && c.Allocation.Strategy == "random" {
  134. concurrency = int(*c.Allocation.Concurrency)
  135. }
  136. portRange := int(c.PortRange.To - c.PortRange.From + 1)
  137. if concurrency >= 0 && concurrency >= portRange {
  138. return nil, newError("not enough ports. concurrency = ", concurrency, " ports: ", c.PortRange.From, " - ", c.PortRange.To)
  139. }
  140. as, err := c.Allocation.Build()
  141. if err != nil {
  142. return nil, err
  143. }
  144. receiverSettings.AllocationStrategy = as
  145. }
  146. if c.StreamSetting != nil {
  147. ss, err := c.StreamSetting.Build()
  148. if err != nil {
  149. return nil, err
  150. }
  151. receiverSettings.StreamSettings = ss
  152. }
  153. if c.SniffingConfig != nil {
  154. s, err := c.SniffingConfig.Build()
  155. if err != nil {
  156. return nil, newError("failed to build sniffing config").Base(err)
  157. }
  158. receiverSettings.SniffingSettings = s
  159. }
  160. if c.DomainOverride != nil {
  161. kp, err := toProtocolList(*c.DomainOverride)
  162. if err != nil {
  163. return nil, newError("failed to parse inbound detour config").Base(err)
  164. }
  165. receiverSettings.DomainOverride = kp
  166. }
  167. settings := []byte("{}")
  168. if c.Settings != nil {
  169. settings = ([]byte)(*c.Settings)
  170. }
  171. rawConfig, err := inboundConfigLoader.LoadWithID(settings, c.Protocol)
  172. if err != nil {
  173. return nil, newError("failed to load inbound detour config.").Base(err)
  174. }
  175. if dokodemoConfig, ok := rawConfig.(*DokodemoConfig); ok {
  176. receiverSettings.ReceiveOriginalDestination = dokodemoConfig.Redirect
  177. }
  178. ts, err := rawConfig.(Buildable).Build()
  179. if err != nil {
  180. return nil, err
  181. }
  182. return &core.InboundHandlerConfig{
  183. Tag: c.Tag,
  184. ReceiverSettings: serial.ToTypedMessage(receiverSettings),
  185. ProxySettings: serial.ToTypedMessage(ts),
  186. }, nil
  187. }
  188. type OutboundDetourConfig struct {
  189. Protocol string `json:"protocol"`
  190. SendThrough *Address `json:"sendThrough"`
  191. Tag string `json:"tag"`
  192. Settings *json.RawMessage `json:"settings"`
  193. StreamSetting *StreamConfig `json:"streamSettings"`
  194. ProxySettings *ProxyConfig `json:"proxySettings"`
  195. MuxSettings *MuxConfig `json:"mux"`
  196. }
  197. // Build implements Buildable.
  198. func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
  199. senderSettings := &proxyman.SenderConfig{}
  200. if c.SendThrough != nil {
  201. address := c.SendThrough
  202. if address.Family().IsDomain() {
  203. return nil, newError("unable to send through: " + address.String())
  204. }
  205. senderSettings.Via = address.Build()
  206. }
  207. if c.StreamSetting != nil {
  208. ss, err := c.StreamSetting.Build()
  209. if err != nil {
  210. return nil, err
  211. }
  212. senderSettings.StreamSettings = ss
  213. }
  214. if c.ProxySettings != nil {
  215. ps, err := c.ProxySettings.Build()
  216. if err != nil {
  217. return nil, newError("invalid outbound detour proxy settings.").Base(err)
  218. }
  219. senderSettings.ProxySettings = ps
  220. }
  221. if c.MuxSettings != nil && c.MuxSettings.Enabled {
  222. senderSettings.MultiplexSettings = &proxyman.MultiplexingConfig{
  223. Enabled: true,
  224. Concurrency: uint32(c.MuxSettings.GetConcurrency()),
  225. }
  226. }
  227. settings := []byte("{}")
  228. if c.Settings != nil {
  229. settings = ([]byte)(*c.Settings)
  230. }
  231. rawConfig, err := outboundConfigLoader.LoadWithID(settings, c.Protocol)
  232. if err != nil {
  233. return nil, newError("failed to parse to outbound detour config.").Base(err)
  234. }
  235. ts, err := rawConfig.(Buildable).Build()
  236. if err != nil {
  237. return nil, err
  238. }
  239. return &core.OutboundHandlerConfig{
  240. SenderSettings: serial.ToTypedMessage(senderSettings),
  241. Tag: c.Tag,
  242. ProxySettings: serial.ToTypedMessage(ts),
  243. }, nil
  244. }
  245. type StatsConfig struct{}
  246. func (c *StatsConfig) Build() (*stats.Config, error) {
  247. return &stats.Config{}, nil
  248. }
  249. type Config struct {
  250. Port uint16 `json:"port"` // Port of this Point server. Deprecated.
  251. LogConfig *LogConfig `json:"log"`
  252. RouterConfig *RouterConfig `json:"routing"`
  253. DNSConfig *DnsConfig `json:"dns"`
  254. InboundConfigs []InboundDetourConfig `json:"inbounds"`
  255. OutboundConfigs []OutboundDetourConfig `json:"outbounds"`
  256. InboundConfig *InboundDetourConfig `json:"inbound"` // Deprecated.
  257. OutboundConfig *OutboundDetourConfig `json:"outbound"` // Deprecated.
  258. InboundDetours []InboundDetourConfig `json:"inboundDetour"` // Deprecated.
  259. OutboundDetours []OutboundDetourConfig `json:"outboundDetour"` // Deprecated.
  260. Transport *TransportConfig `json:"transport"`
  261. Policy *PolicyConfig `json:"policy"`
  262. Api *ApiConfig `json:"api"`
  263. Stats *StatsConfig `json:"stats"`
  264. Reverse *ReverseConfig `json:"reverse"`
  265. }
  266. func applyTransportConfig(s *StreamConfig, t *TransportConfig) {
  267. if s.TCPSettings == nil {
  268. s.TCPSettings = t.TCPConfig
  269. }
  270. if s.KCPSettings == nil {
  271. s.KCPSettings = t.KCPConfig
  272. }
  273. if s.WSSettings == nil {
  274. s.WSSettings = t.WSConfig
  275. }
  276. if s.HTTPSettings == nil {
  277. s.HTTPSettings = t.HTTPConfig
  278. }
  279. if s.DSSettings == nil {
  280. s.DSSettings = t.DSConfig
  281. }
  282. }
  283. // Build implements Buildable.
  284. func (c *Config) Build() (*core.Config, error) {
  285. config := &core.Config{
  286. App: []*serial.TypedMessage{
  287. serial.ToTypedMessage(&dispatcher.Config{}),
  288. serial.ToTypedMessage(&proxyman.InboundConfig{}),
  289. serial.ToTypedMessage(&proxyman.OutboundConfig{}),
  290. },
  291. }
  292. if c.Api != nil {
  293. apiConf, err := c.Api.Build()
  294. if err != nil {
  295. return nil, err
  296. }
  297. config.App = append(config.App, serial.ToTypedMessage(apiConf))
  298. }
  299. if c.Stats != nil {
  300. statsConf, err := c.Stats.Build()
  301. if err != nil {
  302. return nil, err
  303. }
  304. config.App = append(config.App, serial.ToTypedMessage(statsConf))
  305. }
  306. if c.LogConfig != nil {
  307. config.App = append(config.App, serial.ToTypedMessage(c.LogConfig.Build()))
  308. } else {
  309. config.App = append(config.App, serial.ToTypedMessage(DefaultLogConfig()))
  310. }
  311. if c.RouterConfig != nil {
  312. routerConfig, err := c.RouterConfig.Build()
  313. if err != nil {
  314. return nil, err
  315. }
  316. config.App = append(config.App, serial.ToTypedMessage(routerConfig))
  317. }
  318. if c.DNSConfig != nil {
  319. dnsApp, err := c.DNSConfig.Build()
  320. if err != nil {
  321. return nil, newError("failed to parse DNS config").Base(err)
  322. }
  323. config.App = append(config.App, serial.ToTypedMessage(dnsApp))
  324. }
  325. if c.Policy != nil {
  326. pc, err := c.Policy.Build()
  327. if err != nil {
  328. return nil, err
  329. }
  330. config.App = append(config.App, serial.ToTypedMessage(pc))
  331. }
  332. if c.Reverse != nil {
  333. r, err := c.Reverse.Build()
  334. if err != nil {
  335. return nil, err
  336. }
  337. config.App = append(config.App, serial.ToTypedMessage(r))
  338. }
  339. var inbounds []InboundDetourConfig
  340. if c.InboundConfig != nil {
  341. inbounds = append(inbounds, *c.InboundConfig)
  342. }
  343. if len(c.InboundDetours) > 0 {
  344. inbounds = append(inbounds, c.InboundDetours...)
  345. }
  346. if len(c.InboundConfigs) > 0 {
  347. inbounds = append(inbounds, c.InboundConfigs...)
  348. }
  349. // Backward compatibility.
  350. if len(inbounds) > 0 && inbounds[0].PortRange == nil && c.Port > 0 {
  351. inbounds[0].PortRange = &PortRange{
  352. From: uint32(c.Port),
  353. To: uint32(c.Port),
  354. }
  355. }
  356. for _, rawInboundConfig := range inbounds {
  357. if c.Transport != nil {
  358. if rawInboundConfig.StreamSetting == nil {
  359. rawInboundConfig.StreamSetting = &StreamConfig{}
  360. }
  361. applyTransportConfig(rawInboundConfig.StreamSetting, c.Transport)
  362. }
  363. ic, err := rawInboundConfig.Build()
  364. if err != nil {
  365. return nil, err
  366. }
  367. config.Inbound = append(config.Inbound, ic)
  368. }
  369. var outbounds []OutboundDetourConfig
  370. if c.OutboundConfig != nil {
  371. outbounds = append(outbounds, *c.OutboundConfig)
  372. }
  373. if len(c.OutboundDetours) > 0 {
  374. outbounds = append(outbounds, c.OutboundDetours...)
  375. }
  376. if len(c.OutboundConfigs) > 0 {
  377. outbounds = append(outbounds, c.OutboundConfigs...)
  378. }
  379. for _, rawOutboundConfig := range outbounds {
  380. if c.Transport != nil {
  381. if rawOutboundConfig.StreamSetting == nil {
  382. rawOutboundConfig.StreamSetting = &StreamConfig{}
  383. }
  384. applyTransportConfig(rawOutboundConfig.StreamSetting, c.Transport)
  385. }
  386. oc, err := rawOutboundConfig.Build()
  387. if err != nil {
  388. return nil, err
  389. }
  390. config.Outbound = append(config.Outbound, oc)
  391. }
  392. return config, nil
  393. }