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

365 lines
7.9 KiB
Go
Raw Normal View History

2018-06-26 09:04:47 -04:00
package dns
import (
"context"
2018-11-19 07:13:02 -05:00
"encoding/binary"
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"
2018-06-26 09:04:47 -04:00
"v2ray.com/core/common"
"v2ray.com/core/common/net"
2018-12-29 03:03:32 -05:00
"v2ray.com/core/common/protocol/dns"
2019-01-05 15:43:22 -05:00
udp_proto "v2ray.com/core/common/protocol/udp"
2018-11-02 10:01:33 -04:00
"v2ray.com/core/common/session"
2018-07-01 06:38:40 -04:00
"v2ray.com/core/common/signal/pubsub"
2018-06-26 09:04:47 -04:00
"v2ray.com/core/common/task"
2018-11-02 10:01:33 -04:00
"v2ray.com/core/features/routing"
2018-06-26 09:04:47 -04:00
"v2ray.com/core/transport/internet/udp"
)
type IPRecord struct {
2018-12-28 14:15:22 -05:00
IP net.Address
2018-06-26 09:04:47 -04:00
Expire time.Time
}
2018-07-01 11:15:29 -04:00
type pendingRequest struct {
domain string
expire time.Time
}
2018-06-26 09:04:47 -04:00
type ClassicNameServer struct {
sync.RWMutex
address net.Destination
ips map[string][]IPRecord
2018-07-01 11:15:29 -04:00
requests map[uint16]pendingRequest
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
2018-06-26 17:23:59 -04:00
clientIP net.IP
2018-06-26 09:04:47 -04:00
}
func NewClassicNameServer(address net.Destination, dispatcher routing.Dispatcher, clientIP net.IP) *ClassicNameServer {
2018-06-26 09:04:47 -04:00
s := &ClassicNameServer{
address: address,
ips: make(map[string][]IPRecord),
requests: make(map[uint16]pendingRequest),
clientIP: clientIP,
pub: pubsub.NewService(),
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)
2018-06-26 09:04:47 -04:00
return s
}
2018-11-22 10:29:09 -05:00
func (s *ClassicNameServer) Name() string {
return s.address.String()
}
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 {
return newError("nothing to do. stopping...")
}
2018-06-26 09:04:47 -04: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 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 {
s.requests = make(map[uint16]pendingRequest)
}
2018-06-26 09:04:47 -04:00
return nil
}
2019-01-05 15:43:22 -05:00
func (s *ClassicNameServer) HandleResponse(ctx context.Context, packet *udp_proto.Packet) {
payload := packet.Payload
2018-11-19 07:13:02 -05:00
var parser dnsmessage.Parser
header, err := parser.Start(payload.Bytes())
if err != nil {
2018-06-26 09:04:47 -04:00
newError("failed to parse DNS response").Base(err).AtWarning().WriteToLog()
return
}
2018-11-19 08:13:20 -05:00
if err := parser.SkipAllQuestions(); err != nil {
newError("failed to skip questions in DNS response").Base(err).AtWarning().WriteToLog()
return
}
2018-06-26 09:04:47 -04:00
2018-11-19 07:13:02 -05:00
id := header.ID
2018-07-01 11:15:29 -04: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 09:04:47 -04:00
ips := make([]IPRecord, 0, 16)
now := time.Now()
2018-11-19 07:13:02 -05:00
for {
header, err := parser.AnswerHeader()
if err != nil {
if err != dnsmessage.ErrSectionDone {
newError("failed to parse answer section for domain: ", domain).Base(err).WriteToLog()
}
2018-11-19 07:13:02 -05:00
break
2018-06-26 09:04:47 -04:00
}
2018-11-19 07:13:02 -05:00
ttl := header.TTL
2018-06-26 09:04:47 -04:00
if ttl == 0 {
2018-07-01 06:38:40 -04:00
ttl = 600
2018-06-26 09:04:47 -04:00
}
2018-11-19 07:13:02 -05:00
switch header.Type {
case dnsmessage.TypeA:
ans, err := parser.AResource()
if err != nil {
newError("failed to parse A record for domain: ", domain).Base(err).WriteToLog()
2018-11-19 07:13:02 -05:00
break
}
2018-06-26 09:04:47 -04:00
ips = append(ips, IPRecord{
2018-12-28 14:15:22 -05:00
IP: net.IPAddress(ans.A[:]),
2018-11-19 07:13:02 -05:00
Expire: now.Add(time.Duration(ttl) * time.Second),
2018-06-26 09:04:47 -04:00
})
2018-11-19 07:13:02 -05:00
case dnsmessage.TypeAAAA:
ans, err := parser.AAAAResource()
if err != nil {
newError("failed to parse A record for domain: ", domain).Base(err).WriteToLog()
2018-11-19 07:13:02 -05:00
break
}
ips = append(ips, IPRecord{
2018-12-28 14:15:22 -05:00
IP: net.IPAddress(ans.AAAA[:]),
2018-11-19 07:13:02 -05:00
Expire: now.Add(time.Duration(ttl) * time.Second),
})
default:
if err := parser.SkipAnswer(); err != nil {
newError("failed to skip answer").Base(err).WriteToLog()
}
2018-06-26 09:04:47 -04: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 06:38:40 -04:00
s.pub.Publish(domain, nil)
s.Unlock()
common.Must(s.cleanup.Start())
2018-06-26 09:04:47 -04:00
}
2018-11-19 07:13:02 -05:00
func (s *ClassicNameServer) getMsgOptions() *dnsmessage.Resource {
2018-06-26 17:23:59 -04:00
if len(s.clientIP) == 0 {
2018-06-26 11:14:51 -04:00
return nil
}
2018-11-19 07:13:02 -05:00
var netmask int
var family uint16
2018-06-26 11:14:51 -04:00
2018-06-26 17:23:59 -04:00
if len(s.clientIP) == 4 {
2018-11-19 07:13:02 -05:00
family = 1
netmask = 24 // 24 for IPV4, 96 for IPv6
2018-06-26 17:23:59 -04:00
} else {
2018-11-19 07:13:02 -05: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 11:14:51 -04:00
}
2018-11-19 07:13:02 -05:00
const EDNS0SUBNET = 0x08
opt := new(dnsmessage.Resource)
common.Must(opt.Header.SetEDNS0(1350, 0xfe00, true))
2018-06-26 11:14:51 -04:00
2018-11-19 07:13:02 -05:00
opt.Body = &dnsmessage.OPTResource{
Options: []dnsmessage.Option{
{
Code: EDNS0SUBNET,
Data: b,
},
},
}
return opt
2018-07-01 11:15:29 -04: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 11:14:51 -04:00
2018-07-01 11:15:29 -04:00
return id
2018-06-26 11:14:51 -04:00
}
func (s *ClassicNameServer) buildMsgs(domain string, option IPOption) []*dnsmessage.Message {
2018-11-19 07:13:02 -05:00
qA := dnsmessage.Question{
Name: dnsmessage.MustNewName(domain),
Type: dnsmessage.TypeA,
Class: dnsmessage.ClassINET,
2018-06-26 11:14:51 -04:00
}
2018-11-19 07:13:02 -05:00
qAAAA := dnsmessage.Question{
Name: dnsmessage.MustNewName(domain),
Type: dnsmessage.TypeAAAA,
Class: dnsmessage.ClassINET,
2018-06-26 11:14:51 -04:00
}
2018-11-19 07:13:02 -05:00
var msgs []*dnsmessage.Message
2018-06-26 09:04:47 -04:00
if option.IPv4Enable {
2018-11-19 07:13:02 -05:00
msg := new(dnsmessage.Message)
msg.Header.ID = s.addPendingRequest(domain)
msg.Header.RecursionDesired = true
msg.Questions = []dnsmessage.Question{qA}
2018-06-26 11:14:51 -04:00
if opt := s.getMsgOptions(); opt != nil {
2018-11-19 07:13:02 -05:00
msg.Additionals = append(msg.Additionals, *opt)
2018-06-26 09:04:47 -04:00
}
msgs = append(msgs, msg)
}
if option.IPv6Enable {
2018-11-19 07:13:02 -05:00
msg := new(dnsmessage.Message)
msg.Header.ID = s.addPendingRequest(domain)
msg.Header.RecursionDesired = true
msg.Questions = []dnsmessage.Question{qAAAA}
2018-06-26 11:14:51 -04:00
if opt := s.getMsgOptions(); opt != nil {
2018-11-19 07:13:02 -05:00
msg.Additionals = append(msg.Additionals, *opt)
2018-06-26 09:04:47 -04:00
}
msgs = append(msgs, msg)
}
return msgs
}
func (s *ClassicNameServer) sendQuery(ctx context.Context, domain string, option IPOption) {
2018-09-10 16:12:07 -04:00
newError("querying DNS for: ", domain).AtDebug().WriteToLog(session.ExportIDToError(ctx))
msgs := s.buildMsgs(domain, option)
2018-06-26 09:04:47 -04:00
for _, msg := range msgs {
2018-12-29 03:03:32 -05:00
b, err := dns.PackMessage(msg)
2018-06-26 09:04:47 -04:00
common.Must(err)
2019-01-16 14:32:41 -05:00
udpCtx := context.Background()
if inbound := session.InboundFromContext(ctx); inbound != nil {
udpCtx = session.ContextWithInbound(udpCtx, inbound)
}
s.udpServer.Dispatch(udpCtx, s.address, b)
2018-06-26 09:04:47 -04:00
}
}
func (s *ClassicNameServer) findIPsForDomain(domain string, option IPOption) []net.IP {
2018-06-27 03:12:55 -04:00
s.RLock()
2018-06-26 09:04:47 -04:00
records, found := s.ips[domain]
2018-06-27 03:12:55 -04:00
s.RUnlock()
2018-06-26 09:04:47 -04:00
if found && len(records) > 0 {
2018-12-28 14:15:22 -05:00
var ips []net.Address
2018-06-26 09:04:47 -04:00
now := time.Now()
for _, rec := range records {
if rec.Expire.After(now) {
ips = append(ips, rec.IP)
}
}
return toNetIP(filterIP(ips, option))
2018-06-26 09:04:47 -04:00
}
return nil
}
2018-11-19 07:13:02 -05:00
func Fqdn(domain string) string {
if len(domain) > 0 && domain[len(domain)-1] == '.' {
return domain
}
return domain + "."
}
func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string, option IPOption) ([]net.IP, error) {
2018-11-19 07:13:02 -05:00
fqdn := Fqdn(domain)
2018-06-26 09:04:47 -04:00
ips := s.findIPsForDomain(fqdn, option)
2018-06-26 09:04:47 -04:00
if len(ips) > 0 {
return ips, nil
}
2018-07-01 06:38:40 -04:00
sub := s.pub.Subscribe(fqdn)
defer sub.Close()
s.sendQuery(ctx, fqdn, option)
2018-06-26 09:04:47 -04:00
for {
ips := s.findIPsForDomain(fqdn, option)
2018-06-26 09:04:47 -04:00
if len(ips) > 0 {
return ips, nil
}
select {
case <-ctx.Done():
return nil, ctx.Err()
2018-07-01 06:38:40 -04:00
case <-sub.Wait():
2018-06-26 09:04:47 -04:00
}
}
}