server.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. // +build !confonly
  2. package dns
  3. //go:generate errorgen
  4. import (
  5. "context"
  6. "fmt"
  7. "strings"
  8. "sync"
  9. "time"
  10. "v2ray.com/core"
  11. "v2ray.com/core/app/router"
  12. "v2ray.com/core/common"
  13. "v2ray.com/core/common/errors"
  14. "v2ray.com/core/common/net"
  15. "v2ray.com/core/common/session"
  16. "v2ray.com/core/common/strmatcher"
  17. "v2ray.com/core/common/uuid"
  18. "v2ray.com/core/features"
  19. "v2ray.com/core/features/dns"
  20. "v2ray.com/core/features/routing"
  21. )
  22. // Server is a DNS rely server.
  23. type Server struct {
  24. sync.Mutex
  25. hosts *StaticHosts
  26. clients []Client
  27. clientIP net.IP
  28. domainMatcher strmatcher.IndexMatcher
  29. domainIndexMap map[uint32]uint32
  30. ipIndexMap map[uint32]*MultiGeoIPMatcher
  31. tag string
  32. }
  33. // MultiGeoIPMatcher for match
  34. type MultiGeoIPMatcher struct {
  35. matchers []*router.GeoIPMatcher
  36. }
  37. var errExpectedIPNonMatch = errors.New("expected ip not match")
  38. // Match check ip match
  39. func (c *MultiGeoIPMatcher) Match(ip net.IP) bool {
  40. for _, matcher := range c.matchers {
  41. if matcher.Match(ip) {
  42. return true
  43. }
  44. }
  45. return false
  46. }
  47. // HasMatcher check has matcher
  48. func (c *MultiGeoIPMatcher) HasMatcher() bool {
  49. return len(c.matchers) > 0
  50. }
  51. func generateRandomTag() string {
  52. id := uuid.New()
  53. return "v2ray.system." + id.String()
  54. }
  55. // New creates a new DNS server with given configuration.
  56. func New(ctx context.Context, config *Config) (*Server, error) {
  57. server := &Server{
  58. clients: make([]Client, 0, len(config.NameServers)+len(config.NameServer)),
  59. tag: config.Tag,
  60. }
  61. if server.tag == "" {
  62. server.tag = generateRandomTag()
  63. }
  64. if len(config.ClientIp) > 0 {
  65. if len(config.ClientIp) != 4 && len(config.ClientIp) != 16 {
  66. return nil, newError("unexpected IP length", len(config.ClientIp))
  67. }
  68. server.clientIP = net.IP(config.ClientIp)
  69. }
  70. hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts)
  71. if err != nil {
  72. return nil, newError("failed to create hosts").Base(err)
  73. }
  74. server.hosts = hosts
  75. addNameServer := func(endpoint *net.Endpoint) int {
  76. address := endpoint.Address.AsAddress()
  77. if address.Family().IsDomain() && address.Domain() == "localhost" {
  78. server.clients = append(server.clients, NewLocalNameServer())
  79. newError("DNS: localhost inited").AtInfo().WriteToLog()
  80. } else if address.Family().IsDomain() && strings.HasPrefix(address.Domain(), "DOHL_") {
  81. dohHost := address.Domain()[5:]
  82. server.clients = append(server.clients, NewDoHLocalNameServer(dohHost, server.clientIP))
  83. newError("DNS: DOH - Local inited for https://", dohHost).AtInfo().WriteToLog()
  84. } else if address.Family().IsDomain() && strings.HasPrefix(address.Domain(), "DOH_") {
  85. // DOH_ prefix makes net.Address think it's a domain
  86. // need to process the real address here.
  87. dohHost := address.Domain()[4:]
  88. dohAddr := net.ParseAddress(dohHost)
  89. dohIP := dohHost
  90. var dests []net.Destination
  91. if dohAddr.Family().IsDomain() {
  92. // resolve DOH server in advance
  93. ips, err := net.LookupIP(dohAddr.Domain())
  94. if err != nil || len(ips) == 0 {
  95. return 0
  96. }
  97. for _, ip := range ips {
  98. dohIP := ip.String()
  99. if len(ip) == net.IPv6len {
  100. dohIP = fmt.Sprintf("[%s]", dohIP)
  101. }
  102. dohdest, _ := net.ParseDestination(fmt.Sprintf("tcp:%s:443", dohIP))
  103. dests = append(dests, dohdest)
  104. }
  105. } else {
  106. // rfc8484, DOH service only use port 443
  107. dest, err := net.ParseDestination(fmt.Sprintf("tcp:%s:443", dohIP))
  108. if err != nil {
  109. return 0
  110. }
  111. dests = []net.Destination{dest}
  112. }
  113. // need the core dispatcher, register DOHClient at callback
  114. idx := len(server.clients)
  115. server.clients = append(server.clients, nil)
  116. common.Must(core.RequireFeatures(ctx, func(d routing.Dispatcher) {
  117. server.clients[idx] = NewDoHNameServer(dests, dohHost, d, server.clientIP)
  118. newError("DNS: DOH - Remote client inited for https://", dohHost).AtInfo().WriteToLog()
  119. }))
  120. } else {
  121. dest := endpoint.AsDestination()
  122. if dest.Network == net.Network_Unknown {
  123. dest.Network = net.Network_UDP
  124. }
  125. if dest.Network == net.Network_UDP {
  126. idx := len(server.clients)
  127. server.clients = append(server.clients, nil)
  128. common.Must(core.RequireFeatures(ctx, func(d routing.Dispatcher) {
  129. server.clients[idx] = NewClassicNameServer(dest, d, server.clientIP)
  130. }))
  131. }
  132. newError("DNS: UDP client inited for ", dest.NetAddr()).AtInfo().WriteToLog()
  133. }
  134. return len(server.clients) - 1
  135. }
  136. if len(config.NameServers) > 0 {
  137. features.PrintDeprecatedFeatureWarning("simple DNS server")
  138. for _, destPB := range config.NameServers {
  139. addNameServer(destPB)
  140. }
  141. }
  142. if len(config.NameServer) > 0 {
  143. domainMatcher := &strmatcher.MatcherGroup{}
  144. domainIndexMap := make(map[uint32]uint32)
  145. ipIndexMap := make(map[uint32]*MultiGeoIPMatcher)
  146. var geoIPMatcherContainer router.GeoIPMatcherContainer
  147. for _, ns := range config.NameServer {
  148. idx := addNameServer(ns.Address)
  149. for _, domain := range ns.PrioritizedDomain {
  150. matcher, err := toStrMatcher(domain.Type, domain.Domain)
  151. if err != nil {
  152. return nil, newError("failed to create prioritized domain").Base(err).AtWarning()
  153. }
  154. midx := domainMatcher.Add(matcher)
  155. domainIndexMap[midx] = uint32(idx)
  156. }
  157. var matchers []*router.GeoIPMatcher
  158. for _, geoip := range ns.Geoip {
  159. matcher, err := geoIPMatcherContainer.Add(geoip)
  160. if err != nil {
  161. return nil, newError("failed to create ip matcher").Base(err).AtWarning()
  162. }
  163. matchers = append(matchers, matcher)
  164. }
  165. matcher := &MultiGeoIPMatcher{matchers: matchers}
  166. ipIndexMap[uint32(idx)] = matcher
  167. }
  168. server.domainMatcher = domainMatcher
  169. server.domainIndexMap = domainIndexMap
  170. server.ipIndexMap = ipIndexMap
  171. }
  172. if len(server.clients) == 0 {
  173. server.clients = append(server.clients, NewLocalNameServer())
  174. }
  175. return server, nil
  176. }
  177. // Type implements common.HasType.
  178. func (*Server) Type() interface{} {
  179. return dns.ClientType()
  180. }
  181. // Start implements common.Runnable.
  182. func (s *Server) Start() error {
  183. return nil
  184. }
  185. // Close implements common.Closable.
  186. func (s *Server) Close() error {
  187. return nil
  188. }
  189. func (s *Server) IsOwnLink(ctx context.Context) bool {
  190. inbound := session.InboundFromContext(ctx)
  191. return inbound != nil && inbound.Tag == s.tag
  192. }
  193. // Match check dns ip match geoip
  194. func (s *Server) Match(idx uint32, client Client, domain string, ips []net.IP) ([]net.IP, error) {
  195. matcher, exist := s.ipIndexMap[idx]
  196. if !exist {
  197. newError("domain ", domain, " server not in ipIndexMap: ", client.Name(), " idx:", idx, " just return").AtDebug().WriteToLog()
  198. return ips, nil
  199. }
  200. if !matcher.HasMatcher() {
  201. newError("domain ", domain, " server has not valid matcher: ", client.Name(), " idx:", idx, " just return").AtDebug().WriteToLog()
  202. return ips, nil
  203. }
  204. newIps := []net.IP{}
  205. for _, ip := range ips {
  206. if matcher.Match(ip) {
  207. newIps = append(newIps, ip)
  208. newError("domain ", domain, " ip ", ip, " is match at server ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
  209. } else {
  210. newError("domain ", domain, " ip ", ip, " is not match at server ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
  211. }
  212. }
  213. if len(newIps) == 0 {
  214. return nil, errExpectedIPNonMatch
  215. }
  216. return newIps, nil
  217. }
  218. func (s *Server) queryIPTimeout(idx uint32, client Client, domain string, option IPOption) ([]net.IP, error) {
  219. ctx, cancel := context.WithTimeout(context.Background(), time.Second*4)
  220. if len(s.tag) > 0 {
  221. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  222. Tag: s.tag,
  223. })
  224. }
  225. ips, err := client.QueryIP(ctx, domain, option)
  226. cancel()
  227. if err != nil {
  228. return ips, err
  229. }
  230. ips, err = s.Match(idx, client, domain, ips)
  231. return ips, err
  232. }
  233. // LookupIP implements dns.Client.
  234. func (s *Server) LookupIP(domain string) ([]net.IP, error) {
  235. return s.lookupIPInternal(domain, IPOption{
  236. IPv4Enable: true,
  237. IPv6Enable: true,
  238. })
  239. }
  240. // LookupIPv4 implements dns.IPv4Lookup.
  241. func (s *Server) LookupIPv4(domain string) ([]net.IP, error) {
  242. return s.lookupIPInternal(domain, IPOption{
  243. IPv4Enable: true,
  244. IPv6Enable: false,
  245. })
  246. }
  247. // LookupIPv6 implements dns.IPv6Lookup.
  248. func (s *Server) LookupIPv6(domain string) ([]net.IP, error) {
  249. return s.lookupIPInternal(domain, IPOption{
  250. IPv4Enable: false,
  251. IPv6Enable: true,
  252. })
  253. }
  254. func (s *Server) lookupStatic(domain string, option IPOption, depth int32) []net.Address {
  255. ips := s.hosts.LookupIP(domain, option)
  256. if ips == nil {
  257. return nil
  258. }
  259. if ips[0].Family().IsDomain() && depth < 5 {
  260. if newIPs := s.lookupStatic(ips[0].Domain(), option, depth+1); newIPs != nil {
  261. return newIPs
  262. }
  263. }
  264. return ips
  265. }
  266. func toNetIP(ips []net.Address) []net.IP {
  267. if len(ips) == 0 {
  268. return nil
  269. }
  270. netips := make([]net.IP, 0, len(ips))
  271. for _, ip := range ips {
  272. netips = append(netips, ip.IP())
  273. }
  274. return netips
  275. }
  276. func (s *Server) lookupIPInternal(domain string, option IPOption) ([]net.IP, error) {
  277. if domain == "" {
  278. return nil, newError("empty domain name")
  279. }
  280. // normalize the FQDN form query
  281. if domain[len(domain)-1] == '.' {
  282. domain = domain[:len(domain)-1]
  283. }
  284. // skip domain without any dot
  285. if strings.Index(domain, ".") == -1 {
  286. return nil, newError("invalid domain name")
  287. }
  288. ips := s.lookupStatic(domain, option, 0)
  289. if ips != nil && ips[0].Family().IsIP() {
  290. newError("returning ", len(ips), " IPs for domain ", domain).WriteToLog()
  291. return toNetIP(ips), nil
  292. }
  293. if ips != nil && ips[0].Family().IsDomain() {
  294. newdomain := ips[0].Domain()
  295. newError("domain replaced: ", domain, " -> ", newdomain).WriteToLog()
  296. domain = newdomain
  297. }
  298. var lastErr error
  299. var matchedClient Client
  300. if s.domainMatcher != nil {
  301. idx := s.domainMatcher.Match(domain)
  302. if idx > 0 {
  303. matchedClient = s.clients[s.domainIndexMap[idx]]
  304. newError("domain matched, direct lookup ip for domain ", domain, " at ", matchedClient.Name()).WriteToLog()
  305. ips, err := s.queryIPTimeout(s.domainIndexMap[idx], matchedClient, domain, option)
  306. if len(ips) > 0 {
  307. return ips, nil
  308. }
  309. if err == dns.ErrEmptyResponse {
  310. return nil, err
  311. }
  312. if err != nil {
  313. newError("failed to lookup ip for domain ", domain, " at server ", matchedClient.Name()).Base(err).WriteToLog()
  314. lastErr = err
  315. }
  316. }
  317. }
  318. for idx, client := range s.clients {
  319. if client == matchedClient {
  320. newError("domain ", domain, " at server ", client.Name(), " idx:", idx, " already lookup failed, just ignore").AtDebug().WriteToLog()
  321. continue
  322. }
  323. newError("try to lookup ip for domain ", domain, " at server ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
  324. ips, err := s.queryIPTimeout(uint32(idx), client, domain, option)
  325. if len(ips) > 0 {
  326. newError("lookup ip for domain ", domain, " success: ", ips, " at server ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
  327. return ips, nil
  328. }
  329. if err != nil {
  330. newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
  331. lastErr = err
  332. }
  333. if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch {
  334. return nil, err
  335. }
  336. }
  337. return nil, dns.ErrEmptyResponse.Base(lastErr)
  338. }
  339. func init() {
  340. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  341. return New(ctx, config.(*Config))
  342. }))
  343. }