v2ray.go 17 KB

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