v2ray.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. Services map[string]*json.RawMessage `json:"services"`
  316. }
  317. func (c *Config) findInboundTag(tag string) int {
  318. found := -1
  319. for idx, ib := range c.InboundConfigs {
  320. if ib.Tag == tag {
  321. found = idx
  322. break
  323. }
  324. }
  325. return found
  326. }
  327. func (c *Config) findOutboundTag(tag string) int {
  328. found := -1
  329. for idx, ob := range c.OutboundConfigs {
  330. if ob.Tag == tag {
  331. found = idx
  332. break
  333. }
  334. }
  335. return found
  336. }
  337. func applyTransportConfig(s *StreamConfig, t *TransportConfig) {
  338. if s.TCPSettings == nil {
  339. s.TCPSettings = t.TCPConfig
  340. }
  341. if s.KCPSettings == nil {
  342. s.KCPSettings = t.KCPConfig
  343. }
  344. if s.WSSettings == nil {
  345. s.WSSettings = t.WSConfig
  346. }
  347. if s.HTTPSettings == nil {
  348. s.HTTPSettings = t.HTTPConfig
  349. }
  350. if s.DSSettings == nil {
  351. s.DSSettings = t.DSConfig
  352. }
  353. }
  354. // Build implements Buildable.
  355. func (c *Config) Build() (*core.Config, error) {
  356. if err := PostProcessConfigureFile(c); err != nil {
  357. return nil, err
  358. }
  359. config := &core.Config{
  360. App: []*serial.TypedMessage{
  361. serial.ToTypedMessage(&dispatcher.Config{}),
  362. serial.ToTypedMessage(&proxyman.InboundConfig{}),
  363. serial.ToTypedMessage(&proxyman.OutboundConfig{}),
  364. },
  365. }
  366. if c.API != nil {
  367. apiConf, err := c.API.Build()
  368. if err != nil {
  369. return nil, err
  370. }
  371. config.App = append(config.App, serial.ToTypedMessage(apiConf))
  372. }
  373. if c.Stats != nil {
  374. statsConf, err := c.Stats.Build()
  375. if err != nil {
  376. return nil, err
  377. }
  378. config.App = append(config.App, serial.ToTypedMessage(statsConf))
  379. }
  380. var logConfMsg *serial.TypedMessage
  381. if c.LogConfig != nil {
  382. logConfMsg = serial.ToTypedMessage(c.LogConfig.Build())
  383. } else {
  384. logConfMsg = serial.ToTypedMessage(DefaultLogConfig())
  385. }
  386. // let logger module be the first App to start,
  387. // so that other modules could print log during initiating
  388. config.App = append([]*serial.TypedMessage{logConfMsg}, config.App...)
  389. if c.RouterConfig != nil {
  390. routerConfig, err := c.RouterConfig.Build()
  391. if err != nil {
  392. return nil, err
  393. }
  394. config.App = append(config.App, serial.ToTypedMessage(routerConfig))
  395. }
  396. if c.DNSConfig != nil {
  397. dnsApp, err := c.DNSConfig.Build()
  398. if err != nil {
  399. return nil, newError("failed to parse DNS config").Base(err)
  400. }
  401. config.App = append(config.App, serial.ToTypedMessage(dnsApp))
  402. }
  403. if c.Policy != nil {
  404. pc, err := c.Policy.Build()
  405. if err != nil {
  406. return nil, err
  407. }
  408. config.App = append(config.App, serial.ToTypedMessage(pc))
  409. }
  410. if c.Reverse != nil {
  411. r, err := c.Reverse.Build()
  412. if err != nil {
  413. return nil, err
  414. }
  415. config.App = append(config.App, serial.ToTypedMessage(r))
  416. }
  417. if c.FakeDNS != nil {
  418. r, err := c.FakeDNS.Build()
  419. if err != nil {
  420. return nil, err
  421. }
  422. config.App = append(config.App, serial.ToTypedMessage(r))
  423. }
  424. if c.BrowserForwarder != nil {
  425. r, err := c.BrowserForwarder.Build()
  426. if err != nil {
  427. return nil, err
  428. }
  429. config.App = append(config.App, serial.ToTypedMessage(r))
  430. }
  431. if c.Observatory != nil {
  432. r, err := c.Observatory.Build()
  433. if err != nil {
  434. return nil, err
  435. }
  436. config.App = append(config.App, serial.ToTypedMessage(r))
  437. }
  438. // Load Additional Services that do not have a json translator
  439. if msg, err := c.BuildServices(c.Services); err != nil {
  440. developererr := newError("Loading a V2Ray Features as a service is intended for developers only. " +
  441. "This is used for developers to prototype new features or for an advanced client to use special features in V2Ray," +
  442. " instead of allowing end user to enable it without special tool and knowledge.")
  443. sb := strings.Builder{}
  444. return nil, newError("Cannot load service").Base(developererr).Base(err).Base(newError(sb.String()))
  445. } else { // nolint: golint
  446. // Using a else here is required to keep msg in scope
  447. config.App = append(config.App, msg...)
  448. }
  449. var inbounds []InboundDetourConfig
  450. if c.InboundConfig != nil {
  451. inbounds = append(inbounds, *c.InboundConfig)
  452. }
  453. if len(c.InboundDetours) > 0 {
  454. inbounds = append(inbounds, c.InboundDetours...)
  455. }
  456. if len(c.InboundConfigs) > 0 {
  457. inbounds = append(inbounds, c.InboundConfigs...)
  458. }
  459. // Backward compatibility.
  460. if len(inbounds) > 0 && inbounds[0].PortRange == nil && c.Port > 0 {
  461. inbounds[0].PortRange = &cfgcommon.PortRange{
  462. From: uint32(c.Port),
  463. To: uint32(c.Port),
  464. }
  465. }
  466. for _, rawInboundConfig := range inbounds {
  467. if c.Transport != nil {
  468. if rawInboundConfig.StreamSetting == nil {
  469. rawInboundConfig.StreamSetting = &StreamConfig{}
  470. }
  471. applyTransportConfig(rawInboundConfig.StreamSetting, c.Transport)
  472. }
  473. ic, err := rawInboundConfig.Build()
  474. if err != nil {
  475. return nil, err
  476. }
  477. config.Inbound = append(config.Inbound, ic)
  478. }
  479. var outbounds []OutboundDetourConfig
  480. if c.OutboundConfig != nil {
  481. outbounds = append(outbounds, *c.OutboundConfig)
  482. }
  483. if len(c.OutboundDetours) > 0 {
  484. outbounds = append(outbounds, c.OutboundDetours...)
  485. }
  486. if len(c.OutboundConfigs) > 0 {
  487. outbounds = append(outbounds, c.OutboundConfigs...)
  488. }
  489. for _, rawOutboundConfig := range outbounds {
  490. if c.Transport != nil {
  491. if rawOutboundConfig.StreamSetting == nil {
  492. rawOutboundConfig.StreamSetting = &StreamConfig{}
  493. }
  494. applyTransportConfig(rawOutboundConfig.StreamSetting, c.Transport)
  495. }
  496. oc, err := rawOutboundConfig.Build()
  497. if err != nil {
  498. return nil, err
  499. }
  500. config.Outbound = append(config.Outbound, oc)
  501. }
  502. return config, nil
  503. }