2021-10-16 13:02:51 +00:00
|
|
|
package dns
|
|
|
|
|
|
|
|
import (
|
2024-02-29 02:35:35 +00:00
|
|
|
"bytes"
|
2021-10-16 13:02:51 +00:00
|
|
|
"context"
|
2024-02-29 02:35:35 +00:00
|
|
|
"encoding/binary"
|
2021-10-16 13:02:51 +00:00
|
|
|
"net/url"
|
|
|
|
"sync"
|
|
|
|
"sync/atomic"
|
|
|
|
"time"
|
|
|
|
|
2024-12-20 07:19:41 +00:00
|
|
|
"github.com/xtls/quic-go"
|
2021-10-16 13:02:51 +00:00
|
|
|
"github.com/xtls/xray-core/common"
|
|
|
|
"github.com/xtls/xray-core/common/buf"
|
2024-06-29 18:32:57 +00:00
|
|
|
"github.com/xtls/xray-core/common/errors"
|
2022-07-25 03:44:16 +00:00
|
|
|
"github.com/xtls/xray-core/common/log"
|
2021-10-16 13:02:51 +00:00
|
|
|
"github.com/xtls/xray-core/common/net"
|
|
|
|
"github.com/xtls/xray-core/common/protocol/dns"
|
|
|
|
"github.com/xtls/xray-core/common/session"
|
|
|
|
"github.com/xtls/xray-core/common/signal/pubsub"
|
|
|
|
"github.com/xtls/xray-core/common/task"
|
|
|
|
dns_feature "github.com/xtls/xray-core/features/dns"
|
|
|
|
"github.com/xtls/xray-core/transport/internet/tls"
|
2022-05-18 07:29:01 +00:00
|
|
|
"golang.org/x/net/dns/dnsmessage"
|
|
|
|
"golang.org/x/net/http2"
|
2021-10-16 13:02:51 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// NextProtoDQ - During connection establishment, DNS/QUIC support is indicated
|
|
|
|
// by selecting the ALPN token "dq" in the crypto handshake.
|
2024-02-29 02:35:35 +00:00
|
|
|
const NextProtoDQ = "doq"
|
2021-10-16 13:02:51 +00:00
|
|
|
|
|
|
|
const handshakeTimeout = time.Second * 8
|
|
|
|
|
|
|
|
// QUICNameServer implemented DNS over QUIC
|
|
|
|
type QUICNameServer struct {
|
|
|
|
sync.RWMutex
|
2023-09-19 21:03:19 +00:00
|
|
|
ips map[string]*record
|
|
|
|
pub *pubsub.Service
|
|
|
|
cleanup *task.Periodic
|
|
|
|
reqID uint32
|
|
|
|
name string
|
|
|
|
destination *net.Destination
|
|
|
|
connection quic.Connection
|
|
|
|
queryStrategy QueryStrategy
|
2021-10-16 13:02:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewQUICNameServer creates DNS-over-QUIC client object for local resolving
|
2023-09-19 21:03:19 +00:00
|
|
|
func NewQUICNameServer(url *url.URL, queryStrategy QueryStrategy) (*QUICNameServer, error) {
|
2024-06-29 18:32:57 +00:00
|
|
|
errors.LogInfo(context.Background(), "DNS: created Local DNS-over-QUIC client for ", url.String())
|
2021-10-16 13:02:51 +00:00
|
|
|
|
|
|
|
var err error
|
2022-06-16 09:28:48 +00:00
|
|
|
port := net.Port(853)
|
2021-10-16 13:02:51 +00:00
|
|
|
if url.Port() != "" {
|
|
|
|
port, err = net.PortFromString(url.Port())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
dest := net.UDPDestination(net.ParseAddress(url.Hostname()), port)
|
|
|
|
|
|
|
|
s := &QUICNameServer{
|
2023-09-19 21:03:19 +00:00
|
|
|
ips: make(map[string]*record),
|
|
|
|
pub: pubsub.NewService(),
|
|
|
|
name: url.String(),
|
|
|
|
destination: &dest,
|
|
|
|
queryStrategy: queryStrategy,
|
2021-10-16 13:02:51 +00:00
|
|
|
}
|
|
|
|
s.cleanup = &task.Periodic{
|
|
|
|
Interval: time.Minute,
|
|
|
|
Execute: s.Cleanup,
|
|
|
|
}
|
|
|
|
|
|
|
|
return s, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Name returns client name
|
|
|
|
func (s *QUICNameServer) Name() string {
|
|
|
|
return s.name
|
|
|
|
}
|
|
|
|
|
|
|
|
// Cleanup clears expired items from cache
|
|
|
|
func (s *QUICNameServer) Cleanup() error {
|
|
|
|
now := time.Now()
|
|
|
|
s.Lock()
|
|
|
|
defer s.Unlock()
|
|
|
|
|
|
|
|
if len(s.ips) == 0 {
|
2024-06-29 18:32:57 +00:00
|
|
|
return errors.New("nothing to do. stopping...")
|
2021-10-16 13:02:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for domain, record := range s.ips {
|
|
|
|
if record.A != nil && record.A.Expire.Before(now) {
|
|
|
|
record.A = nil
|
|
|
|
}
|
|
|
|
if record.AAAA != nil && record.AAAA.Expire.Before(now) {
|
|
|
|
record.AAAA = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if record.A == nil && record.AAAA == nil {
|
2024-06-29 18:32:57 +00:00
|
|
|
errors.LogDebug(context.Background(), s.name, " cleanup ", domain)
|
2021-10-16 13:02:51 +00:00
|
|
|
delete(s.ips, domain)
|
|
|
|
} else {
|
|
|
|
s.ips[domain] = record
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(s.ips) == 0 {
|
|
|
|
s.ips = make(map[string]*record)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *QUICNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) {
|
|
|
|
elapsed := time.Since(req.start)
|
|
|
|
|
|
|
|
s.Lock()
|
|
|
|
rec, found := s.ips[req.domain]
|
|
|
|
if !found {
|
|
|
|
rec = &record{}
|
|
|
|
}
|
|
|
|
updated := false
|
|
|
|
|
|
|
|
switch req.reqType {
|
|
|
|
case dnsmessage.TypeA:
|
|
|
|
if isNewer(rec.A, ipRec) {
|
|
|
|
rec.A = ipRec
|
|
|
|
updated = true
|
|
|
|
}
|
|
|
|
case dnsmessage.TypeAAAA:
|
|
|
|
addr := make([]net.Address, 0)
|
|
|
|
for _, ip := range ipRec.IP {
|
|
|
|
if len(ip.IP()) == net.IPv6len {
|
|
|
|
addr = append(addr, ip)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
ipRec.IP = addr
|
|
|
|
if isNewer(rec.AAAA, ipRec) {
|
|
|
|
rec.AAAA = ipRec
|
|
|
|
updated = true
|
|
|
|
}
|
|
|
|
}
|
2024-06-29 18:32:57 +00:00
|
|
|
errors.LogInfo(context.Background(), s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed)
|
2021-10-16 13:02:51 +00:00
|
|
|
|
|
|
|
if updated {
|
|
|
|
s.ips[req.domain] = rec
|
|
|
|
}
|
|
|
|
switch req.reqType {
|
|
|
|
case dnsmessage.TypeA:
|
|
|
|
s.pub.Publish(req.domain+"4", nil)
|
|
|
|
case dnsmessage.TypeAAAA:
|
|
|
|
s.pub.Publish(req.domain+"6", nil)
|
|
|
|
}
|
|
|
|
s.Unlock()
|
|
|
|
common.Must(s.cleanup.Start())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *QUICNameServer) newReqID() uint16 {
|
|
|
|
return uint16(atomic.AddUint32(&s.reqID, 1))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) {
|
2024-06-29 18:32:57 +00:00
|
|
|
errors.LogInfo(ctx, s.name, " querying: ", domain)
|
2021-10-16 13:02:51 +00:00
|
|
|
|
|
|
|
reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP))
|
|
|
|
|
|
|
|
var deadline time.Time
|
|
|
|
if d, ok := ctx.Deadline(); ok {
|
|
|
|
deadline = d
|
|
|
|
} else {
|
|
|
|
deadline = time.Now().Add(time.Second * 5)
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, req := range reqs {
|
|
|
|
go func(r *dnsRequest) {
|
|
|
|
// generate new context for each req, using same context
|
|
|
|
// may cause reqs all aborted if any one encounter an error
|
|
|
|
dnsCtx := ctx
|
|
|
|
|
|
|
|
// reserve internal dns server requested Inbound
|
|
|
|
if inbound := session.InboundFromContext(ctx); inbound != nil {
|
|
|
|
dnsCtx = session.ContextWithInbound(dnsCtx, inbound)
|
|
|
|
}
|
|
|
|
|
|
|
|
dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{
|
|
|
|
Protocol: "quic",
|
|
|
|
SkipDNSResolve: true,
|
|
|
|
})
|
|
|
|
|
|
|
|
var cancel context.CancelFunc
|
|
|
|
dnsCtx, cancel = context.WithDeadline(dnsCtx, deadline)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
b, err := dns.PackMessage(r.msg)
|
|
|
|
if err != nil {
|
2024-06-29 18:32:57 +00:00
|
|
|
errors.LogErrorInner(ctx, err, "failed to pack dns query")
|
2021-10-16 13:02:51 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-02-29 02:35:35 +00:00
|
|
|
dnsReqBuf := buf.New()
|
|
|
|
binary.Write(dnsReqBuf, binary.BigEndian, uint16(b.Len()))
|
|
|
|
dnsReqBuf.Write(b.Bytes())
|
|
|
|
b.Release()
|
|
|
|
|
2021-10-16 13:02:51 +00:00
|
|
|
conn, err := s.openStream(dnsCtx)
|
|
|
|
if err != nil {
|
2024-06-29 18:32:57 +00:00
|
|
|
errors.LogErrorInner(ctx, err, "failed to open quic connection")
|
2021-10-16 13:02:51 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-02-29 02:35:35 +00:00
|
|
|
_, err = conn.Write(dnsReqBuf.Bytes())
|
2021-10-16 13:02:51 +00:00
|
|
|
if err != nil {
|
2024-06-29 18:32:57 +00:00
|
|
|
errors.LogErrorInner(ctx, err, "failed to send query")
|
2021-10-16 13:02:51 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
_ = conn.Close()
|
|
|
|
|
|
|
|
respBuf := buf.New()
|
|
|
|
defer respBuf.Release()
|
2024-02-29 02:35:35 +00:00
|
|
|
n, err := respBuf.ReadFullFrom(conn, 2)
|
|
|
|
if err != nil && n == 0 {
|
2024-06-29 18:32:57 +00:00
|
|
|
errors.LogErrorInner(ctx, err, "failed to read response length")
|
2024-02-29 02:35:35 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
var length int16
|
|
|
|
err = binary.Read(bytes.NewReader(respBuf.Bytes()), binary.BigEndian, &length)
|
|
|
|
if err != nil {
|
2024-06-29 18:32:57 +00:00
|
|
|
errors.LogErrorInner(ctx, err, "failed to parse response length")
|
2024-02-29 02:35:35 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
respBuf.Clear()
|
|
|
|
n, err = respBuf.ReadFullFrom(conn, int32(length))
|
2021-10-16 13:02:51 +00:00
|
|
|
if err != nil && n == 0 {
|
2024-06-29 18:32:57 +00:00
|
|
|
errors.LogErrorInner(ctx, err, "failed to read response length")
|
2021-10-16 13:02:51 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
rec, err := parseResponse(respBuf.Bytes())
|
|
|
|
if err != nil {
|
2024-06-29 18:32:57 +00:00
|
|
|
errors.LogErrorInner(ctx, err, "failed to handle response")
|
2021-10-16 13:02:51 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
s.updateIP(r, rec)
|
|
|
|
}(req)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *QUICNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) {
|
|
|
|
s.RLock()
|
|
|
|
record, found := s.ips[domain]
|
|
|
|
s.RUnlock()
|
|
|
|
|
|
|
|
if !found {
|
|
|
|
return nil, errRecordNotFound
|
|
|
|
}
|
|
|
|
|
|
|
|
var err4 error
|
|
|
|
var err6 error
|
|
|
|
var ips []net.Address
|
|
|
|
var ip6 []net.Address
|
|
|
|
|
|
|
|
if option.IPv4Enable {
|
|
|
|
ips, err4 = record.A.getIPs()
|
|
|
|
}
|
|
|
|
|
|
|
|
if option.IPv6Enable {
|
|
|
|
ip6, err6 = record.AAAA.getIPs()
|
|
|
|
ips = append(ips, ip6...)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(ips) > 0 {
|
|
|
|
return toNetIP(ips)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err4 != nil {
|
|
|
|
return nil, err4
|
|
|
|
}
|
|
|
|
|
|
|
|
if err6 != nil {
|
|
|
|
return nil, err6
|
|
|
|
}
|
|
|
|
|
|
|
|
if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) {
|
|
|
|
return nil, dns_feature.ErrEmptyResponse
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, errRecordNotFound
|
|
|
|
}
|
|
|
|
|
|
|
|
// QueryIP is called from dns.Server->queryIPTimeout
|
|
|
|
func (s *QUICNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) {
|
|
|
|
fqdn := Fqdn(domain)
|
2023-09-19 21:03:19 +00:00
|
|
|
option = ResolveIpOptionOverride(s.queryStrategy, option)
|
|
|
|
if !option.IPv4Enable && !option.IPv6Enable {
|
|
|
|
return nil, dns_feature.ErrEmptyResponse
|
|
|
|
}
|
2021-10-16 13:02:51 +00:00
|
|
|
|
|
|
|
if disableCache {
|
2024-06-29 18:32:57 +00:00
|
|
|
errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.name)
|
2021-10-16 13:02:51 +00:00
|
|
|
} else {
|
|
|
|
ips, err := s.findIPsForDomain(fqdn, option)
|
2024-09-12 14:34:45 +00:00
|
|
|
if err == nil || err == dns_feature.ErrEmptyResponse {
|
2024-06-29 18:32:57 +00:00
|
|
|
errors.LogDebugInner(ctx, err, s.name, " cache HIT ", domain, " -> ", ips)
|
2022-07-25 03:44:16 +00:00
|
|
|
log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err})
|
2021-10-16 13:02:51 +00:00
|
|
|
return ips, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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)
|
2022-07-25 03:44:16 +00:00
|
|
|
start := time.Now()
|
2021-10-16 13:02:51 +00:00
|
|
|
|
|
|
|
for {
|
|
|
|
ips, err := s.findIPsForDomain(fqdn, option)
|
|
|
|
if err != errRecordNotFound {
|
2022-07-25 03:44:16 +00:00
|
|
|
log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSQueried, Elapsed: time.Since(start), Error: err})
|
2021-10-16 13:02:51 +00:00
|
|
|
return ips, err
|
|
|
|
}
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return nil, ctx.Err()
|
|
|
|
case <-done:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-09 04:48:02 +00:00
|
|
|
func isActive(s quic.Connection) bool {
|
2021-10-16 13:02:51 +00:00
|
|
|
select {
|
|
|
|
case <-s.Context().Done():
|
|
|
|
return false
|
|
|
|
default:
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-09 04:48:02 +00:00
|
|
|
func (s *QUICNameServer) getConnection() (quic.Connection, error) {
|
|
|
|
var conn quic.Connection
|
2021-10-16 13:02:51 +00:00
|
|
|
s.RLock()
|
2022-04-09 04:48:02 +00:00
|
|
|
conn = s.connection
|
|
|
|
if conn != nil && isActive(conn) {
|
2021-10-16 13:02:51 +00:00
|
|
|
s.RUnlock()
|
2022-04-09 04:48:02 +00:00
|
|
|
return conn, nil
|
2021-10-16 13:02:51 +00:00
|
|
|
}
|
2022-04-09 04:48:02 +00:00
|
|
|
if conn != nil {
|
|
|
|
// we're recreating the connection, let's create a new one
|
|
|
|
_ = conn.CloseWithError(0, "")
|
2021-10-16 13:02:51 +00:00
|
|
|
}
|
|
|
|
s.RUnlock()
|
|
|
|
|
|
|
|
s.Lock()
|
|
|
|
defer s.Unlock()
|
|
|
|
|
|
|
|
var err error
|
2022-04-09 04:48:02 +00:00
|
|
|
conn, err = s.openConnection()
|
2021-10-16 13:02:51 +00:00
|
|
|
if err != nil {
|
|
|
|
// This does not look too nice, but QUIC (or maybe quic-go)
|
|
|
|
// doesn't seem stable enough.
|
|
|
|
// Maybe retransmissions aren't fully implemented in quic-go?
|
|
|
|
// Anyways, the simple solution is to make a second try when
|
2022-04-09 04:48:02 +00:00
|
|
|
// it fails to open the QUIC connection.
|
|
|
|
conn, err = s.openConnection()
|
2021-10-16 13:02:51 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
2022-04-09 04:48:02 +00:00
|
|
|
s.connection = conn
|
|
|
|
return conn, nil
|
2021-10-16 13:02:51 +00:00
|
|
|
}
|
|
|
|
|
2022-04-09 04:48:02 +00:00
|
|
|
func (s *QUICNameServer) openConnection() (quic.Connection, error) {
|
2021-10-16 13:02:51 +00:00
|
|
|
tlsConfig := tls.Config{}
|
|
|
|
quicConfig := &quic.Config{
|
|
|
|
HandshakeIdleTimeout: handshakeTimeout,
|
|
|
|
}
|
2023-06-04 12:45:38 +00:00
|
|
|
tlsConfig.ServerName = s.destination.Address.String()
|
2023-06-02 00:59:07 +00:00
|
|
|
conn, err := quic.DialAddr(context.Background(), s.destination.NetAddr(), tlsConfig.GetTLSConfig(tls.WithNextProto("http/1.1", http2.NextProtoTLS, NextProtoDQ)), quicConfig)
|
2022-07-25 03:44:16 +00:00
|
|
|
log.Record(&log.AccessMessage{
|
|
|
|
From: "DNS",
|
|
|
|
To: s.destination,
|
|
|
|
Status: log.AccessAccepted,
|
|
|
|
Detour: "local",
|
|
|
|
})
|
2021-10-16 13:02:51 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-04-09 04:48:02 +00:00
|
|
|
return conn, nil
|
2021-10-16 13:02:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *QUICNameServer) openStream(ctx context.Context) (quic.Stream, error) {
|
2022-04-09 04:48:02 +00:00
|
|
|
conn, err := s.getConnection()
|
2021-10-16 13:02:51 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// open a new stream
|
2022-04-09 04:48:02 +00:00
|
|
|
return conn.OpenStreamSync(ctx)
|
2021-10-16 13:02:51 +00:00
|
|
|
}
|