server.go 13 KB

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