v2ray.go 16 KB

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