v2ray.go 17 KB

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