dns.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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/net"
  9. )
  10. type NameServerConfig struct {
  11. Address *Address
  12. Port uint16
  13. Domains []string
  14. ExpectIPs StringList
  15. }
  16. func (c *NameServerConfig) UnmarshalJSON(data []byte) error {
  17. var address Address
  18. if err := json.Unmarshal(data, &address); err == nil {
  19. c.Address = &address
  20. return nil
  21. }
  22. var advanced struct {
  23. Address *Address `json:"address"`
  24. Port uint16 `json:"port"`
  25. Domains []string `json:"domains"`
  26. ExpectIPs StringList `json:"expectIps"`
  27. }
  28. if err := json.Unmarshal(data, &advanced); err == nil {
  29. c.Address = advanced.Address
  30. c.Port = advanced.Port
  31. c.Domains = advanced.Domains
  32. c.ExpectIPs = advanced.ExpectIPs
  33. return nil
  34. }
  35. return newError("failed to parse name server: ", string(data))
  36. }
  37. func toDomainMatchingType(t router.Domain_Type) dns.DomainMatchingType {
  38. switch t {
  39. case router.Domain_Domain:
  40. return dns.DomainMatchingType_Subdomain
  41. case router.Domain_Full:
  42. return dns.DomainMatchingType_Full
  43. case router.Domain_Plain:
  44. return dns.DomainMatchingType_Keyword
  45. case router.Domain_Regex:
  46. return dns.DomainMatchingType_Regex
  47. default:
  48. panic("unknown domain type")
  49. }
  50. }
  51. func (c *NameServerConfig) Build() (*dns.NameServer, error) {
  52. if c.Address == nil {
  53. return nil, newError("NameServer address is not specified.")
  54. }
  55. var domains []*dns.NameServer_PriorityDomain
  56. var originalRules []*dns.NameServer_OriginalRule
  57. for _, rule := range c.Domains {
  58. parsedDomain, err := parseDomainRule(rule)
  59. if err != nil {
  60. return nil, newError("invalid domain rule: ", rule).Base(err)
  61. }
  62. for _, pd := range parsedDomain {
  63. domains = append(domains, &dns.NameServer_PriorityDomain{
  64. Type: toDomainMatchingType(pd.Type),
  65. Domain: pd.Value,
  66. })
  67. }
  68. originalRules = append(originalRules, &dns.NameServer_OriginalRule{
  69. Rule: rule,
  70. Size: uint32(len(parsedDomain)),
  71. })
  72. }
  73. geoipList, err := toCidrList(c.ExpectIPs)
  74. if err != nil {
  75. return nil, newError("invalid IP rule: ", c.ExpectIPs).Base(err)
  76. }
  77. return &dns.NameServer{
  78. Address: &net.Endpoint{
  79. Network: net.Network_UDP,
  80. Address: c.Address.Build(),
  81. Port: uint32(c.Port),
  82. },
  83. PrioritizedDomain: domains,
  84. Geoip: geoipList,
  85. OriginalRules: originalRules,
  86. }, nil
  87. }
  88. var typeMap = map[router.Domain_Type]dns.DomainMatchingType{
  89. router.Domain_Full: dns.DomainMatchingType_Full,
  90. router.Domain_Domain: dns.DomainMatchingType_Subdomain,
  91. router.Domain_Plain: dns.DomainMatchingType_Keyword,
  92. router.Domain_Regex: dns.DomainMatchingType_Regex,
  93. }
  94. // DNSConfig is a JSON serializable object for dns.Config.
  95. type DNSConfig struct {
  96. Servers []*NameServerConfig `json:"servers"`
  97. Hosts map[string]*Address `json:"hosts"`
  98. ClientIP *Address `json:"clientIp"`
  99. Tag string `json:"tag"`
  100. }
  101. func getHostMapping(addr *Address) *dns.Config_HostMapping {
  102. if addr.Family().IsIP() {
  103. return &dns.Config_HostMapping{
  104. Ip: [][]byte{[]byte(addr.IP())},
  105. }
  106. } else {
  107. return &dns.Config_HostMapping{
  108. ProxiedDomain: addr.Domain(),
  109. }
  110. }
  111. }
  112. // Build implements Buildable
  113. func (c *DNSConfig) Build() (*dns.Config, error) {
  114. config := &dns.Config{
  115. Tag: c.Tag,
  116. }
  117. if c.ClientIP != nil {
  118. if !c.ClientIP.Family().IsIP() {
  119. return nil, newError("not an IP address:", c.ClientIP.String())
  120. }
  121. config.ClientIp = []byte(c.ClientIP.IP())
  122. }
  123. for _, server := range c.Servers {
  124. ns, err := server.Build()
  125. if err != nil {
  126. return nil, newError("failed to build nameserver").Base(err)
  127. }
  128. config.NameServer = append(config.NameServer, ns)
  129. }
  130. if c.Hosts != nil && len(c.Hosts) > 0 {
  131. domains := make([]string, 0, len(c.Hosts))
  132. for domain := range c.Hosts {
  133. domains = append(domains, domain)
  134. }
  135. sort.Strings(domains)
  136. for _, domain := range domains {
  137. addr := c.Hosts[domain]
  138. var mappings []*dns.Config_HostMapping
  139. switch {
  140. case strings.HasPrefix(domain, "domain:"):
  141. domainName := domain[7:]
  142. if len(domainName) == 0 {
  143. return nil, newError("empty domain type of rule: ", domain)
  144. }
  145. mapping := getHostMapping(addr)
  146. mapping.Type = dns.DomainMatchingType_Subdomain
  147. mapping.Domain = domainName
  148. mappings = append(mappings, mapping)
  149. case strings.HasPrefix(domain, "geosite:"):
  150. listName := domain[8:]
  151. if len(listName) == 0 {
  152. return nil, newError("empty geosite rule: ", domain)
  153. }
  154. domains, err := loadGeositeWithAttr("geosite.dat", listName)
  155. if err != nil {
  156. return nil, newError("failed to load geosite: ", listName).Base(err)
  157. }
  158. for _, d := range domains {
  159. mapping := getHostMapping(addr)
  160. mapping.Type = typeMap[d.Type]
  161. mapping.Domain = d.Value
  162. mappings = append(mappings, mapping)
  163. }
  164. case strings.HasPrefix(domain, "regexp:"):
  165. regexpVal := domain[7:]
  166. if len(regexpVal) == 0 {
  167. return nil, newError("empty regexp type of rule: ", domain)
  168. }
  169. mapping := getHostMapping(addr)
  170. mapping.Type = dns.DomainMatchingType_Regex
  171. mapping.Domain = regexpVal
  172. mappings = append(mappings, mapping)
  173. case strings.HasPrefix(domain, "keyword:"):
  174. keywordVal := domain[8:]
  175. if len(keywordVal) == 0 {
  176. return nil, newError("empty keyword type of rule: ", domain)
  177. }
  178. mapping := getHostMapping(addr)
  179. mapping.Type = dns.DomainMatchingType_Keyword
  180. mapping.Domain = keywordVal
  181. mappings = append(mappings, mapping)
  182. case strings.HasPrefix(domain, "full:"):
  183. fullVal := domain[5:]
  184. if len(fullVal) == 0 {
  185. return nil, newError("empty full domain type of rule: ", domain)
  186. }
  187. mapping := getHostMapping(addr)
  188. mapping.Type = dns.DomainMatchingType_Full
  189. mapping.Domain = fullVal
  190. mappings = append(mappings, mapping)
  191. case strings.HasPrefix(domain, "dotless:"):
  192. mapping := getHostMapping(addr)
  193. mapping.Type = dns.DomainMatchingType_Regex
  194. switch substr := domain[8:]; {
  195. case substr == "":
  196. mapping.Domain = "^[^.]*$"
  197. case !strings.Contains(substr, "."):
  198. mapping.Domain = "^[^.]*" + substr + "[^.]*$"
  199. default:
  200. return nil, newError("substr in dotless rule should not contain a dot: ", substr)
  201. }
  202. mappings = append(mappings, mapping)
  203. case strings.HasPrefix(domain, "ext:"):
  204. kv := strings.Split(domain[4:], ":")
  205. if len(kv) != 2 {
  206. return nil, newError("invalid external resource: ", domain)
  207. }
  208. filename := kv[0]
  209. list := kv[1]
  210. domains, err := loadGeositeWithAttr(filename, list)
  211. if err != nil {
  212. return nil, newError("failed to load domain list: ", list, " from ", filename).Base(err)
  213. }
  214. for _, d := range domains {
  215. mapping := getHostMapping(addr)
  216. mapping.Type = typeMap[d.Type]
  217. mapping.Domain = d.Value
  218. mappings = append(mappings, mapping)
  219. }
  220. default:
  221. mapping := getHostMapping(addr)
  222. mapping.Type = dns.DomainMatchingType_Full
  223. mapping.Domain = domain
  224. mappings = append(mappings, mapping)
  225. }
  226. config.StaticHosts = append(config.StaticHosts, mappings...)
  227. }
  228. }
  229. return config, nil
  230. }