v2ray.go 16 KB

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