server.go 13 KB

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