v2ray.go 17 KB

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