1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-02 09:17:55 -04:00
v2fly/app/dns/nameserver_udp.go

299 lines
6.8 KiB
Go
Raw Normal View History

2019-02-01 14:08:21 -05:00
// +build !confonly
2018-06-26 09:04:47 -04:00
package dns
import (
"context"
2019-06-29 11:43:30 -04:00
"strings"
2018-06-26 09:04:47 -04:00
"sync"
"sync/atomic"
"time"
2018-11-19 07:13:02 -05:00
"golang.org/x/net/dns/dnsmessage"
2021-02-16 15:31:50 -05:00
"github.com/v2fly/v2ray-core/v4/common"
"github.com/v2fly/v2ray-core/v4/common/net"
"github.com/v2fly/v2ray-core/v4/common/protocol/dns"
udp_proto "github.com/v2fly/v2ray-core/v4/common/protocol/udp"
"github.com/v2fly/v2ray-core/v4/common/session"
"github.com/v2fly/v2ray-core/v4/common/signal/pubsub"
"github.com/v2fly/v2ray-core/v4/common/task"
dns_feature "github.com/v2fly/v2ray-core/v4/features/dns"
"github.com/v2fly/v2ray-core/v4/features/routing"
"github.com/v2fly/v2ray-core/v4/transport/internet/udp"
2018-06-26 09:04:47 -04:00
)
// ClassicNameServer implemented traditional UDP DNS.
2018-06-26 09:04:47 -04:00
type ClassicNameServer struct {
sync.RWMutex
2019-06-29 11:43:30 -04:00
name string
2018-06-26 09:04:47 -04:00
address net.Destination
ips map[string]record
2019-06-29 11:43:30 -04:00
requests map[uint16]dnsRequest
2018-07-01 06:38:40 -04:00
pub *pubsub.Service
2018-06-26 09:04:47 -04:00
udpServer *udp.Dispatcher
cleanup *task.Periodic
reqID uint32
}
// NewClassicNameServer creates udp server object for remote resolving.
func NewClassicNameServer(address net.Destination, dispatcher routing.Dispatcher) *ClassicNameServer {
// default to 53 if unspecific
if address.Port == 0 {
address.Port = net.Port(53)
}
2018-06-26 09:04:47 -04:00
s := &ClassicNameServer{
address: address,
ips: make(map[string]record),
2019-06-29 11:43:30 -04:00
requests: make(map[uint16]dnsRequest),
pub: pubsub.NewService(),
2019-06-29 11:43:30 -04:00
name: strings.ToUpper(address.String()),
2018-06-26 09:04:47 -04:00
}
s.cleanup = &task.Periodic{
Interval: time.Minute,
Execute: s.Cleanup,
}
s.udpServer = udp.NewDispatcher(dispatcher, s.HandleResponse)
newError("DNS: created UDP client initialized for ", address.NetAddr()).AtInfo().WriteToLog()
2018-06-26 09:04:47 -04:00
return s
}
// Name implements Server.
2018-11-22 10:29:09 -05:00
func (s *ClassicNameServer) Name() string {
2019-06-29 11:43:30 -04:00
return s.name
2018-11-22 10:29:09 -05:00
}
// Cleanup clears expired items from cache
2018-06-26 09:04:47 -04:00
func (s *ClassicNameServer) Cleanup() error {
now := time.Now()
s.Lock()
defer s.Unlock()
if len(s.ips) == 0 && len(s.requests) == 0 {
2019-06-29 11:43:30 -04:00
return newError(s.name, " nothing to do. stopping...")
}
for domain, record := range s.ips {
if record.A != nil && record.A.Expire.Before(now) {
record.A = nil
2018-06-26 09:04:47 -04:00
}
if record.AAAA != nil && record.AAAA.Expire.Before(now) {
record.AAAA = nil
}
if record.A == nil && record.AAAA == nil {
2018-06-26 09:04:47 -04:00
delete(s.ips, domain)
} else {
s.ips[domain] = record
2018-06-26 09:04:47 -04:00
}
}
if len(s.ips) == 0 {
s.ips = make(map[string]record)
2018-06-26 09:04:47 -04:00
}
2018-07-01 11:15:29 -04:00
for id, req := range s.requests {
if req.expire.Before(now) {
delete(s.requests, id)
}
}
if len(s.requests) == 0 {
2019-06-29 11:43:30 -04:00
s.requests = make(map[uint16]dnsRequest)
2018-07-01 11:15:29 -04:00
}
2018-06-26 09:04:47 -04:00
return nil
}
// HandleResponse handles udp response packet from remote DNS server.
2019-01-05 15:43:22 -05:00
func (s *ClassicNameServer) HandleResponse(ctx context.Context, packet *udp_proto.Packet) {
2019-06-29 11:43:30 -04:00
ipRec, err := parseResponse(packet.Payload.Bytes())
2018-11-19 07:13:02 -05:00
if err != nil {
2020-06-24 00:57:03 -04:00
newError(s.name, " fail to parse responded DNS udp").AtError().WriteToLog()
2018-11-19 08:13:20 -05:00
return
}
2018-06-26 09:04:47 -04:00
2018-07-01 11:15:29 -04:00
s.Lock()
2019-06-29 11:43:30 -04:00
id := ipRec.ReqID
req, ok := s.requests[id]
if ok {
// remove the pending request
2018-07-01 11:15:29 -04:00
delete(s.requests, id)
}
s.Unlock()
2019-06-29 11:43:30 -04:00
if !ok {
newError(s.name, " cannot find the pending request").AtError().WriteToLog()
2018-07-01 11:15:29 -04:00
return
}
var rec record
2019-06-29 11:43:30 -04:00
switch req.reqType {
case dnsmessage.TypeA:
2019-06-29 11:43:30 -04:00
rec.A = ipRec
case dnsmessage.TypeAAAA:
2019-06-29 11:43:30 -04:00
rec.AAAA = ipRec
}
2019-06-29 11:43:30 -04:00
elapsed := time.Since(req.start)
2020-08-09 04:51:06 -04:00
newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog()
2019-06-29 11:43:30 -04:00
if len(req.domain) > 0 && (rec.A != nil || rec.AAAA != nil) {
s.updateIP(req.domain, rec)
}
2018-06-26 09:04:47 -04:00
}
func (s *ClassicNameServer) updateIP(domain string, newRec record) {
2018-06-26 09:04:47 -04:00
s.Lock()
2019-06-29 11:43:30 -04:00
newError(s.name, " updating IP records for domain:", domain).AtDebug().WriteToLog()
rec := s.ips[domain]
updated := false
if isNewer(rec.A, newRec.A) {
rec.A = newRec.A
updated = true
}
if isNewer(rec.AAAA, newRec.AAAA) {
rec.AAAA = newRec.AAAA
updated = true
}
if updated {
s.ips[domain] = rec
2018-06-26 09:04:47 -04:00
}
if newRec.A != nil {
s.pub.Publish(domain+"4", nil)
}
if newRec.AAAA != nil {
s.pub.Publish(domain+"6", nil)
}
s.Unlock()
common.Must(s.cleanup.Start())
2018-06-26 09:04:47 -04:00
}
2019-06-29 11:43:30 -04:00
func (s *ClassicNameServer) newReqID() uint16 {
return uint16(atomic.AddUint32(&s.reqID, 1))
2018-07-01 11:15:29 -04:00
}
2019-06-29 11:43:30 -04:00
func (s *ClassicNameServer) addPendingRequest(req *dnsRequest) {
2018-07-01 11:15:29 -04:00
s.Lock()
defer s.Unlock()
2019-06-29 11:43:30 -04:00
id := req.msg.ID
req.expire = time.Now().Add(time.Second * 8)
s.requests[id] = *req
2018-06-26 09:04:47 -04:00
}
func (s *ClassicNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) {
2019-06-29 11:43:30 -04:00
newError(s.name, " querying DNS for: ", domain).AtDebug().WriteToLog(session.ExportIDToError(ctx))
2018-06-26 09:04:47 -04:00
reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP))
2019-06-29 11:43:30 -04:00
for _, req := range reqs {
s.addPendingRequest(req)
b, _ := dns.PackMessage(req.msg)
2019-01-16 14:32:41 -05:00
udpCtx := context.Background()
if inbound := session.InboundFromContext(ctx); inbound != nil {
udpCtx = session.ContextWithInbound(udpCtx, inbound)
}
2019-02-22 10:58:16 -05:00
udpCtx = session.ContextWithContent(udpCtx, &session.Content{
Protocol: "dns",
})
2019-01-16 14:32:41 -05:00
s.udpServer.Dispatch(udpCtx, s.address, b)
2018-06-26 09:04:47 -04:00
}
}
func (s *ClassicNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) {
2018-06-27 03:12:55 -04:00
s.RLock()
record, found := s.ips[domain]
2018-06-27 03:12:55 -04:00
s.RUnlock()
if !found {
return nil, errRecordNotFound
}
var ips []net.Address
var lastErr error
if option.IPv4Enable {
a, err := record.A.getIPs()
if err != nil {
lastErr = err
2018-06-26 09:04:47 -04:00
}
ips = append(ips, a...)
2018-06-26 09:04:47 -04:00
}
if option.IPv6Enable {
aaaa, err := record.AAAA.getIPs()
if err != nil {
lastErr = err
}
ips = append(ips, aaaa...)
}
if len(ips) > 0 {
return toNetIP(ips)
}
if lastErr != nil {
return nil, lastErr
}
return nil, dns_feature.ErrEmptyResponse
2018-06-26 09:04:47 -04:00
}
// QueryIP implements Server.
func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) {
2018-11-19 07:13:02 -05:00
fqdn := Fqdn(domain)
2018-06-26 09:04:47 -04:00
if disableCache {
newError("DNS cache is disabled. Querying IP for ", domain, " at ", s.name).AtDebug().WriteToLog()
} else {
ips, err := s.findIPsForDomain(fqdn, option)
if err != errRecordNotFound {
newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog()
return ips, err
}
2018-06-26 09:04:47 -04:00
}
// ipv4 and ipv6 belong to different subscription groups
var sub4, sub6 *pubsub.Subscriber
if option.IPv4Enable {
sub4 = s.pub.Subscribe(fqdn + "4")
defer sub4.Close()
}
if option.IPv6Enable {
sub6 = s.pub.Subscribe(fqdn + "6")
defer sub6.Close()
}
done := make(chan interface{})
go func() {
if sub4 != nil {
select {
case <-sub4.Wait():
case <-ctx.Done():
}
}
if sub6 != nil {
select {
case <-sub6.Wait():
case <-ctx.Done():
}
}
close(done)
}()
s.sendQuery(ctx, fqdn, clientIP, option)
2018-06-26 09:04:47 -04:00
for {
ips, err := s.findIPsForDomain(fqdn, option)
if err != errRecordNotFound {
return ips, err
2018-06-26 09:04:47 -04:00
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-done:
2018-06-26 09:04:47 -04:00
}
}
}