xray.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. package conf
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "os"
  7. "path/filepath"
  8. "sort"
  9. "strings"
  10. "github.com/xtls/xray-core/app/dispatcher"
  11. "github.com/xtls/xray-core/app/proxyman"
  12. "github.com/xtls/xray-core/app/router"
  13. "github.com/xtls/xray-core/app/stats"
  14. "github.com/xtls/xray-core/common/errors"
  15. "github.com/xtls/xray-core/common/net"
  16. "github.com/xtls/xray-core/common/platform"
  17. "github.com/xtls/xray-core/common/serial"
  18. core "github.com/xtls/xray-core/core"
  19. "github.com/xtls/xray-core/transport/internet"
  20. )
  21. var (
  22. inboundConfigLoader = NewJSONConfigLoader(ConfigCreatorCache{
  23. "tunnel": func() interface{} { return new(DokodemoConfig) },
  24. "dokodemo-door": func() interface{} { return new(DokodemoConfig) },
  25. "http": func() interface{} { return new(HTTPServerConfig) },
  26. "shadowsocks": func() interface{} { return new(ShadowsocksServerConfig) },
  27. "mixed": func() interface{} { return new(SocksServerConfig) },
  28. "socks": func() interface{} { return new(SocksServerConfig) },
  29. "vless": func() interface{} { return new(VLessInboundConfig) },
  30. "vmess": func() interface{} { return new(VMessInboundConfig) },
  31. "trojan": func() interface{} { return new(TrojanServerConfig) },
  32. "wireguard": func() interface{} { return &WireGuardConfig{IsClient: false} },
  33. "hysteria": func() interface{} { return new(HysteriaServerConfig) },
  34. "tun": func() interface{} { return new(TunConfig) },
  35. }, "protocol", "settings")
  36. outboundConfigLoader = NewJSONConfigLoader(ConfigCreatorCache{
  37. "block": func() interface{} { return new(BlackholeConfig) },
  38. "blackhole": func() interface{} { return new(BlackholeConfig) },
  39. "loopback": func() interface{} { return new(LoopbackConfig) },
  40. "direct": func() interface{} { return new(FreedomConfig) },
  41. "freedom": func() interface{} { return new(FreedomConfig) },
  42. "http": func() interface{} { return new(HTTPClientConfig) },
  43. "shadowsocks": func() interface{} { return new(ShadowsocksClientConfig) },
  44. "socks": func() interface{} { return new(SocksClientConfig) },
  45. "vless": func() interface{} { return new(VLessOutboundConfig) },
  46. "vmess": func() interface{} { return new(VMessOutboundConfig) },
  47. "trojan": func() interface{} { return new(TrojanClientConfig) },
  48. "hysteria": func() interface{} { return new(HysteriaClientConfig) },
  49. "dns": func() interface{} { return new(DNSOutboundConfig) },
  50. "wireguard": func() interface{} { return &WireGuardConfig{IsClient: true} },
  51. }, "protocol", "settings")
  52. )
  53. type SniffingConfig struct {
  54. Enabled bool `json:"enabled"`
  55. DestOverride *StringList `json:"destOverride"`
  56. DomainsExcluded *StringList `json:"domainsExcluded"`
  57. MetadataOnly bool `json:"metadataOnly"`
  58. RouteOnly bool `json:"routeOnly"`
  59. }
  60. // Build implements Buildable.
  61. func (c *SniffingConfig) Build() (*proxyman.SniffingConfig, error) {
  62. var p []string
  63. if c.DestOverride != nil {
  64. for _, protocol := range *c.DestOverride {
  65. switch strings.ToLower(protocol) {
  66. case "http":
  67. p = append(p, "http")
  68. case "tls", "https", "ssl":
  69. p = append(p, "tls")
  70. case "quic":
  71. p = append(p, "quic")
  72. case "fakedns", "fakedns+others":
  73. p = append(p, "fakedns")
  74. default:
  75. return nil, errors.New("unknown protocol: ", protocol)
  76. }
  77. }
  78. }
  79. var d []string
  80. if c.DomainsExcluded != nil {
  81. for _, domain := range *c.DomainsExcluded {
  82. d = append(d, strings.ToLower(domain))
  83. }
  84. }
  85. return &proxyman.SniffingConfig{
  86. Enabled: c.Enabled,
  87. DestinationOverride: p,
  88. DomainsExcluded: d,
  89. MetadataOnly: c.MetadataOnly,
  90. RouteOnly: c.RouteOnly,
  91. }, nil
  92. }
  93. type MuxConfig struct {
  94. Enabled bool `json:"enabled"`
  95. Concurrency int16 `json:"concurrency"`
  96. XudpConcurrency int16 `json:"xudpConcurrency"`
  97. XudpProxyUDP443 string `json:"xudpProxyUDP443"`
  98. }
  99. // Build creates MultiplexingConfig, Concurrency < 0 completely disables mux.
  100. func (m *MuxConfig) Build() (*proxyman.MultiplexingConfig, error) {
  101. switch m.XudpProxyUDP443 {
  102. case "":
  103. m.XudpProxyUDP443 = "reject"
  104. case "reject", "allow", "skip":
  105. default:
  106. return nil, errors.New(`unknown "xudpProxyUDP443": `, m.XudpProxyUDP443)
  107. }
  108. return &proxyman.MultiplexingConfig{
  109. Enabled: m.Enabled,
  110. Concurrency: int32(m.Concurrency),
  111. XudpConcurrency: int32(m.XudpConcurrency),
  112. XudpProxyUDP443: m.XudpProxyUDP443,
  113. }, nil
  114. }
  115. type InboundDetourConfig struct {
  116. Protocol string `json:"protocol"`
  117. PortList *PortList `json:"port"`
  118. ListenOn *Address `json:"listen"`
  119. Settings *json.RawMessage `json:"settings"`
  120. Tag string `json:"tag"`
  121. StreamSetting *StreamConfig `json:"streamSettings"`
  122. SniffingConfig *SniffingConfig `json:"sniffing"`
  123. }
  124. // Build implements Buildable.
  125. func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
  126. receiverSettings := &proxyman.ReceiverConfig{}
  127. // TUN inbound doesn't need port configuration as it uses network interface instead
  128. if strings.ToLower(c.Protocol) == "tun" {
  129. // Skip port validation for TUN
  130. } else if c.ListenOn == nil {
  131. // Listen on anyip, must set PortList
  132. if c.PortList == nil {
  133. return nil, errors.New("Listen on AnyIP but no Port(s) set in InboundDetour.")
  134. }
  135. receiverSettings.PortList = c.PortList.Build()
  136. } else {
  137. // Listen on specific IP or Unix Domain Socket
  138. receiverSettings.Listen = c.ListenOn.Build()
  139. listenDS := c.ListenOn.Family().IsDomain() && (filepath.IsAbs(c.ListenOn.Domain()) || c.ListenOn.Domain()[0] == '@')
  140. listenIP := c.ListenOn.Family().IsIP() || (c.ListenOn.Family().IsDomain() && c.ListenOn.Domain() == "localhost")
  141. if listenIP {
  142. // Listen on specific IP, must set PortList
  143. if c.PortList == nil {
  144. return nil, errors.New("Listen on specific ip without port in InboundDetour.")
  145. }
  146. // Listen on IP:Port
  147. receiverSettings.PortList = c.PortList.Build()
  148. } else if listenDS {
  149. if c.PortList != nil {
  150. // Listen on Unix Domain Socket, PortList should be nil
  151. receiverSettings.PortList = nil
  152. }
  153. } else {
  154. return nil, errors.New("unable to listen on domain address: ", c.ListenOn.Domain())
  155. }
  156. }
  157. if c.StreamSetting != nil {
  158. ss, err := c.StreamSetting.Build()
  159. if err != nil {
  160. return nil, err
  161. }
  162. receiverSettings.StreamSettings = ss
  163. }
  164. if c.SniffingConfig != nil {
  165. s, err := c.SniffingConfig.Build()
  166. if err != nil {
  167. return nil, errors.New("failed to build sniffing config").Base(err)
  168. }
  169. receiverSettings.SniffingSettings = s
  170. }
  171. settings := []byte("{}")
  172. if c.Settings != nil {
  173. settings = ([]byte)(*c.Settings)
  174. }
  175. rawConfig, err := inboundConfigLoader.LoadWithID(settings, c.Protocol)
  176. if err != nil {
  177. return nil, errors.New("failed to load inbound detour config for protocol ", c.Protocol).Base(err)
  178. }
  179. if dokodemoConfig, ok := rawConfig.(*DokodemoConfig); ok {
  180. receiverSettings.ReceiveOriginalDestination = dokodemoConfig.FollowRedirect
  181. }
  182. ts, err := rawConfig.(Buildable).Build()
  183. if err != nil {
  184. return nil, errors.New("failed to build inbound handler for protocol ", c.Protocol).Base(err)
  185. }
  186. return &core.InboundHandlerConfig{
  187. Tag: c.Tag,
  188. ReceiverSettings: serial.ToTypedMessage(receiverSettings),
  189. ProxySettings: serial.ToTypedMessage(ts),
  190. }, nil
  191. }
  192. type OutboundDetourConfig struct {
  193. Protocol string `json:"protocol"`
  194. SendThrough *string `json:"sendThrough"`
  195. Tag string `json:"tag"`
  196. Settings *json.RawMessage `json:"settings"`
  197. StreamSetting *StreamConfig `json:"streamSettings"`
  198. ProxySettings *ProxyConfig `json:"proxySettings"`
  199. MuxSettings *MuxConfig `json:"mux"`
  200. TargetStrategy string `json:"targetStrategy"`
  201. }
  202. func (c *OutboundDetourConfig) checkChainProxyConfig() error {
  203. if c.StreamSetting == nil || c.ProxySettings == nil || c.StreamSetting.SocketSettings == nil {
  204. return nil
  205. }
  206. if len(c.ProxySettings.Tag) > 0 && len(c.StreamSetting.SocketSettings.DialerProxy) > 0 {
  207. return errors.New("proxySettings.tag is conflicted with sockopt.dialerProxy").AtWarning()
  208. }
  209. return nil
  210. }
  211. // Build implements Buildable.
  212. func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
  213. senderSettings := &proxyman.SenderConfig{}
  214. switch strings.ToLower(c.TargetStrategy) {
  215. case "asis", "":
  216. senderSettings.TargetStrategy = internet.DomainStrategy_AS_IS
  217. case "useip":
  218. senderSettings.TargetStrategy = internet.DomainStrategy_USE_IP
  219. case "useipv4":
  220. senderSettings.TargetStrategy = internet.DomainStrategy_USE_IP4
  221. case "useipv6":
  222. senderSettings.TargetStrategy = internet.DomainStrategy_USE_IP6
  223. case "useipv4v6":
  224. senderSettings.TargetStrategy = internet.DomainStrategy_USE_IP46
  225. case "useipv6v4":
  226. senderSettings.TargetStrategy = internet.DomainStrategy_USE_IP64
  227. case "forceip":
  228. senderSettings.TargetStrategy = internet.DomainStrategy_FORCE_IP
  229. case "forceipv4":
  230. senderSettings.TargetStrategy = internet.DomainStrategy_FORCE_IP4
  231. case "forceipv6":
  232. senderSettings.TargetStrategy = internet.DomainStrategy_FORCE_IP6
  233. case "forceipv4v6":
  234. senderSettings.TargetStrategy = internet.DomainStrategy_FORCE_IP46
  235. case "forceipv6v4":
  236. senderSettings.TargetStrategy = internet.DomainStrategy_FORCE_IP64
  237. default:
  238. return nil, errors.New("unsupported target domain strategy: ", c.TargetStrategy)
  239. }
  240. if err := c.checkChainProxyConfig(); err != nil {
  241. return nil, err
  242. }
  243. if c.SendThrough != nil {
  244. address := ParseSendThough(c.SendThrough)
  245. //Check if CIDR exists
  246. if strings.Contains(*c.SendThrough, "/") {
  247. senderSettings.ViaCidr = strings.Split(*c.SendThrough, "/")[1]
  248. } else {
  249. if address.Family().IsDomain() {
  250. domain := address.Address.Domain()
  251. if domain != "origin" && domain != "srcip" {
  252. return nil, errors.New("unable to send through: " + address.String())
  253. }
  254. }
  255. }
  256. senderSettings.Via = address.Build()
  257. }
  258. if c.StreamSetting != nil {
  259. ss, err := c.StreamSetting.Build()
  260. if err != nil {
  261. return nil, errors.New("failed to build stream settings for outbound detour").Base(err)
  262. }
  263. senderSettings.StreamSettings = ss
  264. }
  265. if c.ProxySettings != nil {
  266. ps, err := c.ProxySettings.Build()
  267. if err != nil {
  268. return nil, errors.New("invalid outbound detour proxy settings").Base(err)
  269. }
  270. if ps.TransportLayerProxy {
  271. if senderSettings.StreamSettings != nil {
  272. if senderSettings.StreamSettings.SocketSettings != nil {
  273. senderSettings.StreamSettings.SocketSettings.DialerProxy = ps.Tag
  274. } else {
  275. senderSettings.StreamSettings.SocketSettings = &internet.SocketConfig{DialerProxy: ps.Tag}
  276. }
  277. } else {
  278. senderSettings.StreamSettings = &internet.StreamConfig{SocketSettings: &internet.SocketConfig{DialerProxy: ps.Tag}}
  279. }
  280. ps = nil
  281. }
  282. senderSettings.ProxySettings = ps
  283. }
  284. if c.MuxSettings != nil {
  285. ms, err := c.MuxSettings.Build()
  286. if err != nil {
  287. return nil, errors.New("failed to build Mux config").Base(err)
  288. }
  289. senderSettings.MultiplexSettings = ms
  290. }
  291. settings := []byte("{}")
  292. if c.Settings != nil {
  293. settings = ([]byte)(*c.Settings)
  294. }
  295. rawConfig, err := outboundConfigLoader.LoadWithID(settings, c.Protocol)
  296. if err != nil {
  297. return nil, errors.New("failed to load outbound detour config for protocol ", c.Protocol).Base(err)
  298. }
  299. ts, err := rawConfig.(Buildable).Build()
  300. if err != nil {
  301. return nil, errors.New("failed to build outbound handler for protocol ", c.Protocol).Base(err)
  302. }
  303. return &core.OutboundHandlerConfig{
  304. SenderSettings: serial.ToTypedMessage(senderSettings),
  305. Tag: c.Tag,
  306. ProxySettings: serial.ToTypedMessage(ts),
  307. }, nil
  308. }
  309. type StatsConfig struct{}
  310. // Build implements Buildable.
  311. func (c *StatsConfig) Build() (*stats.Config, error) {
  312. return &stats.Config{}, nil
  313. }
  314. type Config struct {
  315. // Deprecated: Global transport config is no longer used
  316. // left for returning error
  317. Transport map[string]json.RawMessage `json:"transport"`
  318. LogConfig *LogConfig `json:"log"`
  319. RouterConfig *RouterConfig `json:"routing"`
  320. DNSConfig *DNSConfig `json:"dns"`
  321. InboundConfigs []InboundDetourConfig `json:"inbounds"`
  322. OutboundConfigs []OutboundDetourConfig `json:"outbounds"`
  323. Policy *PolicyConfig `json:"policy"`
  324. API *APIConfig `json:"api"`
  325. Metrics *MetricsConfig `json:"metrics"`
  326. Stats *StatsConfig `json:"stats"`
  327. Reverse *ReverseConfig `json:"reverse"`
  328. FakeDNS *FakeDNSConfig `json:"fakeDns"`
  329. Observatory *ObservatoryConfig `json:"observatory"`
  330. BurstObservatory *BurstObservatoryConfig `json:"burstObservatory"`
  331. Version *VersionConfig `json:"version"`
  332. }
  333. func (c *Config) findInboundTag(tag string) int {
  334. found := -1
  335. for idx, ib := range c.InboundConfigs {
  336. if ib.Tag == tag {
  337. found = idx
  338. break
  339. }
  340. }
  341. return found
  342. }
  343. func (c *Config) findOutboundTag(tag string) int {
  344. found := -1
  345. for idx, ob := range c.OutboundConfigs {
  346. if ob.Tag == tag {
  347. found = idx
  348. break
  349. }
  350. }
  351. return found
  352. }
  353. // Override method accepts another Config overrides the current attribute
  354. func (c *Config) Override(o *Config, fn string) {
  355. // only process the non-deprecated members
  356. if o.LogConfig != nil {
  357. c.LogConfig = o.LogConfig
  358. }
  359. if o.RouterConfig != nil {
  360. c.RouterConfig = o.RouterConfig
  361. }
  362. if o.DNSConfig != nil {
  363. c.DNSConfig = o.DNSConfig
  364. }
  365. if o.Transport != nil {
  366. c.Transport = o.Transport
  367. }
  368. if o.Policy != nil {
  369. c.Policy = o.Policy
  370. }
  371. if o.API != nil {
  372. c.API = o.API
  373. }
  374. if o.Metrics != nil {
  375. c.Metrics = o.Metrics
  376. }
  377. if o.Stats != nil {
  378. c.Stats = o.Stats
  379. }
  380. if o.Reverse != nil {
  381. c.Reverse = o.Reverse
  382. }
  383. if o.FakeDNS != nil {
  384. c.FakeDNS = o.FakeDNS
  385. }
  386. if o.Observatory != nil {
  387. c.Observatory = o.Observatory
  388. }
  389. if o.BurstObservatory != nil {
  390. c.BurstObservatory = o.BurstObservatory
  391. }
  392. if o.Version != nil {
  393. c.Version = o.Version
  394. }
  395. // update the Inbound in slice if the only one in override config has same tag
  396. if len(o.InboundConfigs) > 0 {
  397. for i := range o.InboundConfigs {
  398. if idx := c.findInboundTag(o.InboundConfigs[i].Tag); idx > -1 {
  399. c.InboundConfigs[idx] = o.InboundConfigs[i]
  400. errors.LogInfo(context.Background(), "[", fn, "] updated inbound with tag: ", o.InboundConfigs[i].Tag)
  401. } else {
  402. c.InboundConfigs = append(c.InboundConfigs, o.InboundConfigs[i])
  403. errors.LogInfo(context.Background(), "[", fn, "] appended inbound with tag: ", o.InboundConfigs[i].Tag)
  404. }
  405. }
  406. }
  407. // update the Outbound in slice if the only one in override config has same tag
  408. if len(o.OutboundConfigs) > 0 {
  409. outboundPrepends := []OutboundDetourConfig{}
  410. for i := range o.OutboundConfigs {
  411. if idx := c.findOutboundTag(o.OutboundConfigs[i].Tag); idx > -1 {
  412. c.OutboundConfigs[idx] = o.OutboundConfigs[i]
  413. errors.LogInfo(context.Background(), "[", fn, "] updated outbound with tag: ", o.OutboundConfigs[i].Tag)
  414. } else {
  415. if strings.Contains(strings.ToLower(fn), "tail") {
  416. c.OutboundConfigs = append(c.OutboundConfigs, o.OutboundConfigs[i])
  417. errors.LogInfo(context.Background(), "[", fn, "] appended outbound with tag: ", o.OutboundConfigs[i].Tag)
  418. } else {
  419. outboundPrepends = append(outboundPrepends, o.OutboundConfigs[i])
  420. errors.LogInfo(context.Background(), "[", fn, "] prepend outbound with tag: ", o.OutboundConfigs[i].Tag)
  421. }
  422. }
  423. }
  424. if !strings.Contains(strings.ToLower(fn), "tail") && len(outboundPrepends) > 0 {
  425. c.OutboundConfigs = append(outboundPrepends, c.OutboundConfigs...)
  426. }
  427. }
  428. }
  429. // Build implements Buildable.
  430. func (c *Config) Build() (*core.Config, error) {
  431. if err := PostProcessConfigureFile(c); err != nil {
  432. return nil, errors.New("failed to post-process configuration file").Base(err)
  433. }
  434. config := &core.Config{
  435. App: []*serial.TypedMessage{
  436. serial.ToTypedMessage(&dispatcher.Config{}),
  437. serial.ToTypedMessage(&proxyman.InboundConfig{}),
  438. serial.ToTypedMessage(&proxyman.OutboundConfig{}),
  439. },
  440. }
  441. if c.API != nil {
  442. apiConf, err := c.API.Build()
  443. if err != nil {
  444. return nil, errors.New("failed to build API configuration").Base(err)
  445. }
  446. config.App = append(config.App, serial.ToTypedMessage(apiConf))
  447. }
  448. if c.Metrics != nil {
  449. metricsConf, err := c.Metrics.Build()
  450. if err != nil {
  451. return nil, errors.New("failed to build metrics configuration").Base(err)
  452. }
  453. config.App = append(config.App, serial.ToTypedMessage(metricsConf))
  454. }
  455. if c.Stats != nil {
  456. statsConf, err := c.Stats.Build()
  457. if err != nil {
  458. return nil, errors.New("failed to build stats configuration").Base(err)
  459. }
  460. config.App = append(config.App, serial.ToTypedMessage(statsConf))
  461. }
  462. var logConfMsg *serial.TypedMessage
  463. if c.LogConfig != nil {
  464. logConfMsg = serial.ToTypedMessage(c.LogConfig.Build())
  465. } else {
  466. logConfMsg = serial.ToTypedMessage(DefaultLogConfig())
  467. }
  468. // let logger module be the first App to start,
  469. // so that other modules could print log during initiating
  470. config.App = append([]*serial.TypedMessage{logConfMsg}, config.App...)
  471. if c.RouterConfig != nil {
  472. routerConfig, err := c.RouterConfig.Build()
  473. if err != nil {
  474. return nil, errors.New("failed to build routing configuration").Base(err)
  475. }
  476. config.App = append(config.App, serial.ToTypedMessage(routerConfig))
  477. }
  478. if c.DNSConfig != nil {
  479. dnsApp, err := c.DNSConfig.Build()
  480. if err != nil {
  481. return nil, errors.New("failed to build DNS configuration").Base(err)
  482. }
  483. config.App = append(config.App, serial.ToTypedMessage(dnsApp))
  484. }
  485. if c.Policy != nil {
  486. pc, err := c.Policy.Build()
  487. if err != nil {
  488. return nil, errors.New("failed to build policy configuration").Base(err)
  489. }
  490. config.App = append(config.App, serial.ToTypedMessage(pc))
  491. }
  492. if c.Reverse != nil {
  493. r, err := c.Reverse.Build()
  494. if err != nil {
  495. return nil, errors.New("failed to build reverse configuration").Base(err)
  496. }
  497. config.App = append(config.App, serial.ToTypedMessage(r))
  498. }
  499. if c.FakeDNS != nil {
  500. r, err := c.FakeDNS.Build()
  501. if err != nil {
  502. return nil, errors.New("failed to build fake DNS configuration").Base(err)
  503. }
  504. config.App = append([]*serial.TypedMessage{serial.ToTypedMessage(r)}, config.App...)
  505. }
  506. if c.Observatory != nil {
  507. r, err := c.Observatory.Build()
  508. if err != nil {
  509. return nil, errors.New("failed to build observatory configuration").Base(err)
  510. }
  511. config.App = append(config.App, serial.ToTypedMessage(r))
  512. }
  513. if c.BurstObservatory != nil {
  514. r, err := c.BurstObservatory.Build()
  515. if err != nil {
  516. return nil, errors.New("failed to build burst observatory configuration").Base(err)
  517. }
  518. config.App = append(config.App, serial.ToTypedMessage(r))
  519. }
  520. if c.Version != nil {
  521. r, err := c.Version.Build()
  522. if err != nil {
  523. return nil, errors.New("failed to build version configuration").Base(err)
  524. }
  525. config.App = append(config.App, serial.ToTypedMessage(r))
  526. }
  527. var inbounds []InboundDetourConfig
  528. if len(c.InboundConfigs) > 0 {
  529. inbounds = append(inbounds, c.InboundConfigs...)
  530. }
  531. if len(c.Transport) > 0 {
  532. return nil, errors.PrintRemovedFeatureError("Global transport config", "streamSettings in inbounds and outbounds")
  533. }
  534. for _, rawInboundConfig := range inbounds {
  535. ic, err := rawInboundConfig.Build()
  536. if err != nil {
  537. return nil, errors.New("failed to build inbound config with tag ", rawInboundConfig.Tag).Base(err)
  538. }
  539. config.Inbound = append(config.Inbound, ic)
  540. }
  541. var outbounds []OutboundDetourConfig
  542. if len(c.OutboundConfigs) > 0 {
  543. outbounds = append(outbounds, c.OutboundConfigs...)
  544. }
  545. for _, rawOutboundConfig := range outbounds {
  546. oc, err := rawOutboundConfig.Build()
  547. if err != nil {
  548. return nil, errors.New("failed to build outbound config with tag ", rawOutboundConfig.Tag).Base(err)
  549. }
  550. config.Outbound = append(config.Outbound, oc)
  551. }
  552. return config, nil
  553. }
  554. func (c *Config) BuildMPHCache(customMatcherFilePath *string) error {
  555. var geosite []*router.GeoSite
  556. deps := make(map[string][]string)
  557. uniqueGeosites := make(map[string]bool)
  558. uniqueTags := make(map[string]bool)
  559. matcherFilePath := platform.GetAssetLocation("matcher.cache")
  560. if customMatcherFilePath != nil {
  561. matcherFilePath = *customMatcherFilePath
  562. }
  563. processGeosite := func(dStr string) bool {
  564. prefix := ""
  565. if strings.HasPrefix(dStr, "geosite:") {
  566. prefix = "geosite:"
  567. } else if strings.HasPrefix(dStr, "ext-domain:") {
  568. prefix = "ext-domain:"
  569. }
  570. if prefix == "" {
  571. return false
  572. }
  573. key := strings.ToLower(dStr)
  574. country := strings.ToUpper(dStr[len(prefix):])
  575. if !uniqueGeosites[country] {
  576. ds, err := loadGeositeWithAttr("geosite.dat", country)
  577. if err == nil {
  578. uniqueGeosites[country] = true
  579. geosite = append(geosite, &router.GeoSite{CountryCode: key, Domain: ds})
  580. }
  581. }
  582. return true
  583. }
  584. processDomains := func(tag string, rawDomains []string) {
  585. var manualDomains []*router.Domain
  586. var dDeps []string
  587. for _, dStr := range rawDomains {
  588. if processGeosite(dStr) {
  589. dDeps = append(dDeps, strings.ToLower(dStr))
  590. } else {
  591. ds, err := parseDomainRule(dStr)
  592. if err == nil {
  593. manualDomains = append(manualDomains, ds...)
  594. }
  595. }
  596. }
  597. if len(manualDomains) > 0 {
  598. if !uniqueTags[tag] {
  599. uniqueTags[tag] = true
  600. geosite = append(geosite, &router.GeoSite{CountryCode: tag, Domain: manualDomains})
  601. }
  602. }
  603. if len(dDeps) > 0 {
  604. deps[tag] = append(deps[tag], dDeps...)
  605. }
  606. }
  607. // proccess rules
  608. if c.RouterConfig != nil {
  609. for _, rawRule := range c.RouterConfig.RuleList {
  610. type SimpleRule struct {
  611. RuleTag string `json:"ruleTag"`
  612. Domain *StringList `json:"domain"`
  613. Domains *StringList `json:"domains"`
  614. }
  615. var sr SimpleRule
  616. json.Unmarshal(rawRule, &sr)
  617. if sr.RuleTag == "" {
  618. continue
  619. }
  620. var allDomains []string
  621. if sr.Domain != nil {
  622. allDomains = append(allDomains, *sr.Domain...)
  623. }
  624. if sr.Domains != nil {
  625. allDomains = append(allDomains, *sr.Domains...)
  626. }
  627. processDomains(sr.RuleTag, allDomains)
  628. }
  629. }
  630. // proccess dns servers
  631. if c.DNSConfig != nil {
  632. for _, ns := range c.DNSConfig.Servers {
  633. if ns.Tag == "" {
  634. continue
  635. }
  636. processDomains(ns.Tag, ns.Domains)
  637. }
  638. }
  639. var hostIPs map[string][]string
  640. if c.DNSConfig != nil && c.DNSConfig.Hosts != nil {
  641. hostIPs = make(map[string][]string)
  642. var hostDeps []string
  643. var hostPatterns []string
  644. // use raw map to avoid expanding geosites
  645. var domains []string
  646. for domain := range c.DNSConfig.Hosts.Hosts {
  647. domains = append(domains, domain)
  648. }
  649. sort.Strings(domains)
  650. manualHostGroups := make(map[string][]*router.Domain)
  651. manualHostIPs := make(map[string][]string)
  652. manualHostNames := make(map[string]string)
  653. for _, domain := range domains {
  654. ha := c.DNSConfig.Hosts.Hosts[domain]
  655. m := getHostMapping(ha)
  656. var ips []string
  657. if m.ProxiedDomain != "" {
  658. ips = append(ips, m.ProxiedDomain)
  659. } else {
  660. for _, ip := range m.Ip {
  661. ips = append(ips, net.IPAddress(ip).String())
  662. }
  663. }
  664. if processGeosite(domain) {
  665. tag := strings.ToLower(domain)
  666. hostDeps = append(hostDeps, tag)
  667. hostIPs[tag] = ips
  668. hostPatterns = append(hostPatterns, domain)
  669. } else {
  670. // build manual domains by their destination IPs
  671. sort.Strings(ips)
  672. ipKey := strings.Join(ips, ",")
  673. ds, err := parseDomainRule(domain)
  674. if err == nil {
  675. manualHostGroups[ipKey] = append(manualHostGroups[ipKey], ds...)
  676. manualHostIPs[ipKey] = ips
  677. if _, ok := manualHostNames[ipKey]; !ok {
  678. manualHostNames[ipKey] = domain
  679. }
  680. }
  681. }
  682. }
  683. // create manual host groups
  684. var ipKeys []string
  685. for k := range manualHostGroups {
  686. ipKeys = append(ipKeys, k)
  687. }
  688. sort.Strings(ipKeys)
  689. for _, k := range ipKeys {
  690. tag := manualHostNames[k]
  691. geosite = append(geosite, &router.GeoSite{CountryCode: tag, Domain: manualHostGroups[k]})
  692. hostDeps = append(hostDeps, tag)
  693. hostIPs[tag] = manualHostIPs[k]
  694. // record tag _ORDER links the matcher to IP addresses
  695. hostPatterns = append(hostPatterns, tag)
  696. }
  697. deps["HOSTS"] = hostDeps
  698. hostIPs["_ORDER"] = hostPatterns
  699. }
  700. f, err := os.Create(matcherFilePath)
  701. if err != nil {
  702. return err
  703. }
  704. defer f.Close()
  705. var buf bytes.Buffer
  706. if err := router.SerializeGeoSiteList(geosite, deps, hostIPs, &buf); err != nil {
  707. return err
  708. }
  709. if _, err := f.Write(buf.Bytes()); err != nil {
  710. return err
  711. }
  712. return nil
  713. }
  714. // Convert string to Address.
  715. func ParseSendThough(Addr *string) *Address {
  716. var addr Address
  717. addr.Address = net.ParseAddress(strings.Split(*Addr, "/")[0])
  718. return &addr
  719. }