v2ray.go 17 KB

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