1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-03 12:35:24 +00:00
v2fly/app/dns/udpns.go

356 lines
7.1 KiB
Go
Raw Normal View History

2018-06-26 13:04:47 +00:00
package dns
import (
"context"
2018-11-19 12:13:02 +00:00
"encoding/binary"
2018-06-26 13:04:47 +00:00
"sync"
"sync/atomic"
"time"
2018-11-19 12:13:02 +00:00
"golang.org/x/net/dns/dnsmessage"
2018-11-02 14:01:33 +00:00
2018-06-26 13:04:47 +00:00
"v2ray.com/core/common"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/net"
2018-11-02 14:01:33 +00:00
"v2ray.com/core/common/session"
2018-07-01 10:38:40 +00:00
"v2ray.com/core/common/signal/pubsub"
2018-06-26 13:04:47 +00:00
"v2ray.com/core/common/task"
2018-11-02 14:01:33 +00:00
"v2ray.com/core/features/routing"
2018-06-26 13:04:47 +00:00
"v2ray.com/core/transport/internet/udp"
)
type IPRecord struct {
IP net.IP
Expire time.Time
}
2018-07-01 15:15:29 +00:00
type pendingRequest struct {
domain string
expire time.Time
}
2018-06-26 13:04:47 +00:00
type ClassicNameServer struct {
sync.RWMutex
address net.Destination
ips map[string][]IPRecord
2018-07-01 15:15:29 +00:00
requests map[uint16]pendingRequest
2018-07-01 10:38:40 +00:00
pub *pubsub.Service
2018-06-26 13:04:47 +00:00
udpServer *udp.Dispatcher
cleanup *task.Periodic
reqID uint32
2018-06-26 21:23:59 +00:00
clientIP net.IP
2018-06-26 13:04:47 +00:00
}
func NewClassicNameServer(address net.Destination, dispatcher routing.Dispatcher, clientIP net.IP) *ClassicNameServer {
2018-06-26 13:04:47 +00:00
s := &ClassicNameServer{
address: address,
ips: make(map[string][]IPRecord),
requests: make(map[uint16]pendingRequest),
clientIP: clientIP,
pub: pubsub.NewService(),
2018-06-26 13:04:47 +00:00
}
s.cleanup = &task.Periodic{
Interval: time.Minute,
Execute: s.Cleanup,
}
s.udpServer = udp.NewDispatcher(dispatcher, s.HandleResponse)
2018-06-26 13:04:47 +00:00
return s
}
func (s *ClassicNameServer) Cleanup() error {
now := time.Now()
s.Lock()
defer s.Unlock()
if len(s.ips) == 0 && len(s.requests) == 0 {
return newError("nothing to do. stopping...")
}
2018-06-26 13:04:47 +00:00
for domain, ips := range s.ips {
newIPs := make([]IPRecord, 0, len(ips))
for _, ip := range ips {
if ip.Expire.After(now) {
newIPs = append(newIPs, ip)
}
}
if len(newIPs) == 0 {
delete(s.ips, domain)
} else if len(newIPs) < len(ips) {
s.ips[domain] = newIPs
}
}
if len(s.ips) == 0 {
s.ips = make(map[string][]IPRecord)
}
2018-07-01 15:15:29 +00:00
for id, req := range s.requests {
if req.expire.Before(now) {
delete(s.requests, id)
}
}
if len(s.requests) == 0 {
s.requests = make(map[uint16]pendingRequest)
}
2018-06-26 13:04:47 +00:00
return nil
}
func (s *ClassicNameServer) HandleResponse(ctx context.Context, payload *buf.Buffer) {
2018-11-19 12:13:02 +00:00
var parser dnsmessage.Parser
header, err := parser.Start(payload.Bytes())
if err != nil {
2018-06-26 13:04:47 +00:00
newError("failed to parse DNS response").Base(err).AtWarning().WriteToLog()
return
}
2018-11-19 12:13:02 +00:00
parser.SkipAllQuestions()
2018-06-26 13:04:47 +00:00
2018-11-19 12:13:02 +00:00
id := header.ID
2018-07-01 15:15:29 +00:00
s.Lock()
req, f := s.requests[id]
if f {
delete(s.requests, id)
}
s.Unlock()
if !f {
return
}
domain := req.domain
2018-06-26 13:04:47 +00:00
ips := make([]IPRecord, 0, 16)
now := time.Now()
2018-11-19 12:13:02 +00:00
for {
header, err := parser.AnswerHeader()
if err != nil {
break
2018-06-26 13:04:47 +00:00
}
2018-11-19 12:13:02 +00:00
ttl := header.TTL
2018-06-26 13:04:47 +00:00
if ttl == 0 {
2018-07-01 10:38:40 +00:00
ttl = 600
2018-06-26 13:04:47 +00:00
}
2018-11-19 12:13:02 +00:00
switch header.Type {
case dnsmessage.TypeA:
ans, err := parser.AResource()
if err != nil {
break
}
2018-06-26 13:04:47 +00:00
ips = append(ips, IPRecord{
2018-11-19 12:13:02 +00:00
IP: net.IP(ans.A[:]),
Expire: now.Add(time.Duration(ttl) * time.Second),
2018-06-26 13:04:47 +00:00
})
2018-11-19 12:13:02 +00:00
case dnsmessage.TypeAAAA:
ans, err := parser.AAAAResource()
if err != nil {
break
}
ips = append(ips, IPRecord{
IP: net.IP(ans.AAAA[:]),
Expire: now.Add(time.Duration(ttl) * time.Second),
})
default:
2018-06-26 13:04:47 +00:00
}
}
if len(domain) > 0 && len(ips) > 0 {
s.updateIP(domain, ips)
}
}
func (s *ClassicNameServer) updateIP(domain string, ips []IPRecord) {
s.Lock()
newError("updating IP records for domain:", domain).AtDebug().WriteToLog()
now := time.Now()
eips := s.ips[domain]
for _, ip := range eips {
if ip.Expire.After(now) {
ips = append(ips, ip)
}
}
s.ips[domain] = ips
2018-07-01 10:38:40 +00:00
s.pub.Publish(domain, nil)
s.Unlock()
common.Must(s.cleanup.Start())
2018-06-26 13:04:47 +00:00
}
2018-11-19 12:13:02 +00:00
func (s *ClassicNameServer) getMsgOptions() *dnsmessage.Resource {
2018-06-26 21:23:59 +00:00
if len(s.clientIP) == 0 {
2018-06-26 15:14:51 +00:00
return nil
}
2018-11-19 12:13:02 +00:00
var netmask int
var family uint16
2018-06-26 15:14:51 +00:00
2018-06-26 21:23:59 +00:00
if len(s.clientIP) == 4 {
2018-11-19 12:13:02 +00:00
family = 1
netmask = 24 // 24 for IPV4, 96 for IPv6
2018-06-26 21:23:59 +00:00
} else {
2018-11-19 12:13:02 +00:00
family = 2
netmask = 96
}
b := make([]byte, 4)
binary.BigEndian.PutUint16(b[0:], family)
b[2] = byte(netmask)
b[3] = 0
switch family {
case 1:
ip := s.clientIP.To4().Mask(net.CIDRMask(netmask, net.IPv4len*8))
needLength := (netmask + 8 - 1) / 8 // division rounding up
b = append(b, ip[:needLength]...)
case 2:
ip := s.clientIP.Mask(net.CIDRMask(netmask, net.IPv6len*8))
needLength := (netmask + 8 - 1) / 8 // division rounding up
b = append(b, ip[:needLength]...)
2018-06-26 15:14:51 +00:00
}
2018-11-19 12:13:02 +00:00
const EDNS0SUBNET = 0x08
opt := new(dnsmessage.Resource)
common.Must(opt.Header.SetEDNS0(1350, 0xfe00, true))
2018-06-26 15:14:51 +00:00
2018-11-19 12:13:02 +00:00
opt.Body = &dnsmessage.OPTResource{
Options: []dnsmessage.Option{
{
Code: EDNS0SUBNET,
Data: b,
},
},
}
return opt
2018-07-01 15:15:29 +00:00
}
func (s *ClassicNameServer) addPendingRequest(domain string) uint16 {
id := uint16(atomic.AddUint32(&s.reqID, 1))
s.Lock()
defer s.Unlock()
s.requests[id] = pendingRequest{
domain: domain,
expire: time.Now().Add(time.Second * 8),
}
2018-06-26 15:14:51 +00:00
2018-07-01 15:15:29 +00:00
return id
2018-06-26 15:14:51 +00:00
}
2018-11-19 12:13:02 +00:00
func (s *ClassicNameServer) buildMsgs(domain string) []*dnsmessage.Message {
qA := dnsmessage.Question{
Name: dnsmessage.MustNewName(domain),
Type: dnsmessage.TypeA,
Class: dnsmessage.ClassINET,
2018-06-26 15:14:51 +00:00
}
2018-11-19 12:13:02 +00:00
qAAAA := dnsmessage.Question{
Name: dnsmessage.MustNewName(domain),
Type: dnsmessage.TypeAAAA,
Class: dnsmessage.ClassINET,
2018-06-26 15:14:51 +00:00
}
2018-11-19 12:13:02 +00:00
var msgs []*dnsmessage.Message
2018-06-26 13:04:47 +00:00
{
2018-11-19 12:13:02 +00:00
msg := new(dnsmessage.Message)
msg.Header.ID = s.addPendingRequest(domain)
msg.Header.RecursionDesired = true
msg.Questions = []dnsmessage.Question{qA}
2018-06-26 15:14:51 +00:00
if opt := s.getMsgOptions(); opt != nil {
2018-11-19 12:13:02 +00:00
msg.Additionals = append(msg.Additionals, *opt)
2018-06-26 13:04:47 +00:00
}
msgs = append(msgs, msg)
}
2018-11-19 12:13:02 +00:00
{
msg := new(dnsmessage.Message)
msg.Header.ID = s.addPendingRequest(domain)
msg.Header.RecursionDesired = true
msg.Questions = []dnsmessage.Question{qAAAA}
2018-06-26 15:14:51 +00:00
if opt := s.getMsgOptions(); opt != nil {
2018-11-19 12:13:02 +00:00
msg.Additionals = append(msg.Additionals, *opt)
2018-06-26 13:04:47 +00:00
}
msgs = append(msgs, msg)
}
return msgs
}
2018-11-19 12:13:02 +00:00
func msgToBuffer(msg *dnsmessage.Message) (*buf.Buffer, error) {
2018-06-26 13:04:47 +00:00
buffer := buf.New()
2018-11-02 20:34:04 +00:00
rawBytes := buffer.Extend(buf.Size)
2018-11-19 12:13:02 +00:00
packed, err := msg.AppendPack(rawBytes[:0])
2018-11-02 20:34:04 +00:00
if err != nil {
2018-08-29 14:42:14 +00:00
buffer.Release()
2018-06-26 13:04:47 +00:00
return nil, err
}
2018-11-02 20:34:04 +00:00
buffer.Resize(0, int32(len(packed)))
2018-06-26 13:04:47 +00:00
return buffer, nil
}
func (s *ClassicNameServer) sendQuery(ctx context.Context, domain string) {
2018-09-10 20:12:07 +00:00
newError("querying DNS for: ", domain).AtDebug().WriteToLog(session.ExportIDToError(ctx))
2018-06-26 13:04:47 +00:00
msgs := s.buildMsgs(domain)
for _, msg := range msgs {
b, err := msgToBuffer(msg)
common.Must(err)
s.udpServer.Dispatch(context.Background(), s.address, b)
2018-06-26 13:04:47 +00:00
}
}
func (s *ClassicNameServer) findIPsForDomain(domain string) []net.IP {
2018-06-27 07:12:55 +00:00
s.RLock()
2018-06-26 13:04:47 +00:00
records, found := s.ips[domain]
2018-06-27 07:12:55 +00:00
s.RUnlock()
2018-06-26 13:04:47 +00:00
if found && len(records) > 0 {
var ips []net.IP
now := time.Now()
for _, rec := range records {
if rec.Expire.After(now) {
ips = append(ips, rec.IP)
}
}
return ips
}
return nil
}
2018-11-19 12:13:02 +00:00
func Fqdn(domain string) string {
if len(domain) > 0 && domain[len(domain)-1] == '.' {
return domain
}
return domain + "."
}
2018-06-26 13:04:47 +00:00
func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string) ([]net.IP, error) {
2018-11-19 12:13:02 +00:00
fqdn := Fqdn(domain)
2018-06-26 13:04:47 +00:00
ips := s.findIPsForDomain(fqdn)
if len(ips) > 0 {
return ips, nil
}
2018-07-01 10:38:40 +00:00
sub := s.pub.Subscribe(fqdn)
defer sub.Close()
2018-06-26 13:04:47 +00:00
s.sendQuery(ctx, fqdn)
for {
ips := s.findIPsForDomain(fqdn)
if len(ips) > 0 {
return ips, nil
}
select {
case <-ctx.Done():
return nil, ctx.Err()
2018-07-01 10:38:40 +00:00
case <-sub.Wait():
2018-06-26 13:04:47 +00:00
}
}
}