server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. package dns
  2. //go:generate go run github.com/xtls/xray-core/common/errors/errorgen
  3. import (
  4. "context"
  5. "fmt"
  6. "log"
  7. "net/url"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/xtls/xray-core/app/router"
  12. "github.com/xtls/xray-core/common"
  13. "github.com/xtls/xray-core/common/errors"
  14. "github.com/xtls/xray-core/common/net"
  15. "github.com/xtls/xray-core/common/session"
  16. "github.com/xtls/xray-core/common/strmatcher"
  17. "github.com/xtls/xray-core/common/uuid"
  18. core "github.com/xtls/xray-core/core"
  19. "github.com/xtls/xray-core/features"
  20. "github.com/xtls/xray-core/features/dns"
  21. "github.com/xtls/xray-core/features/routing"
  22. )
  23. // Server is a DNS rely server.
  24. type Server struct {
  25. sync.Mutex
  26. hosts *StaticHosts
  27. clientIP net.IP
  28. clients []Client // clientIdx -> Client
  29. ipIndexMap []*MultiGeoIPMatcher // clientIdx -> *MultiGeoIPMatcher
  30. domainRules [][]string // clientIdx -> domainRuleIdx -> DomainRule
  31. domainMatcher strmatcher.IndexMatcher
  32. matcherInfos []DomainMatcherInfo // matcherIdx -> DomainMatcherInfo
  33. tag string
  34. }
  35. // DomainMatcherInfo contains information attached to index returned by Server.domainMatcher
  36. type DomainMatcherInfo struct {
  37. clientIdx uint16
  38. domainRuleIdx uint16
  39. }
  40. // MultiGeoIPMatcher for match
  41. type MultiGeoIPMatcher struct {
  42. matchers []*router.GeoIPMatcher
  43. }
  44. var errExpectedIPNonMatch = errors.New("expectIPs not match")
  45. // Match check ip match
  46. func (c *MultiGeoIPMatcher) Match(ip net.IP) bool {
  47. for _, matcher := range c.matchers {
  48. if matcher.Match(ip) {
  49. return true
  50. }
  51. }
  52. return false
  53. }
  54. // HasMatcher check has matcher
  55. func (c *MultiGeoIPMatcher) HasMatcher() bool {
  56. return len(c.matchers) > 0
  57. }
  58. func generateRandomTag() string {
  59. id := uuid.New()
  60. return "xray.system." + id.String()
  61. }
  62. // New creates a new DNS server with given configuration.
  63. func New(ctx context.Context, config *Config) (*Server, error) {
  64. server := &Server{
  65. clients: make([]Client, 0, len(config.NameServers)+len(config.NameServer)),
  66. tag: config.Tag,
  67. }
  68. if server.tag == "" {
  69. server.tag = generateRandomTag()
  70. }
  71. if len(config.ClientIp) > 0 {
  72. if len(config.ClientIp) != net.IPv4len && len(config.ClientIp) != net.IPv6len {
  73. return nil, newError("unexpected IP length", len(config.ClientIp))
  74. }
  75. server.clientIP = net.IP(config.ClientIp)
  76. }
  77. hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts)
  78. if err != nil {
  79. return nil, newError("failed to create hosts").Base(err)
  80. }
  81. server.hosts = hosts
  82. addNameServer := func(ns *NameServer) int {
  83. endpoint := ns.Address
  84. address := endpoint.Address.AsAddress()
  85. switch {
  86. case address.Family().IsDomain() && address.Domain() == "localhost":
  87. server.clients = append(server.clients, NewLocalNameServer())
  88. // Priotize local domains with specific TLDs or without any dot to local DNS
  89. // References:
  90. // https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml
  91. // https://unix.stackexchange.com/questions/92441/whats-the-difference-between-local-home-and-lan
  92. localTLDsAndDotlessDomains := []*NameServer_PriorityDomain{
  93. {Type: DomainMatchingType_Regex, Domain: "^[^.]+$"}, // This will only match domains without any dot
  94. {Type: DomainMatchingType_Subdomain, Domain: "local"},
  95. {Type: DomainMatchingType_Subdomain, Domain: "localdomain"},
  96. {Type: DomainMatchingType_Subdomain, Domain: "localhost"},
  97. {Type: DomainMatchingType_Subdomain, Domain: "lan"},
  98. {Type: DomainMatchingType_Subdomain, Domain: "home.arpa"},
  99. {Type: DomainMatchingType_Subdomain, Domain: "example"},
  100. {Type: DomainMatchingType_Subdomain, Domain: "invalid"},
  101. {Type: DomainMatchingType_Subdomain, Domain: "test"},
  102. }
  103. ns.PrioritizedDomain = append(ns.PrioritizedDomain, localTLDsAndDotlessDomains...)
  104. case address.Family().IsDomain() && strings.HasPrefix(address.Domain(), "https+local://"):
  105. // URI schemed string treated as domain
  106. // DOH Local mode
  107. u, err := url.Parse(address.Domain())
  108. if err != nil {
  109. log.Fatalln(newError("DNS config error").Base(err))
  110. }
  111. server.clients = append(server.clients, NewDoHLocalNameServer(u, server.clientIP))
  112. case address.Family().IsDomain() && strings.HasPrefix(address.Domain(), "https://"):
  113. // DOH Remote mode
  114. u, err := url.Parse(address.Domain())
  115. if err != nil {
  116. log.Fatalln(newError("DNS config error").Base(err))
  117. }
  118. idx := len(server.clients)
  119. server.clients = append(server.clients, nil)
  120. // need the core dispatcher, register DOHClient at callback
  121. common.Must(core.RequireFeatures(ctx, func(d routing.Dispatcher) {
  122. c, err := NewDoHNameServer(u, d, server.clientIP)
  123. if err != nil {
  124. log.Fatalln(newError("DNS config error").Base(err))
  125. }
  126. server.clients[idx] = c
  127. }))
  128. default:
  129. // UDP classic DNS mode
  130. dest := endpoint.AsDestination()
  131. if dest.Network == net.Network_Unknown {
  132. dest.Network = net.Network_UDP
  133. }
  134. if dest.Network == net.Network_UDP {
  135. idx := len(server.clients)
  136. server.clients = append(server.clients, nil)
  137. common.Must(core.RequireFeatures(ctx, func(d routing.Dispatcher) {
  138. server.clients[idx] = NewClassicNameServer(dest, d, server.clientIP)
  139. }))
  140. }
  141. }
  142. server.ipIndexMap = append(server.ipIndexMap, nil)
  143. return len(server.clients) - 1
  144. }
  145. if len(config.NameServers) > 0 {
  146. features.PrintDeprecatedFeatureWarning("simple DNS server")
  147. for _, destPB := range config.NameServers {
  148. addNameServer(&NameServer{Address: destPB})
  149. }
  150. }
  151. if len(config.NameServer) > 0 {
  152. clientIndices := []int{}
  153. domainRuleCount := 0
  154. for _, ns := range config.NameServer {
  155. idx := addNameServer(ns)
  156. clientIndices = append(clientIndices, idx)
  157. domainRuleCount += len(ns.PrioritizedDomain)
  158. }
  159. domainRules := make([][]string, len(server.clients))
  160. domainMatcher := &strmatcher.MatcherGroup{}
  161. matcherInfos := make([]DomainMatcherInfo, domainRuleCount+1) // matcher index starts from 1
  162. var geoIPMatcherContainer router.GeoIPMatcherContainer
  163. for nidx, ns := range config.NameServer {
  164. idx := clientIndices[nidx]
  165. // Establish domain rule matcher
  166. rules := []string{}
  167. ruleCurr := 0
  168. ruleIter := 0
  169. for _, domain := range ns.PrioritizedDomain {
  170. matcher, err := toStrMatcher(domain.Type, domain.Domain)
  171. if err != nil {
  172. return nil, newError("failed to create prioritized domain").Base(err).AtWarning()
  173. }
  174. midx := domainMatcher.Add(matcher)
  175. if midx >= uint32(len(matcherInfos)) { // This rarely happens according to current matcher's implementation
  176. newError("expanding domain matcher info array to size ", midx, " when adding ", matcher).AtDebug().WriteToLog()
  177. matcherInfos = append(matcherInfos, make([]DomainMatcherInfo, midx-uint32(len(matcherInfos))+1)...)
  178. }
  179. info := &matcherInfos[midx]
  180. info.clientIdx = uint16(idx)
  181. if ruleCurr < len(ns.OriginalRules) {
  182. info.domainRuleIdx = uint16(ruleCurr)
  183. rule := ns.OriginalRules[ruleCurr]
  184. if ruleCurr >= len(rules) {
  185. rules = append(rules, rule.Rule)
  186. }
  187. ruleIter++
  188. if ruleIter >= int(rule.Size) {
  189. ruleIter = 0
  190. ruleCurr++
  191. }
  192. } else { // No original rule, generate one according to current domain matcher (majorly for compatibility with tests)
  193. info.domainRuleIdx = uint16(len(rules))
  194. rules = append(rules, matcher.String())
  195. }
  196. }
  197. domainRules[idx] = rules
  198. // only add to ipIndexMap if GeoIP is configured
  199. if len(ns.Geoip) > 0 {
  200. var matchers []*router.GeoIPMatcher
  201. for _, geoip := range ns.Geoip {
  202. matcher, err := geoIPMatcherContainer.Add(geoip)
  203. if err != nil {
  204. return nil, newError("failed to create ip matcher").Base(err).AtWarning()
  205. }
  206. matchers = append(matchers, matcher)
  207. }
  208. matcher := &MultiGeoIPMatcher{matchers: matchers}
  209. server.ipIndexMap[idx] = matcher
  210. }
  211. }
  212. server.domainRules = domainRules
  213. server.domainMatcher = domainMatcher
  214. server.matcherInfos = matcherInfos
  215. }
  216. if len(server.clients) == 0 {
  217. server.clients = append(server.clients, NewLocalNameServer())
  218. server.ipIndexMap = append(server.ipIndexMap, nil)
  219. }
  220. return server, nil
  221. }
  222. // Type implements common.HasType.
  223. func (*Server) Type() interface{} {
  224. return dns.ClientType()
  225. }
  226. // Start implements common.Runnable.
  227. func (s *Server) Start() error {
  228. return nil
  229. }
  230. // Close implements common.Closable.
  231. func (s *Server) Close() error {
  232. return nil
  233. }
  234. func (s *Server) IsOwnLink(ctx context.Context) bool {
  235. inbound := session.InboundFromContext(ctx)
  236. return inbound != nil && inbound.Tag == s.tag
  237. }
  238. // Match check dns ip match geoip
  239. func (s *Server) Match(idx int, client Client, domain string, ips []net.IP) ([]net.IP, error) {
  240. var matcher *MultiGeoIPMatcher
  241. if idx < len(s.ipIndexMap) {
  242. matcher = s.ipIndexMap[idx]
  243. }
  244. if matcher == nil {
  245. return ips, nil
  246. }
  247. if !matcher.HasMatcher() {
  248. newError("domain ", domain, " server has no valid matcher: ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
  249. return ips, nil
  250. }
  251. newIps := []net.IP{}
  252. for _, ip := range ips {
  253. if matcher.Match(ip) {
  254. newIps = append(newIps, ip)
  255. }
  256. }
  257. if len(newIps) == 0 {
  258. return nil, errExpectedIPNonMatch
  259. }
  260. newError("domain ", domain, " expectIPs ", newIps, " matched at server ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
  261. return newIps, nil
  262. }
  263. func (s *Server) queryIPTimeout(idx int, client Client, domain string, option IPOption) ([]net.IP, error) {
  264. ctx, cancel := context.WithTimeout(context.Background(), time.Second*4)
  265. if len(s.tag) > 0 {
  266. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  267. Tag: s.tag,
  268. })
  269. }
  270. ips, err := client.QueryIP(ctx, domain, option)
  271. cancel()
  272. if err != nil {
  273. return ips, err
  274. }
  275. ips, err = s.Match(idx, client, domain, ips)
  276. return ips, err
  277. }
  278. // LookupIP implements dns.Client.
  279. func (s *Server) LookupIP(domain string) ([]net.IP, error) {
  280. return s.lookupIPInternal(domain, IPOption{
  281. IPv4Enable: true,
  282. IPv6Enable: true,
  283. })
  284. }
  285. // LookupIPv4 implements dns.IPv4Lookup.
  286. func (s *Server) LookupIPv4(domain string) ([]net.IP, error) {
  287. return s.lookupIPInternal(domain, IPOption{
  288. IPv4Enable: true,
  289. IPv6Enable: false,
  290. })
  291. }
  292. // LookupIPv6 implements dns.IPv6Lookup.
  293. func (s *Server) LookupIPv6(domain string) ([]net.IP, error) {
  294. return s.lookupIPInternal(domain, IPOption{
  295. IPv4Enable: false,
  296. IPv6Enable: true,
  297. })
  298. }
  299. func (s *Server) lookupStatic(domain string, option IPOption, depth int32) []net.Address {
  300. ips := s.hosts.LookupIP(domain, option)
  301. if ips == nil {
  302. return nil
  303. }
  304. if ips[0].Family().IsDomain() && depth < 5 {
  305. if newIPs := s.lookupStatic(ips[0].Domain(), option, depth+1); newIPs != nil {
  306. return newIPs
  307. }
  308. }
  309. return ips
  310. }
  311. func toNetIP(ips []net.Address) []net.IP {
  312. if len(ips) == 0 {
  313. return nil
  314. }
  315. netips := make([]net.IP, 0, len(ips))
  316. for _, ip := range ips {
  317. netips = append(netips, ip.IP())
  318. }
  319. return netips
  320. }
  321. func (s *Server) lookupIPInternal(domain string, option IPOption) ([]net.IP, error) {
  322. if domain == "" {
  323. return nil, newError("empty domain name")
  324. }
  325. domain = strings.ToLower(domain)
  326. // normalize the FQDN form query
  327. if domain[len(domain)-1] == '.' {
  328. domain = domain[:len(domain)-1]
  329. }
  330. ips := s.lookupStatic(domain, option, 0)
  331. if ips != nil && ips[0].Family().IsIP() {
  332. newError("returning ", len(ips), " IPs for domain ", domain).WriteToLog()
  333. return toNetIP(ips), nil
  334. }
  335. if ips != nil && ips[0].Family().IsDomain() {
  336. newdomain := ips[0].Domain()
  337. newError("domain replaced: ", domain, " -> ", newdomain).WriteToLog()
  338. domain = newdomain
  339. }
  340. var lastErr error
  341. var matchedClient Client
  342. if s.domainMatcher != nil {
  343. indices := s.domainMatcher.Match(domain)
  344. domainRules := []string{}
  345. matchingDNS := []string{}
  346. for _, idx := range indices {
  347. info := s.matcherInfos[idx]
  348. rule := s.domainRules[info.clientIdx][info.domainRuleIdx]
  349. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", rule, info.clientIdx))
  350. matchingDNS = append(matchingDNS, s.clients[info.clientIdx].Name())
  351. }
  352. if len(domainRules) > 0 {
  353. newError("domain ", domain, " matches following rules: ", domainRules).AtDebug().WriteToLog()
  354. }
  355. if len(matchingDNS) > 0 {
  356. newError("domain ", domain, " uses following DNS first: ", matchingDNS).AtDebug().WriteToLog()
  357. }
  358. for _, idx := range indices {
  359. clientIdx := int(s.matcherInfos[idx].clientIdx)
  360. matchedClient = s.clients[clientIdx]
  361. ips, err := s.queryIPTimeout(clientIdx, matchedClient, domain, option)
  362. if len(ips) > 0 {
  363. return ips, nil
  364. }
  365. if err == dns.ErrEmptyResponse {
  366. return nil, err
  367. }
  368. if err != nil {
  369. newError("failed to lookup ip for domain ", domain, " at server ", matchedClient.Name()).Base(err).WriteToLog()
  370. lastErr = err
  371. }
  372. }
  373. }
  374. for idx, client := range s.clients {
  375. if client == matchedClient {
  376. newError("domain ", domain, " at server ", client.Name(), " idx:", idx, " already lookup failed, just ignore").AtDebug().WriteToLog()
  377. continue
  378. }
  379. ips, err := s.queryIPTimeout(idx, client, domain, option)
  380. if len(ips) > 0 {
  381. return ips, nil
  382. }
  383. if err != nil {
  384. newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
  385. lastErr = err
  386. }
  387. if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch {
  388. return nil, err
  389. }
  390. }
  391. return nil, newError("returning nil for domain ", domain).Base(lastErr)
  392. }
  393. func init() {
  394. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  395. return New(ctx, config.(*Config))
  396. }))
  397. }