1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-17 18:06:15 -05:00
v2fly/app/dns/server.go

436 lines
12 KiB
Go
Raw Normal View History

2019-02-01 14:08:21 -05:00
// +build !confonly
2017-12-19 17:55:09 -05:00
package dns
2016-01-31 11:01:28 -05:00
2018-09-30 17:08:41 -04:00
//go:generate errorgen
2017-04-08 19:43:25 -04:00
2016-01-31 11:01:28 -05:00
import (
2017-01-13 07:41:40 -05:00
"context"
"fmt"
"log"
2019-12-05 23:55:14 -05:00
"net/url"
2019-06-29 11:43:30 -04:00
"strings"
2016-05-16 02:09:28 -04:00
"sync"
2016-01-31 11:01:28 -05:00
"time"
"v2ray.com/core"
2019-11-18 10:46:56 -05:00
"v2ray.com/core/app/router"
2017-01-06 09:32:36 -05:00
"v2ray.com/core/common"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/net"
2019-01-16 14:32:41 -05:00
"v2ray.com/core/common/session"
"v2ray.com/core/common/strmatcher"
2019-02-06 04:21:04 -05:00
"v2ray.com/core/common/uuid"
2018-10-13 09:15:49 -04:00
"v2ray.com/core/features"
2018-10-11 17:09:15 -04:00
"v2ray.com/core/features/dns"
2018-10-22 05:26:22 -04:00
"v2ray.com/core/features/routing"
2016-01-31 11:01:28 -05:00
)
2018-11-13 17:19:58 -05:00
// Server is a DNS rely server.
2017-12-28 17:19:41 -05:00
type Server struct {
2017-11-14 18:36:14 -05:00
sync.Mutex
hosts *StaticHosts
clientIP net.IP
clients []Client // clientIdx -> Client
ipIndexMap []*MultiGeoIPMatcher // clientIdx -> *MultiGeoIPMatcher
domainRules [][]string // clientIdx -> domainRuleIdx -> DomainRule
domainMatcher strmatcher.IndexMatcher
matcherInfos []DomainMatcherInfo // matcherIdx -> DomainMatcherInfo
tag string
}
// DomainMatcherInfo contains information attached to index returned by Server.domainMatcher
type DomainMatcherInfo struct {
clientIdx uint16
domainRuleIdx uint16
2016-01-31 11:01:28 -05:00
}
2019-11-18 10:46:56 -05:00
// MultiGeoIPMatcher for match
type MultiGeoIPMatcher struct {
matchers []*router.GeoIPMatcher
}
var errExpectedIPNonMatch = errors.New("expectIPs not match")
2019-11-20 04:20:33 -05:00
// Match check ip match
2019-11-18 10:46:56 -05:00
func (c *MultiGeoIPMatcher) Match(ip net.IP) bool {
for _, matcher := range c.matchers {
if matcher.Match(ip) {
return true
}
}
return false
}
2019-11-20 04:20:33 -05:00
// HasMatcher check has matcher
2019-11-18 10:46:56 -05:00
func (c *MultiGeoIPMatcher) HasMatcher() bool {
2019-11-22 04:57:16 -05:00
return len(c.matchers) > 0
2019-11-18 10:46:56 -05:00
}
2019-02-06 04:21:04 -05:00
func generateRandomTag() string {
id := uuid.New()
return "v2ray.system." + id.String()
}
2018-11-13 17:19:58 -05:00
// New creates a new DNS server with given configuration.
2017-12-28 17:19:41 -05:00
func New(ctx context.Context, config *Config) (*Server, error) {
server := &Server{
2018-12-28 14:28:31 -05:00
clients: make([]Client, 0, len(config.NameServers)+len(config.NameServer)),
2019-01-16 14:32:41 -05:00
tag: config.Tag,
2016-05-16 02:09:28 -04:00
}
if server.tag == "" {
2019-02-06 04:21:04 -05:00
server.tag = generateRandomTag()
}
2018-06-26 17:23:59 -04:00
if len(config.ClientIp) > 0 {
if len(config.ClientIp) != net.IPv4len && len(config.ClientIp) != net.IPv6len {
2018-06-26 17:23:59 -04:00
return nil, newError("unexpected IP length", len(config.ClientIp))
}
server.clientIP = net.IP(config.ClientIp)
2018-06-26 11:14:51 -04:00
}
hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts)
if err != nil {
return nil, newError("failed to create hosts").Base(err)
}
server.hosts = hosts
2020-08-09 04:51:06 -04:00
addNameServer := func(ns *NameServer) int {
endpoint := ns.Address
address := endpoint.Address.AsAddress()
if address.Family().IsDomain() && address.Domain() == "localhost" {
2018-12-28 14:28:31 -05:00
server.clients = append(server.clients, NewLocalNameServer())
2020-08-09 04:51:06 -04:00
if len(ns.PrioritizedDomain) == 0 { // Priotize local domain with .local domain or without any dot to local DNS
ns.PrioritizedDomain = []*NameServer_PriorityDomain{
{Type: DomainMatchingType_Regex, Domain: "^[^.]*$"}, // This will only match domain without any dot
{Type: DomainMatchingType_Subdomain, Domain: "local"},
{Type: DomainMatchingType_Subdomain, Domain: "localdomain"},
}
}
2019-12-05 23:55:14 -05:00
} else if address.Family().IsDomain() && strings.HasPrefix(address.Domain(), "https+local://") {
// URI schemed string treated as domain
2019-12-08 20:37:35 -05:00
// DOH Local mode
u, err := url.Parse(address.Domain())
2019-12-05 23:55:14 -05:00
if err != nil {
log.Fatalln(newError("DNS config error").Base(err))
}
2019-12-08 20:37:35 -05:00
server.clients = append(server.clients, NewDoHLocalNameServer(u, server.clientIP))
2020-08-31 05:53:16 -04:00
} else if address.Family().IsDomain() && strings.HasPrefix(address.Domain(), "https://") {
2019-12-08 20:37:35 -05:00
// DOH Remote mode
u, err := url.Parse(address.Domain())
2019-12-05 23:55:14 -05:00
if err != nil {
log.Fatalln(newError("DNS config error").Base(err))
}
2019-06-29 11:43:30 -04:00
idx := len(server.clients)
server.clients = append(server.clients, nil)
// need the core dispatcher, register DOHClient at callback
2019-06-29 11:43:30 -04:00
common.Must(core.RequireFeatures(ctx, func(d routing.Dispatcher) {
2019-12-08 20:37:35 -05:00
c, err := NewDoHNameServer(u, d, server.clientIP)
if err != nil {
log.Fatalln(newError("DNS config error").Base(err))
}
server.clients[idx] = c
2019-06-29 11:43:30 -04:00
}))
} else {
2019-12-08 20:37:35 -05:00
// UDP classic DNS mode
dest := endpoint.AsDestination()
if dest.Network == net.Network_Unknown {
dest.Network = net.Network_UDP
}
if dest.Network == net.Network_UDP {
2018-12-28 14:28:31 -05:00
idx := len(server.clients)
server.clients = append(server.clients, nil)
2018-10-22 05:26:22 -04:00
2018-11-13 17:19:58 -05:00
common.Must(core.RequireFeatures(ctx, func(d routing.Dispatcher) {
2018-12-28 14:28:31 -05:00
server.clients[idx] = NewClassicNameServer(dest, d, server.clientIP)
2018-11-13 17:19:58 -05:00
}))
2016-05-18 11:12:04 -04:00
}
}
server.ipIndexMap = append(server.ipIndexMap, nil)
2018-12-28 14:28:31 -05:00
return len(server.clients) - 1
}
2018-09-21 10:54:06 -04:00
if len(config.NameServers) > 0 {
2018-10-13 09:15:49 -04:00
features.PrintDeprecatedFeatureWarning("simple DNS server")
2019-11-22 04:37:03 -05:00
for _, destPB := range config.NameServers {
2020-08-09 04:51:06 -04:00
addNameServer(&NameServer{Address: destPB})
2019-11-22 04:37:03 -05:00
}
2018-09-21 10:54:06 -04:00
}
if len(config.NameServer) > 0 {
clientIndices := []int{}
domainRuleCount := 0
for _, ns := range config.NameServer {
2020-08-09 04:51:06 -04:00
idx := addNameServer(ns)
clientIndices = append(clientIndices, idx)
domainRuleCount += len(ns.PrioritizedDomain)
}
domainRules := make([][]string, len(server.clients))
domainMatcher := &strmatcher.MatcherGroup{}
matcherInfos := make([]DomainMatcherInfo, domainRuleCount+1) // matcher index starts from 1
var geoIPMatcherContainer router.GeoIPMatcherContainer
for nidx, ns := range config.NameServer {
idx := clientIndices[nidx]
// Establish domain rule matcher
rules := []string{}
ruleCurr := 0
ruleIter := 0
for _, domain := range ns.PrioritizedDomain {
matcher, err := toStrMatcher(domain.Type, domain.Domain)
if err != nil {
2018-10-29 07:24:17 -04:00
return nil, newError("failed to create prioritized domain").Base(err).AtWarning()
}
midx := domainMatcher.Add(matcher)
if midx >= uint32(len(matcherInfos)) { // This rarely happens according to current matcher's implementation
newError("expanding domain matcher info array to size ", midx, " when adding ", matcher).AtDebug().WriteToLog()
matcherInfos = append(matcherInfos, make([]DomainMatcherInfo, midx-uint32(len(matcherInfos))+1)...)
}
info := &matcherInfos[midx]
info.clientIdx = uint16(idx)
if ruleCurr < len(ns.OriginalRules) {
info.domainRuleIdx = uint16(ruleCurr)
rule := ns.OriginalRules[ruleCurr]
if ruleCurr >= len(rules) {
rules = append(rules, rule.Rule)
}
ruleIter++
if ruleIter >= int(rule.Size) {
ruleIter = 0
ruleCurr++
}
} else { // No original rule, generate one according to current domain matcher (majorly for compability with tests)
info.domainRuleIdx = uint16(len(rules))
rules = append(rules, matcher.String())
}
}
domainRules[idx] = rules
2019-11-18 10:46:56 -05:00
// only add to ipIndexMap if GeoIP is configured
if len(ns.Geoip) > 0 {
var matchers []*router.GeoIPMatcher
for _, geoip := range ns.Geoip {
matcher, err := geoIPMatcherContainer.Add(geoip)
if err != nil {
return nil, newError("failed to create ip matcher").Base(err).AtWarning()
}
matchers = append(matchers, matcher)
2019-11-18 10:46:56 -05:00
}
matcher := &MultiGeoIPMatcher{matchers: matchers}
server.ipIndexMap[idx] = matcher
2019-11-18 10:46:56 -05:00
}
}
server.domainRules = domainRules
server.domainMatcher = domainMatcher
server.matcherInfos = matcherInfos
}
2018-12-28 14:28:31 -05:00
if len(server.clients) == 0 {
server.clients = append(server.clients, NewLocalNameServer())
server.ipIndexMap = append(server.ipIndexMap, nil)
}
2017-01-13 07:41:40 -05:00
return server, nil
}
2018-10-22 05:26:22 -04:00
// Type implements common.HasType.
2018-10-12 17:57:56 -04:00
func (*Server) Type() interface{} {
return dns.ClientType()
}
2018-02-08 11:00:22 -05:00
// Start implements common.Runnable.
2017-12-28 17:19:41 -05:00
func (s *Server) Start() error {
2018-06-26 09:35:22 -04:00
return nil
2017-02-01 15:35:40 -05:00
}
2018-04-03 05:11:54 -04:00
// Close implements common.Closable.
2018-02-08 11:00:22 -05:00
func (s *Server) Close() error {
2018-06-26 09:35:22 -04:00
return nil
2017-12-28 17:19:41 -05:00
}
2017-02-01 15:35:40 -05:00
2019-02-06 04:21:04 -05:00
func (s *Server) IsOwnLink(ctx context.Context) bool {
inbound := session.InboundFromContext(ctx)
return inbound != nil && inbound.Tag == s.tag
}
2019-11-18 10:46:56 -05:00
// Match check dns ip match geoip
func (s *Server) Match(idx int, client Client, domain string, ips []net.IP) ([]net.IP, error) {
var matcher *MultiGeoIPMatcher
if idx < len(s.ipIndexMap) {
matcher = s.ipIndexMap[idx]
}
if matcher == nil {
2019-11-18 10:46:56 -05:00
return ips, nil
}
2019-11-22 04:37:03 -05:00
if !matcher.HasMatcher() {
newError("domain ", domain, " server has no valid matcher: ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
2019-11-18 10:46:56 -05:00
return ips, nil
}
newIps := []net.IP{}
for _, ip := range ips {
if matcher.Match(ip) {
newIps = append(newIps, ip)
}
}
if len(newIps) == 0 {
return nil, errExpectedIPNonMatch
2019-11-18 10:46:56 -05:00
}
newError("domain ", domain, " expectIPs ", newIps, " matched at server ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
2019-11-18 10:46:56 -05:00
return newIps, nil
}
func (s *Server) queryIPTimeout(idx int, client Client, domain string, option IPOption) ([]net.IP, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*4)
2019-01-16 14:32:41 -05:00
if len(s.tag) > 0 {
ctx = session.ContextWithInbound(ctx, &session.Inbound{
Tag: s.tag,
})
}
2018-12-28 14:28:31 -05:00
ips, err := client.QueryIP(ctx, domain, option)
cancel()
if err != nil {
return ips, err
}
ips, err = s.Match(idx, client, domain, ips)
return ips, err
}
2018-10-22 05:26:22 -04:00
// LookupIP implements dns.Client.
2017-12-28 17:19:41 -05:00
func (s *Server) LookupIP(domain string) ([]net.IP, error) {
return s.lookupIPInternal(domain, IPOption{
IPv4Enable: true,
IPv6Enable: true,
})
}
// LookupIPv4 implements dns.IPv4Lookup.
func (s *Server) LookupIPv4(domain string) ([]net.IP, error) {
return s.lookupIPInternal(domain, IPOption{
IPv4Enable: true,
IPv6Enable: false,
})
}
// LookupIPv6 implements dns.IPv6Lookup.
func (s *Server) LookupIPv6(domain string) ([]net.IP, error) {
return s.lookupIPInternal(domain, IPOption{
IPv4Enable: false,
IPv6Enable: true,
})
}
func (s *Server) lookupStatic(domain string, option IPOption, depth int32) []net.Address {
ips := s.hosts.LookupIP(domain, option)
if ips == nil {
return nil
}
if ips[0].Family().IsDomain() && depth < 5 {
if newIPs := s.lookupStatic(ips[0].Domain(), option, depth+1); newIPs != nil {
return newIPs
}
}
return ips
}
func toNetIP(ips []net.Address) []net.IP {
if len(ips) == 0 {
return nil
}
netips := make([]net.IP, 0, len(ips))
for _, ip := range ips {
netips = append(netips, ip.IP())
}
return netips
}
func (s *Server) lookupIPInternal(domain string, option IPOption) ([]net.IP, error) {
if domain == "" {
2019-02-06 15:02:03 -05:00
return nil, newError("empty domain name")
}
2019-06-29 11:43:30 -04:00
// normalize the FQDN form query
2019-02-06 15:02:03 -05:00
if domain[len(domain)-1] == '.' {
domain = domain[:len(domain)-1]
}
ips := s.lookupStatic(domain, option, 0)
if ips != nil && ips[0].Family().IsIP() {
2019-02-12 15:04:28 -05:00
newError("returning ", len(ips), " IPs for domain ", domain).WriteToLog()
return toNetIP(ips), nil
}
if ips != nil && ips[0].Family().IsDomain() {
newdomain := ips[0].Domain()
newError("domain replaced: ", domain, " -> ", newdomain).WriteToLog()
domain = newdomain
2016-05-22 16:30:08 -04:00
}
2018-06-26 09:04:47 -04:00
var lastErr error
2019-11-20 13:32:09 -05:00
var matchedClient Client
if s.domainMatcher != nil {
indices := s.domainMatcher.Match(domain)
domainRules := []string{}
matchingDNS := []string{}
for _, idx := range indices {
info := s.matcherInfos[idx]
rule := s.domainRules[info.clientIdx][info.domainRuleIdx]
domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", rule, info.clientIdx))
matchingDNS = append(matchingDNS, s.clients[info.clientIdx].Name())
}
2020-08-22 07:07:14 -04:00
if len(domainRules) > 0 {
newError("domain ", domain, " matches following rules: ", domainRules).AtDebug().WriteToLog()
}
if len(matchingDNS) > 0 {
newError("domain ", domain, " uses following DNS first: ", matchingDNS).AtDebug().WriteToLog()
}
for _, idx := range indices {
clientIdx := int(s.matcherInfos[idx].clientIdx)
matchedClient = s.clients[clientIdx]
ips, err := s.queryIPTimeout(clientIdx, matchedClient, domain, option)
if len(ips) > 0 {
return ips, nil
}
if err == dns.ErrEmptyResponse {
return nil, err
}
if err != nil {
2019-11-20 13:32:09 -05:00
newError("failed to lookup ip for domain ", domain, " at server ", matchedClient.Name()).Base(err).WriteToLog()
lastErr = err
}
2018-06-26 09:04:47 -04:00
}
}
2019-11-18 10:46:56 -05:00
for idx, client := range s.clients {
2019-11-20 13:32:09 -05:00
if client == matchedClient {
newError("domain ", domain, " at server ", client.Name(), " idx:", idx, " already lookup failed, just ignore").AtDebug().WriteToLog()
continue
}
2019-11-18 10:46:56 -05:00
ips, err := s.queryIPTimeout(idx, client, domain, option)
2018-06-26 09:04:47 -04:00
if len(ips) > 0 {
return ips, nil
2016-05-16 02:09:28 -04:00
}
2019-11-18 10:46:56 -05:00
if err != nil {
2018-12-28 14:28:31 -05:00
newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
lastErr = err
}
if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch {
2019-02-21 09:17:04 -05:00
return nil, err
}
2016-01-31 11:01:28 -05:00
}
2016-05-16 02:09:28 -04:00
2019-12-31 21:23:14 -05:00
return nil, newError("returning nil for domain ", domain).Base(lastErr)
2016-01-31 11:01:28 -05:00
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return New(ctx, config.(*Config))
}))
}