dns.go 7.4 KB

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