v2ray.go 16 KB

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