v2ray.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. package v4
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "path/filepath"
  7. "strings"
  8. "google.golang.org/protobuf/types/known/anypb"
  9. core "github.com/v2fly/v2ray-core/v5"
  10. "github.com/v2fly/v2ray-core/v5/app/dispatcher"
  11. "github.com/v2fly/v2ray-core/v5/app/proxyman"
  12. "github.com/v2fly/v2ray-core/v5/app/stats"
  13. "github.com/v2fly/v2ray-core/v5/common/serial"
  14. "github.com/v2fly/v2ray-core/v5/features"
  15. "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon"
  16. "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/loader"
  17. "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/muxcfg"
  18. "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/proxycfg"
  19. "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon/sniffer"
  20. "github.com/v2fly/v2ray-core/v5/infra/conf/synthetic/dns"
  21. "github.com/v2fly/v2ray-core/v5/infra/conf/synthetic/log"
  22. "github.com/v2fly/v2ray-core/v5/infra/conf/synthetic/router"
  23. "github.com/v2fly/v2ray-core/v5/infra/conf/v5cfg"
  24. )
  25. var (
  26. inboundConfigLoader = loader.NewJSONConfigLoader(loader.ConfigCreatorCache{
  27. "dokodemo-door": func() interface{} { return new(DokodemoConfig) },
  28. "http": func() interface{} { return new(HTTPServerConfig) },
  29. "shadowsocks": func() interface{} { return new(ShadowsocksServerConfig) },
  30. "socks": func() interface{} { return new(SocksServerConfig) },
  31. "vless": func() interface{} { return new(VLessInboundConfig) },
  32. "vmess": func() interface{} { return new(VMessInboundConfig) },
  33. "trojan": func() interface{} { return new(TrojanServerConfig) },
  34. }, "protocol", "settings")
  35. outboundConfigLoader = loader.NewJSONConfigLoader(loader.ConfigCreatorCache{
  36. "blackhole": func() interface{} { return new(BlackholeConfig) },
  37. "freedom": func() interface{} { return new(FreedomConfig) },
  38. "http": func() interface{} { return new(HTTPClientConfig) },
  39. "shadowsocks": func() interface{} { return new(ShadowsocksClientConfig) },
  40. "socks": func() interface{} { return new(SocksClientConfig) },
  41. "vless": func() interface{} { return new(VLessOutboundConfig) },
  42. "vmess": func() interface{} { return new(VMessOutboundConfig) },
  43. "trojan": func() interface{} { return new(TrojanClientConfig) },
  44. "dns": func() interface{} { return new(DNSOutboundConfig) },
  45. "loopback": func() interface{} { return new(LoopbackConfig) },
  46. }, "protocol", "settings")
  47. )
  48. func toProtocolList(s []string) ([]proxyman.KnownProtocols, error) {
  49. kp := make([]proxyman.KnownProtocols, 0, 8)
  50. for _, p := range s {
  51. switch strings.ToLower(p) {
  52. case "http":
  53. kp = append(kp, proxyman.KnownProtocols_HTTP)
  54. case "https", "tls", "ssl":
  55. kp = append(kp, proxyman.KnownProtocols_TLS)
  56. default:
  57. return nil, newError("Unknown protocol: ", p)
  58. }
  59. }
  60. return kp, nil
  61. }
  62. type InboundDetourAllocationConfig struct {
  63. Strategy string `json:"strategy"`
  64. Concurrency *uint32 `json:"concurrency"`
  65. RefreshMin *uint32 `json:"refresh"`
  66. }
  67. // Build implements Buildable.
  68. func (c *InboundDetourAllocationConfig) Build() (*proxyman.AllocationStrategy, error) {
  69. config := new(proxyman.AllocationStrategy)
  70. switch strings.ToLower(c.Strategy) {
  71. case "always":
  72. config.Type = proxyman.AllocationStrategy_Always
  73. case "random":
  74. config.Type = proxyman.AllocationStrategy_Random
  75. case "external":
  76. config.Type = proxyman.AllocationStrategy_External
  77. default:
  78. return nil, newError("unknown allocation strategy: ", c.Strategy)
  79. }
  80. if c.Concurrency != nil {
  81. config.Concurrency = &proxyman.AllocationStrategy_AllocationStrategyConcurrency{
  82. Value: *c.Concurrency,
  83. }
  84. }
  85. if c.RefreshMin != nil {
  86. config.Refresh = &proxyman.AllocationStrategy_AllocationStrategyRefresh{
  87. Value: *c.RefreshMin,
  88. }
  89. }
  90. return config, nil
  91. }
  92. type InboundDetourConfig struct {
  93. Protocol string `json:"protocol"`
  94. PortRange *cfgcommon.PortRange `json:"port"`
  95. ListenOn *cfgcommon.Address `json:"listen"`
  96. Settings *json.RawMessage `json:"settings"`
  97. Tag string `json:"tag"`
  98. Allocation *InboundDetourAllocationConfig `json:"allocate"`
  99. StreamSetting *StreamConfig `json:"streamSettings"`
  100. DomainOverride *cfgcommon.StringList `json:"domainOverride"`
  101. SniffingConfig *sniffer.SniffingConfig `json:"sniffing"`
  102. }
  103. // Build implements Buildable.
  104. func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
  105. receiverSettings := &proxyman.ReceiverConfig{}
  106. if c.ListenOn == nil {
  107. // Listen on anyip, must set PortRange
  108. if c.PortRange == nil {
  109. return nil, newError("Listen on AnyIP but no Port(s) set in InboundDetour.")
  110. }
  111. receiverSettings.PortRange = c.PortRange.Build()
  112. } else {
  113. // Listen on specific IP or Unix Domain Socket
  114. receiverSettings.Listen = c.ListenOn.Build()
  115. listenDS := c.ListenOn.Family().IsDomain() && (filepath.IsAbs(c.ListenOn.Domain()) || c.ListenOn.Domain()[0] == '@')
  116. listenIP := c.ListenOn.Family().IsIP() || (c.ListenOn.Family().IsDomain() && c.ListenOn.Domain() == "localhost")
  117. switch {
  118. case listenIP:
  119. // Listen on specific IP, must set PortRange
  120. if c.PortRange == nil {
  121. return nil, newError("Listen on specific ip without port in InboundDetour.")
  122. }
  123. // Listen on IP:Port
  124. receiverSettings.PortRange = c.PortRange.Build()
  125. case listenDS:
  126. if c.PortRange != nil {
  127. // Listen on Unix Domain Socket, PortRange should be nil
  128. receiverSettings.PortRange = nil
  129. }
  130. default:
  131. return nil, newError("unable to listen on domain address: ", c.ListenOn.Domain())
  132. }
  133. }
  134. if c.Allocation != nil {
  135. concurrency := -1
  136. if c.Allocation.Concurrency != nil && c.Allocation.Strategy == "random" {
  137. concurrency = int(*c.Allocation.Concurrency)
  138. }
  139. portRange := int(c.PortRange.To - c.PortRange.From + 1)
  140. if concurrency >= 0 && concurrency >= portRange {
  141. return nil, newError("not enough ports. concurrency = ", concurrency, " ports: ", c.PortRange.From, " - ", c.PortRange.To)
  142. }
  143. as, err := c.Allocation.Build()
  144. if err != nil {
  145. return nil, err
  146. }
  147. receiverSettings.AllocationStrategy = as
  148. }
  149. if c.StreamSetting != nil {
  150. ss, err := c.StreamSetting.Build()
  151. if err != nil {
  152. return nil, err
  153. }
  154. receiverSettings.StreamSettings = ss
  155. }
  156. if c.SniffingConfig != nil {
  157. s, err := c.SniffingConfig.Build()
  158. if err != nil {
  159. return nil, newError("failed to build sniffing config").Base(err)
  160. }
  161. receiverSettings.SniffingSettings = s
  162. }
  163. if c.DomainOverride != nil {
  164. kp, err := toProtocolList(*c.DomainOverride)
  165. if err != nil {
  166. return nil, newError("failed to parse inbound detour config").Base(err)
  167. }
  168. receiverSettings.DomainOverride = kp
  169. }
  170. settings := []byte("{}")
  171. if c.Settings != nil {
  172. settings = ([]byte)(*c.Settings)
  173. }
  174. rawConfig, err := inboundConfigLoader.LoadWithID(settings, c.Protocol)
  175. if err != nil {
  176. return nil, newError("failed to load inbound detour config.").Base(err)
  177. }
  178. if dokodemoConfig, ok := rawConfig.(*DokodemoConfig); ok {
  179. receiverSettings.ReceiveOriginalDestination = dokodemoConfig.Redirect
  180. }
  181. ts, err := rawConfig.(cfgcommon.Buildable).Build()
  182. if err != nil {
  183. return nil, err
  184. }
  185. return &core.InboundHandlerConfig{
  186. Tag: c.Tag,
  187. ReceiverSettings: serial.ToTypedMessage(receiverSettings),
  188. ProxySettings: serial.ToTypedMessage(ts),
  189. }, nil
  190. }
  191. type OutboundDetourConfig struct {
  192. Protocol string `json:"protocol"`
  193. SendThrough *cfgcommon.Address `json:"sendThrough"`
  194. Tag string `json:"tag"`
  195. Settings *json.RawMessage `json:"settings"`
  196. StreamSetting *StreamConfig `json:"streamSettings"`
  197. ProxySettings *proxycfg.ProxyConfig `json:"proxySettings"`
  198. MuxSettings *muxcfg.MuxConfig `json:"mux"`
  199. DomainStrategy string `json:"domainStrategy"`
  200. }
  201. // Build implements Buildable.
  202. func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
  203. senderSettings := &proxyman.SenderConfig{}
  204. if c.SendThrough != nil {
  205. address := c.SendThrough
  206. if address.Family().IsDomain() {
  207. return nil, newError("unable to send through: " + address.String())
  208. }
  209. senderSettings.Via = address.Build()
  210. }
  211. if c.StreamSetting != nil {
  212. ss, err := c.StreamSetting.Build()
  213. if err != nil {
  214. return nil, err
  215. }
  216. senderSettings.StreamSettings = ss
  217. }
  218. if c.ProxySettings != nil {
  219. ps, err := c.ProxySettings.Build()
  220. if err != nil {
  221. return nil, newError("invalid outbound detour proxy settings.").Base(err)
  222. }
  223. senderSettings.ProxySettings = ps
  224. }
  225. if c.MuxSettings != nil {
  226. senderSettings.MultiplexSettings = c.MuxSettings.Build()
  227. }
  228. senderSettings.DomainStrategy = proxyman.SenderConfig_AS_IS
  229. switch strings.ToLower(c.DomainStrategy) {
  230. case "useip", "use_ip", "use-ip":
  231. senderSettings.DomainStrategy = proxyman.SenderConfig_USE_IP
  232. case "useip4", "useipv4", "use_ip4", "use_ipv4", "use_ip_v4", "use-ip4", "use-ipv4", "use-ip-v4":
  233. senderSettings.DomainStrategy = proxyman.SenderConfig_USE_IP4
  234. case "useip6", "useipv6", "use_ip6", "use_ipv6", "use_ip_v6", "use-ip6", "use-ipv6", "use-ip-v6":
  235. senderSettings.DomainStrategy = proxyman.SenderConfig_USE_IP6
  236. }
  237. settings := []byte("{}")
  238. if c.Settings != nil {
  239. settings = ([]byte)(*c.Settings)
  240. }
  241. rawConfig, err := outboundConfigLoader.LoadWithID(settings, c.Protocol)
  242. if err != nil {
  243. return nil, newError("failed to parse to outbound detour config.").Base(err)
  244. }
  245. ts, err := rawConfig.(cfgcommon.Buildable).Build()
  246. if err != nil {
  247. return nil, err
  248. }
  249. return &core.OutboundHandlerConfig{
  250. SenderSettings: serial.ToTypedMessage(senderSettings),
  251. Tag: c.Tag,
  252. ProxySettings: serial.ToTypedMessage(ts),
  253. }, nil
  254. }
  255. type StatsConfig struct{}
  256. // Build implements Buildable.
  257. func (c *StatsConfig) Build() (*stats.Config, error) {
  258. return &stats.Config{}, nil
  259. }
  260. type Config struct {
  261. // Port of this Point server.
  262. // Deprecated: Port exists for historical compatibility
  263. // and should not be used.
  264. Port uint16 `json:"port"`
  265. // Deprecated: InboundConfig exists for historical compatibility
  266. // and should not be used.
  267. InboundConfig *InboundDetourConfig `json:"inbound"`
  268. // Deprecated: OutboundConfig exists for historical compatibility
  269. // and should not be used.
  270. OutboundConfig *OutboundDetourConfig `json:"outbound"`
  271. // Deprecated: InboundDetours exists for historical compatibility
  272. // and should not be used.
  273. InboundDetours []InboundDetourConfig `json:"inboundDetour"`
  274. // Deprecated: OutboundDetours exists for historical compatibility
  275. // and should not be used.
  276. OutboundDetours []OutboundDetourConfig `json:"outboundDetour"`
  277. LogConfig *log.LogConfig `json:"log"`
  278. RouterConfig *router.RouterConfig `json:"routing"`
  279. DNSConfig *dns.DNSConfig `json:"dns"`
  280. InboundConfigs []InboundDetourConfig `json:"inbounds"`
  281. OutboundConfigs []OutboundDetourConfig `json:"outbounds"`
  282. Transport *TransportConfig `json:"transport"`
  283. Policy *PolicyConfig `json:"policy"`
  284. API *APIConfig `json:"api"`
  285. Stats *StatsConfig `json:"stats"`
  286. Reverse *ReverseConfig `json:"reverse"`
  287. FakeDNS *dns.FakeDNSConfig `json:"fakeDns"`
  288. BrowserForwarder *BrowserForwarderConfig `json:"browserForwarder"`
  289. Observatory *ObservatoryConfig `json:"observatory"`
  290. BurstObservatory *BurstObservatoryConfig `json:"burstObservatory"`
  291. MultiObservatory *MultiObservatoryConfig `json:"multiObservatory"`
  292. Services map[string]*json.RawMessage `json:"services"`
  293. }
  294. func (c *Config) findInboundTag(tag string) int {
  295. found := -1
  296. for idx, ib := range c.InboundConfigs {
  297. if ib.Tag == tag {
  298. found = idx
  299. break
  300. }
  301. }
  302. return found
  303. }
  304. func (c *Config) findOutboundTag(tag string) int {
  305. found := -1
  306. for idx, ob := range c.OutboundConfigs {
  307. if ob.Tag == tag {
  308. found = idx
  309. break
  310. }
  311. }
  312. return found
  313. }
  314. func applyTransportConfig(s *StreamConfig, t *TransportConfig) {
  315. if s.TCPSettings == nil {
  316. s.TCPSettings = t.TCPConfig
  317. }
  318. if s.KCPSettings == nil {
  319. s.KCPSettings = t.KCPConfig
  320. }
  321. if s.WSSettings == nil {
  322. s.WSSettings = t.WSConfig
  323. }
  324. if s.HTTPSettings == nil {
  325. s.HTTPSettings = t.HTTPConfig
  326. }
  327. if s.DSSettings == nil {
  328. s.DSSettings = t.DSConfig
  329. }
  330. }
  331. // Build implements Buildable.
  332. func (c *Config) Build() (*core.Config, error) {
  333. if err := PostProcessConfigureFile(c); err != nil {
  334. return nil, err
  335. }
  336. config := &core.Config{
  337. App: []*anypb.Any{
  338. serial.ToTypedMessage(&dispatcher.Config{}),
  339. serial.ToTypedMessage(&proxyman.InboundConfig{}),
  340. serial.ToTypedMessage(&proxyman.OutboundConfig{}),
  341. },
  342. }
  343. if c.API != nil {
  344. apiConf, err := c.API.Build()
  345. if err != nil {
  346. return nil, err
  347. }
  348. config.App = append(config.App, serial.ToTypedMessage(apiConf))
  349. }
  350. if c.Stats != nil {
  351. statsConf, err := c.Stats.Build()
  352. if err != nil {
  353. return nil, err
  354. }
  355. config.App = append(config.App, serial.ToTypedMessage(statsConf))
  356. }
  357. var logConfMsg *anypb.Any
  358. if c.LogConfig != nil {
  359. logConfMsg = serial.ToTypedMessage(c.LogConfig.Build())
  360. } else {
  361. logConfMsg = serial.ToTypedMessage(log.DefaultLogConfig())
  362. }
  363. // let logger module be the first App to start,
  364. // so that other modules could print log during initiating
  365. config.App = append([]*anypb.Any{logConfMsg}, config.App...)
  366. if c.RouterConfig != nil {
  367. routerConfig, err := c.RouterConfig.Build()
  368. if err != nil {
  369. return nil, err
  370. }
  371. config.App = append(config.App, serial.ToTypedMessage(routerConfig))
  372. }
  373. if c.FakeDNS != nil {
  374. features.PrintDeprecatedFeatureWarning("root fakedns settings")
  375. if c.DNSConfig != nil {
  376. c.DNSConfig.FakeDNS = c.FakeDNS
  377. } else {
  378. c.DNSConfig = &dns.DNSConfig{
  379. FakeDNS: c.FakeDNS,
  380. }
  381. }
  382. }
  383. if c.DNSConfig != nil {
  384. dnsApp, err := c.DNSConfig.Build()
  385. if err != nil {
  386. return nil, newError("failed to parse DNS config").Base(err)
  387. }
  388. config.App = append(config.App, serial.ToTypedMessage(dnsApp))
  389. }
  390. if c.Policy != nil {
  391. pc, err := c.Policy.Build()
  392. if err != nil {
  393. return nil, err
  394. }
  395. config.App = append(config.App, serial.ToTypedMessage(pc))
  396. }
  397. if c.Reverse != nil {
  398. r, err := c.Reverse.Build()
  399. if err != nil {
  400. return nil, err
  401. }
  402. config.App = append(config.App, serial.ToTypedMessage(r))
  403. }
  404. if c.BrowserForwarder != nil {
  405. r, err := c.BrowserForwarder.Build()
  406. if err != nil {
  407. return nil, err
  408. }
  409. config.App = append(config.App, serial.ToTypedMessage(r))
  410. }
  411. if c.Observatory != nil {
  412. r, err := c.Observatory.Build()
  413. if err != nil {
  414. return nil, err
  415. }
  416. config.App = append(config.App, serial.ToTypedMessage(r))
  417. }
  418. if c.BurstObservatory != nil {
  419. r, err := c.BurstObservatory.Build()
  420. if err != nil {
  421. return nil, err
  422. }
  423. config.App = append(config.App, serial.ToTypedMessage(r))
  424. }
  425. if c.MultiObservatory != nil {
  426. r, err := c.MultiObservatory.Build()
  427. if err != nil {
  428. return nil, err
  429. }
  430. config.App = append(config.App, serial.ToTypedMessage(r))
  431. }
  432. // Load Additional Services that do not have a json translator
  433. for serviceName, service := range c.Services {
  434. servicePackedConfig, err := v5cfg.LoadHeterogeneousConfigFromRawJSON(context.Background(), "service", serviceName, *service)
  435. if err != nil {
  436. return nil, newError(fmt.Sprintf("failed to parse %v config in Services", serviceName)).Base(err)
  437. }
  438. config.App = append(config.App, serial.ToTypedMessage(servicePackedConfig))
  439. }
  440. var inbounds []InboundDetourConfig
  441. if c.InboundConfig != nil {
  442. inbounds = append(inbounds, *c.InboundConfig)
  443. }
  444. if len(c.InboundDetours) > 0 {
  445. inbounds = append(inbounds, c.InboundDetours...)
  446. }
  447. if len(c.InboundConfigs) > 0 {
  448. inbounds = append(inbounds, c.InboundConfigs...)
  449. }
  450. // Backward compatibility.
  451. if len(inbounds) > 0 && inbounds[0].PortRange == nil && c.Port > 0 {
  452. inbounds[0].PortRange = &cfgcommon.PortRange{
  453. From: uint32(c.Port),
  454. To: uint32(c.Port),
  455. }
  456. }
  457. for _, rawInboundConfig := range inbounds {
  458. if c.Transport != nil {
  459. if rawInboundConfig.StreamSetting == nil {
  460. rawInboundConfig.StreamSetting = &StreamConfig{}
  461. }
  462. applyTransportConfig(rawInboundConfig.StreamSetting, c.Transport)
  463. }
  464. ic, err := rawInboundConfig.Build()
  465. if err != nil {
  466. return nil, err
  467. }
  468. config.Inbound = append(config.Inbound, ic)
  469. }
  470. var outbounds []OutboundDetourConfig
  471. if c.OutboundConfig != nil {
  472. outbounds = append(outbounds, *c.OutboundConfig)
  473. }
  474. if len(c.OutboundDetours) > 0 {
  475. outbounds = append(outbounds, c.OutboundDetours...)
  476. }
  477. if len(c.OutboundConfigs) > 0 {
  478. outbounds = append(outbounds, c.OutboundConfigs...)
  479. }
  480. for _, rawOutboundConfig := range outbounds {
  481. if c.Transport != nil {
  482. if rawOutboundConfig.StreamSetting == nil {
  483. rawOutboundConfig.StreamSetting = &StreamConfig{}
  484. }
  485. applyTransportConfig(rawOutboundConfig.StreamSetting, c.Transport)
  486. }
  487. oc, err := rawOutboundConfig.Build()
  488. if err != nil {
  489. return nil, err
  490. }
  491. config.Outbound = append(config.Outbound, oc)
  492. }
  493. return config, nil
  494. }