dns.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. package conf
  2. import (
  3. "encoding/json"
  4. "sort"
  5. "strings"
  6. "github.com/xtls/xray-core/app/dns"
  7. "github.com/xtls/xray-core/app/router"
  8. "github.com/xtls/xray-core/common/errors"
  9. "github.com/xtls/xray-core/common/net"
  10. )
  11. type NameServerConfig struct {
  12. Address *Address
  13. ClientIP *Address
  14. Port uint16
  15. SkipFallback bool
  16. Domains []string
  17. ExpectIPs StringList
  18. QueryStrategy string
  19. }
  20. func (c *NameServerConfig) UnmarshalJSON(data []byte) error {
  21. var address Address
  22. if err := json.Unmarshal(data, &address); err == nil {
  23. c.Address = &address
  24. return nil
  25. }
  26. var advanced struct {
  27. Address *Address `json:"address"`
  28. ClientIP *Address `json:"clientIp"`
  29. Port uint16 `json:"port"`
  30. SkipFallback bool `json:"skipFallback"`
  31. Domains []string `json:"domains"`
  32. ExpectIPs StringList `json:"expectIps"`
  33. QueryStrategy string `json:"queryStrategy"`
  34. }
  35. if err := json.Unmarshal(data, &advanced); err == nil {
  36. c.Address = advanced.Address
  37. c.ClientIP = advanced.ClientIP
  38. c.Port = advanced.Port
  39. c.SkipFallback = advanced.SkipFallback
  40. c.Domains = advanced.Domains
  41. c.ExpectIPs = advanced.ExpectIPs
  42. c.QueryStrategy = advanced.QueryStrategy
  43. return nil
  44. }
  45. return errors.New("failed to parse name server: ", string(data))
  46. }
  47. func toDomainMatchingType(t router.Domain_Type) dns.DomainMatchingType {
  48. switch t {
  49. case router.Domain_Domain:
  50. return dns.DomainMatchingType_Subdomain
  51. case router.Domain_Full:
  52. return dns.DomainMatchingType_Full
  53. case router.Domain_Plain:
  54. return dns.DomainMatchingType_Keyword
  55. case router.Domain_Regex:
  56. return dns.DomainMatchingType_Regex
  57. default:
  58. panic("unknown domain type")
  59. }
  60. }
  61. func (c *NameServerConfig) Build() (*dns.NameServer, error) {
  62. if c.Address == nil {
  63. return nil, errors.New("NameServer address is not specified.")
  64. }
  65. var domains []*dns.NameServer_PriorityDomain
  66. var originalRules []*dns.NameServer_OriginalRule
  67. for _, rule := range c.Domains {
  68. parsedDomain, err := parseDomainRule(rule)
  69. if err != nil {
  70. return nil, errors.New("invalid domain rule: ", rule).Base(err)
  71. }
  72. for _, pd := range parsedDomain {
  73. domains = append(domains, &dns.NameServer_PriorityDomain{
  74. Type: toDomainMatchingType(pd.Type),
  75. Domain: pd.Value,
  76. })
  77. }
  78. originalRules = append(originalRules, &dns.NameServer_OriginalRule{
  79. Rule: rule,
  80. Size: uint32(len(parsedDomain)),
  81. })
  82. }
  83. geoipList, err := ToCidrList(c.ExpectIPs)
  84. if err != nil {
  85. return nil, errors.New("invalid IP rule: ", c.ExpectIPs).Base(err)
  86. }
  87. var myClientIP []byte
  88. if c.ClientIP != nil {
  89. if !c.ClientIP.Family().IsIP() {
  90. return nil, errors.New("not an IP address:", c.ClientIP.String())
  91. }
  92. myClientIP = []byte(c.ClientIP.IP())
  93. }
  94. return &dns.NameServer{
  95. Address: &net.Endpoint{
  96. Network: net.Network_UDP,
  97. Address: c.Address.Build(),
  98. Port: uint32(c.Port),
  99. },
  100. ClientIp: myClientIP,
  101. SkipFallback: c.SkipFallback,
  102. PrioritizedDomain: domains,
  103. Geoip: geoipList,
  104. OriginalRules: originalRules,
  105. QueryStrategy: resolveQueryStrategy(c.QueryStrategy),
  106. }, nil
  107. }
  108. var typeMap = map[router.Domain_Type]dns.DomainMatchingType{
  109. router.Domain_Full: dns.DomainMatchingType_Full,
  110. router.Domain_Domain: dns.DomainMatchingType_Subdomain,
  111. router.Domain_Plain: dns.DomainMatchingType_Keyword,
  112. router.Domain_Regex: dns.DomainMatchingType_Regex,
  113. }
  114. // DNSConfig is a JSON serializable object for dns.Config.
  115. type DNSConfig struct {
  116. Servers []*NameServerConfig `json:"servers"`
  117. Hosts *HostsWrapper `json:"hosts"`
  118. ClientIP *Address `json:"clientIp"`
  119. Tag string `json:"tag"`
  120. QueryStrategy string `json:"queryStrategy"`
  121. DisableCache bool `json:"disableCache"`
  122. DisableFallback bool `json:"disableFallback"`
  123. DisableFallbackIfMatch bool `json:"disableFallbackIfMatch"`
  124. }
  125. type HostAddress struct {
  126. addr *Address
  127. addrs []*Address
  128. }
  129. // UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON
  130. func (h *HostAddress) UnmarshalJSON(data []byte) error {
  131. addr := new(Address)
  132. var addrs []*Address
  133. switch {
  134. case json.Unmarshal(data, &addr) == nil:
  135. h.addr = addr
  136. case json.Unmarshal(data, &addrs) == nil:
  137. h.addrs = addrs
  138. default:
  139. return errors.New("invalid address")
  140. }
  141. return nil
  142. }
  143. type HostsWrapper struct {
  144. Hosts map[string]*HostAddress
  145. }
  146. func getHostMapping(ha *HostAddress) *dns.Config_HostMapping {
  147. if ha.addr != nil {
  148. if ha.addr.Family().IsDomain() {
  149. return &dns.Config_HostMapping{
  150. ProxiedDomain: ha.addr.Domain(),
  151. }
  152. }
  153. return &dns.Config_HostMapping{
  154. Ip: [][]byte{ha.addr.IP()},
  155. }
  156. }
  157. ips := make([][]byte, 0, len(ha.addrs))
  158. for _, addr := range ha.addrs {
  159. if addr.Family().IsDomain() {
  160. return &dns.Config_HostMapping{
  161. ProxiedDomain: addr.Domain(),
  162. }
  163. }
  164. ips = append(ips, []byte(addr.IP()))
  165. }
  166. return &dns.Config_HostMapping{
  167. Ip: ips,
  168. }
  169. }
  170. // UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON
  171. func (m *HostsWrapper) UnmarshalJSON(data []byte) error {
  172. hosts := make(map[string]*HostAddress)
  173. err := json.Unmarshal(data, &hosts)
  174. if err == nil {
  175. m.Hosts = hosts
  176. return nil
  177. }
  178. return errors.New("invalid DNS hosts").Base(err)
  179. }
  180. // Build implements Buildable
  181. func (m *HostsWrapper) Build() ([]*dns.Config_HostMapping, error) {
  182. mappings := make([]*dns.Config_HostMapping, 0, 20)
  183. domains := make([]string, 0, len(m.Hosts))
  184. for domain := range m.Hosts {
  185. domains = append(domains, domain)
  186. }
  187. sort.Strings(domains)
  188. for _, domain := range domains {
  189. switch {
  190. case strings.HasPrefix(domain, "domain:"):
  191. domainName := domain[7:]
  192. if len(domainName) == 0 {
  193. return nil, errors.New("empty domain type of rule: ", domain)
  194. }
  195. mapping := getHostMapping(m.Hosts[domain])
  196. mapping.Type = dns.DomainMatchingType_Subdomain
  197. mapping.Domain = domainName
  198. mappings = append(mappings, mapping)
  199. case strings.HasPrefix(domain, "geosite:"):
  200. listName := domain[8:]
  201. if len(listName) == 0 {
  202. return nil, errors.New("empty geosite rule: ", domain)
  203. }
  204. geositeList, err := loadGeositeWithAttr("geosite.dat", listName)
  205. if err != nil {
  206. return nil, errors.New("failed to load geosite: ", listName).Base(err)
  207. }
  208. for _, d := range geositeList {
  209. mapping := getHostMapping(m.Hosts[domain])
  210. mapping.Type = typeMap[d.Type]
  211. mapping.Domain = d.Value
  212. mappings = append(mappings, mapping)
  213. }
  214. case strings.HasPrefix(domain, "regexp:"):
  215. regexpVal := domain[7:]
  216. if len(regexpVal) == 0 {
  217. return nil, errors.New("empty regexp type of rule: ", domain)
  218. }
  219. mapping := getHostMapping(m.Hosts[domain])
  220. mapping.Type = dns.DomainMatchingType_Regex
  221. mapping.Domain = regexpVal
  222. mappings = append(mappings, mapping)
  223. case strings.HasPrefix(domain, "keyword:"):
  224. keywordVal := domain[8:]
  225. if len(keywordVal) == 0 {
  226. return nil, errors.New("empty keyword type of rule: ", domain)
  227. }
  228. mapping := getHostMapping(m.Hosts[domain])
  229. mapping.Type = dns.DomainMatchingType_Keyword
  230. mapping.Domain = keywordVal
  231. mappings = append(mappings, mapping)
  232. case strings.HasPrefix(domain, "full:"):
  233. fullVal := domain[5:]
  234. if len(fullVal) == 0 {
  235. return nil, errors.New("empty full domain type of rule: ", domain)
  236. }
  237. mapping := getHostMapping(m.Hosts[domain])
  238. mapping.Type = dns.DomainMatchingType_Full
  239. mapping.Domain = fullVal
  240. mappings = append(mappings, mapping)
  241. case strings.HasPrefix(domain, "dotless:"):
  242. mapping := getHostMapping(m.Hosts[domain])
  243. mapping.Type = dns.DomainMatchingType_Regex
  244. switch substr := domain[8:]; {
  245. case substr == "":
  246. mapping.Domain = "^[^.]*$"
  247. case !strings.Contains(substr, "."):
  248. mapping.Domain = "^[^.]*" + substr + "[^.]*$"
  249. default:
  250. return nil, errors.New("substr in dotless rule should not contain a dot: ", substr)
  251. }
  252. mappings = append(mappings, mapping)
  253. case strings.HasPrefix(domain, "ext:"):
  254. kv := strings.Split(domain[4:], ":")
  255. if len(kv) != 2 {
  256. return nil, errors.New("invalid external resource: ", domain)
  257. }
  258. filename := kv[0]
  259. list := kv[1]
  260. geositeList, err := loadGeositeWithAttr(filename, list)
  261. if err != nil {
  262. return nil, errors.New("failed to load domain list: ", list, " from ", filename).Base(err)
  263. }
  264. for _, d := range geositeList {
  265. mapping := getHostMapping(m.Hosts[domain])
  266. mapping.Type = typeMap[d.Type]
  267. mapping.Domain = d.Value
  268. mappings = append(mappings, mapping)
  269. }
  270. default:
  271. mapping := getHostMapping(m.Hosts[domain])
  272. mapping.Type = dns.DomainMatchingType_Full
  273. mapping.Domain = domain
  274. mappings = append(mappings, mapping)
  275. }
  276. }
  277. return mappings, nil
  278. }
  279. // Build implements Buildable
  280. func (c *DNSConfig) Build() (*dns.Config, error) {
  281. config := &dns.Config{
  282. Tag: c.Tag,
  283. DisableCache: c.DisableCache,
  284. DisableFallback: c.DisableFallback,
  285. DisableFallbackIfMatch: c.DisableFallbackIfMatch,
  286. QueryStrategy: resolveQueryStrategy(c.QueryStrategy),
  287. }
  288. if c.ClientIP != nil {
  289. if !c.ClientIP.Family().IsIP() {
  290. return nil, errors.New("not an IP address:", c.ClientIP.String())
  291. }
  292. config.ClientIp = []byte(c.ClientIP.IP())
  293. }
  294. for _, server := range c.Servers {
  295. ns, err := server.Build()
  296. if err != nil {
  297. return nil, errors.New("failed to build nameserver").Base(err)
  298. }
  299. config.NameServer = append(config.NameServer, ns)
  300. }
  301. if c.Hosts != nil {
  302. staticHosts, err := c.Hosts.Build()
  303. if err != nil {
  304. return nil, errors.New("failed to build hosts").Base(err)
  305. }
  306. config.StaticHosts = append(config.StaticHosts, staticHosts...)
  307. }
  308. return config, nil
  309. }
  310. func resolveQueryStrategy(queryStrategy string) dns.QueryStrategy {
  311. switch strings.ToLower(queryStrategy) {
  312. case "useip", "use_ip", "use-ip":
  313. return dns.QueryStrategy_USE_IP
  314. case "useip4", "useipv4", "use_ip4", "use_ipv4", "use_ip_v4", "use-ip4", "use-ipv4", "use-ip-v4":
  315. return dns.QueryStrategy_USE_IP4
  316. case "useip6", "useipv6", "use_ip6", "use_ipv6", "use_ip_v6", "use-ip6", "use-ipv6", "use-ip-v6":
  317. return dns.QueryStrategy_USE_IP6
  318. default:
  319. return dns.QueryStrategy_USE_IP
  320. }
  321. }