server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. switch {
  87. case address.Family().IsDomain() && address.Domain() == "localhost":
  88. server.clients = append(server.clients, NewLocalNameServer())
  89. // Priotize local domains with specific TLDs or without any dot to local DNS
  90. // References:
  91. // https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml
  92. // https://unix.stackexchange.com/questions/92441/whats-the-difference-between-local-home-and-lan
  93. localTLDsAndDotlessDomains := []*NameServer_PriorityDomain{
  94. {Type: DomainMatchingType_Regex, Domain: "^[^.]+$"}, // This will only match domains without any dot
  95. {Type: DomainMatchingType_Subdomain, Domain: "local"},
  96. {Type: DomainMatchingType_Subdomain, Domain: "localdomain"},
  97. {Type: DomainMatchingType_Subdomain, Domain: "localhost"},
  98. {Type: DomainMatchingType_Subdomain, Domain: "lan"},
  99. {Type: DomainMatchingType_Subdomain, Domain: "home.arpa"},
  100. {Type: DomainMatchingType_Subdomain, Domain: "example"},
  101. {Type: DomainMatchingType_Subdomain, Domain: "invalid"},
  102. {Type: DomainMatchingType_Subdomain, Domain: "test"},
  103. }
  104. ns.PrioritizedDomain = append(ns.PrioritizedDomain, localTLDsAndDotlessDomains...)
  105. case address.Family().IsDomain() && strings.HasPrefix(address.Domain(), "https+local://"):
  106. // URI schemed string treated as domain
  107. // DOH Local mode
  108. u, err := url.Parse(address.Domain())
  109. if err != nil {
  110. log.Fatalln(newError("DNS config error").Base(err))
  111. }
  112. server.clients = append(server.clients, NewDoHLocalNameServer(u, server.clientIP))
  113. case address.Family().IsDomain() && strings.HasPrefix(address.Domain(), "https://"):
  114. // DOH Remote mode
  115. u, err := url.Parse(address.Domain())
  116. if err != nil {
  117. log.Fatalln(newError("DNS config error").Base(err))
  118. }
  119. idx := len(server.clients)
  120. server.clients = append(server.clients, nil)
  121. // need the core dispatcher, register DOHClient at callback
  122. common.Must(core.RequireFeatures(ctx, func(d routing.Dispatcher) {
  123. c, err := NewDoHNameServer(u, d, server.clientIP)
  124. if err != nil {
  125. log.Fatalln(newError("DNS config error").Base(err))
  126. }
  127. server.clients[idx] = c
  128. }))
  129. default:
  130. // UDP classic DNS mode
  131. dest := endpoint.AsDestination()
  132. if dest.Network == net.Network_Unknown {
  133. dest.Network = net.Network_UDP
  134. }
  135. if dest.Network == net.Network_UDP {
  136. idx := len(server.clients)
  137. server.clients = append(server.clients, nil)
  138. common.Must(core.RequireFeatures(ctx, func(d routing.Dispatcher) {
  139. server.clients[idx] = NewClassicNameServer(dest, d, server.clientIP)
  140. }))
  141. }
  142. }
  143. server.ipIndexMap = append(server.ipIndexMap, nil)
  144. return len(server.clients) - 1
  145. }
  146. if len(config.NameServers) > 0 {
  147. features.PrintDeprecatedFeatureWarning("simple DNS server")
  148. for _, destPB := range config.NameServers {
  149. addNameServer(&NameServer{Address: destPB})
  150. }
  151. }
  152. if len(config.NameServer) > 0 {
  153. clientIndices := []int{}
  154. domainRuleCount := 0
  155. for _, ns := range config.NameServer {
  156. idx := addNameServer(ns)
  157. clientIndices = append(clientIndices, idx)
  158. domainRuleCount += len(ns.PrioritizedDomain)
  159. }
  160. domainRules := make([][]string, len(server.clients))
  161. domainMatcher := &strmatcher.MatcherGroup{}
  162. matcherInfos := make([]DomainMatcherInfo, domainRuleCount+1) // matcher index starts from 1
  163. var geoIPMatcherContainer router.GeoIPMatcherContainer
  164. for nidx, ns := range config.NameServer {
  165. idx := clientIndices[nidx]
  166. // Establish domain rule matcher
  167. rules := []string{}
  168. ruleCurr := 0
  169. ruleIter := 0
  170. for _, domain := range ns.PrioritizedDomain {
  171. matcher, err := toStrMatcher(domain.Type, domain.Domain)
  172. if err != nil {
  173. return nil, newError("failed to create prioritized domain").Base(err).AtWarning()
  174. }
  175. midx := domainMatcher.Add(matcher)
  176. if midx >= uint32(len(matcherInfos)) { // This rarely happens according to current matcher's implementation
  177. newError("expanding domain matcher info array to size ", midx, " when adding ", matcher).AtDebug().WriteToLog()
  178. matcherInfos = append(matcherInfos, make([]DomainMatcherInfo, midx-uint32(len(matcherInfos))+1)...)
  179. }
  180. info := &matcherInfos[midx]
  181. info.clientIdx = uint16(idx)
  182. if ruleCurr < len(ns.OriginalRules) {
  183. info.domainRuleIdx = uint16(ruleCurr)
  184. rule := ns.OriginalRules[ruleCurr]
  185. if ruleCurr >= len(rules) {
  186. rules = append(rules, rule.Rule)
  187. }
  188. ruleIter++
  189. if ruleIter >= int(rule.Size) {
  190. ruleIter = 0
  191. ruleCurr++
  192. }
  193. } else { // No original rule, generate one according to current domain matcher (majorly for compatibility with tests)
  194. info.domainRuleIdx = uint16(len(rules))
  195. rules = append(rules, matcher.String())
  196. }
  197. }
  198. domainRules[idx] = rules
  199. // only add to ipIndexMap if GeoIP is configured
  200. if len(ns.Geoip) > 0 {
  201. var matchers []*router.GeoIPMatcher
  202. for _, geoip := range ns.Geoip {
  203. matcher, err := geoIPMatcherContainer.Add(geoip)
  204. if err != nil {
  205. return nil, newError("failed to create ip matcher").Base(err).AtWarning()
  206. }
  207. matchers = append(matchers, matcher)
  208. }
  209. matcher := &MultiGeoIPMatcher{matchers: matchers}
  210. server.ipIndexMap[idx] = matcher
  211. }
  212. }
  213. server.domainRules = domainRules
  214. server.domainMatcher = domainMatcher
  215. server.matcherInfos = matcherInfos
  216. }
  217. if len(server.clients) == 0 {
  218. server.clients = append(server.clients, NewLocalNameServer())
  219. server.ipIndexMap = append(server.ipIndexMap, nil)
  220. }
  221. return server, nil
  222. }
  223. // Type implements common.HasType.
  224. func (*Server) Type() interface{} {
  225. return dns.ClientType()
  226. }
  227. // Start implements common.Runnable.
  228. func (s *Server) Start() error {
  229. return nil
  230. }
  231. // Close implements common.Closable.
  232. func (s *Server) Close() error {
  233. return nil
  234. }
  235. func (s *Server) IsOwnLink(ctx context.Context) bool {
  236. inbound := session.InboundFromContext(ctx)
  237. return inbound != nil && inbound.Tag == s.tag
  238. }
  239. // Match check dns ip match geoip
  240. func (s *Server) Match(idx int, client Client, domain string, ips []net.IP) ([]net.IP, error) {
  241. var matcher *MultiGeoIPMatcher
  242. if idx < len(s.ipIndexMap) {
  243. matcher = s.ipIndexMap[idx]
  244. }
  245. if matcher == nil {
  246. return ips, nil
  247. }
  248. if !matcher.HasMatcher() {
  249. newError("domain ", domain, " server has no valid matcher: ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
  250. return ips, nil
  251. }
  252. newIps := []net.IP{}
  253. for _, ip := range ips {
  254. if matcher.Match(ip) {
  255. newIps = append(newIps, ip)
  256. }
  257. }
  258. if len(newIps) == 0 {
  259. return nil, errExpectedIPNonMatch
  260. }
  261. newError("domain ", domain, " expectIPs ", newIps, " matched at server ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
  262. return newIps, nil
  263. }
  264. func (s *Server) queryIPTimeout(idx int, client Client, domain string, option IPOption) ([]net.IP, error) {
  265. ctx, cancel := context.WithTimeout(context.Background(), time.Second*4)
  266. if len(s.tag) > 0 {
  267. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  268. Tag: s.tag,
  269. })
  270. }
  271. ips, err := client.QueryIP(ctx, domain, option)
  272. cancel()
  273. if err != nil {
  274. return ips, err
  275. }
  276. ips, err = s.Match(idx, client, domain, ips)
  277. return ips, err
  278. }
  279. // LookupIP implements dns.Client.
  280. func (s *Server) LookupIP(domain string) ([]net.IP, error) {
  281. return s.lookupIPInternal(domain, IPOption{
  282. IPv4Enable: true,
  283. IPv6Enable: true,
  284. })
  285. }
  286. // LookupIPv4 implements dns.IPv4Lookup.
  287. func (s *Server) LookupIPv4(domain string) ([]net.IP, error) {
  288. return s.lookupIPInternal(domain, IPOption{
  289. IPv4Enable: true,
  290. IPv6Enable: false,
  291. })
  292. }
  293. // LookupIPv6 implements dns.IPv6Lookup.
  294. func (s *Server) LookupIPv6(domain string) ([]net.IP, error) {
  295. return s.lookupIPInternal(domain, IPOption{
  296. IPv4Enable: false,
  297. IPv6Enable: true,
  298. })
  299. }
  300. func (s *Server) lookupStatic(domain string, option IPOption, depth int32) []net.Address {
  301. ips := s.hosts.LookupIP(domain, option)
  302. if ips == nil {
  303. return nil
  304. }
  305. if ips[0].Family().IsDomain() && depth < 5 {
  306. if newIPs := s.lookupStatic(ips[0].Domain(), option, depth+1); newIPs != nil {
  307. return newIPs
  308. }
  309. }
  310. return ips
  311. }
  312. func toNetIP(ips []net.Address) []net.IP {
  313. if len(ips) == 0 {
  314. return nil
  315. }
  316. netips := make([]net.IP, 0, len(ips))
  317. for _, ip := range ips {
  318. netips = append(netips, ip.IP())
  319. }
  320. return netips
  321. }
  322. func (s *Server) lookupIPInternal(domain string, option IPOption) ([]net.IP, error) {
  323. if domain == "" {
  324. return nil, newError("empty domain name")
  325. }
  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. }