v2ray.go 17 KB

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