v2ray.go 17 KB

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