server.go 10 KB

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