1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 18:17:52 -05:00
v2fly/app/dns/nameserver_doh.go

386 lines
9.5 KiB
Go
Raw Normal View History

2019-06-29 11:43:30 -04:00
// +build !confonly
package dns
import (
"bytes"
"context"
"fmt"
2020-03-02 21:00:52 -05:00
"io"
2019-06-29 11:43:30 -04:00
"io/ioutil"
"net/http"
2019-12-08 20:37:35 -05:00
"net/url"
2019-06-29 11:43:30 -04:00
"sync"
"sync/atomic"
"time"
2020-03-02 21:00:52 -05:00
2019-06-29 11:43:30 -04: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"
"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"
2019-06-29 11:43:30 -04:00
)
2020-06-25 02:10:24 -04:00
// DoHNameServer implemented DNS over HTTPS (RFC8484) Wire Format,
// which is compatible with traditional dns over udp(RFC1035),
// thus most of the DOH implementation is copied from udpns.go
2019-06-29 11:43:30 -04:00
type DoHNameServer struct {
sync.RWMutex
ips map[string]record
pub *pubsub.Service
cleanup *task.Periodic
reqID uint32
httpClient *http.Client
dohURL string
name string
}
// NewDoHNameServer creates DOH server object for remote resolving.
func NewDoHNameServer(url *url.URL, dispatcher routing.Dispatcher) (*DoHNameServer, error) {
2020-03-02 05:07:43 -05:00
newError("DNS: created Remote DOH client for ", url.String()).AtInfo().WriteToLog()
s := baseDOHNameServer(url, "DOH")
2019-06-29 11:43:30 -04:00
2020-06-25 02:10:24 -04:00
// Dispatched connection will be closed (interrupted) after each request
// This makes DOH inefficient without a keep-alived connection
2019-06-29 11:43:30 -04:00
// See: core/app/proxyman/outbound/handler.go:113
// Using mux (https request wrapped in a stream layer) improves the situation.
2020-06-25 02:10:24 -04:00
// Recommend to use NewDoHLocalNameServer (DOHL:) if v2ray instance is running on
2019-06-29 11:43:30 -04:00
// a normal network eg. the server side of v2ray
tr := &http.Transport{
2020-03-02 05:07:43 -05:00
MaxIdleConns: 30,
2019-06-29 11:43:30 -04:00
IdleConnTimeout: 90 * time.Second,
2020-03-02 05:07:43 -05:00
TLSHandshakeTimeout: 30 * time.Second,
2020-07-31 01:11:42 -04:00
ForceAttemptHTTP2: true,
2020-03-02 05:07:43 -05:00
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
2020-03-02 21:00:52 -05:00
dest, err := net.ParseDestination(network + ":" + addr)
2020-03-02 05:07:43 -05:00
if err != nil {
return nil, err
}
link, err := dispatcher.Dispatch(ctx, dest)
if err != nil {
return nil, err
}
return net.NewConnection(
net.ConnectionInputMulti(link.Writer),
net.ConnectionOutputMulti(link.Reader),
), nil
},
2019-06-29 11:43:30 -04:00
}
dispatchedClient := &http.Client{
Transport: tr,
2020-03-02 05:07:43 -05:00
Timeout: 60 * time.Second,
2019-06-29 11:43:30 -04:00
}
s.httpClient = dispatchedClient
return s, nil
}
2019-11-26 00:24:46 -05:00
// NewDoHLocalNameServer creates DOH client object for local resolving
func NewDoHLocalNameServer(url *url.URL) *DoHNameServer {
2019-12-08 20:37:35 -05:00
url.Scheme = "https"
s := baseDOHNameServer(url, "DOHL")
2020-03-02 05:07:43 -05:00
tr := &http.Transport{
2020-07-31 01:11:42 -04:00
IdleConnTimeout: 90 * time.Second,
ForceAttemptHTTP2: true,
2020-03-02 05:07:43 -05:00
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
2020-03-02 21:00:52 -05:00
dest, err := net.ParseDestination(network + ":" + addr)
2020-03-02 05:07:43 -05:00
if err != nil {
return nil, err
}
conn, err := internet.DialSystem(ctx, dest, nil)
if err != nil {
return nil, err
}
return conn, nil
},
}
s.httpClient = &http.Client{
2020-03-02 05:07:43 -05:00
Timeout: time.Second * 180,
Transport: tr,
}
2019-12-08 20:37:35 -05:00
newError("DNS: created Local DOH client for ", url.String()).AtInfo().WriteToLog()
2019-06-29 11:43:30 -04:00
return s
}
func baseDOHNameServer(url *url.URL, prefix string) *DoHNameServer {
2019-06-29 11:43:30 -04:00
s := &DoHNameServer{
ips: make(map[string]record),
pub: pubsub.NewService(),
name: prefix + "//" + url.Host,
dohURL: url.String(),
2019-06-29 11:43:30 -04:00
}
s.cleanup = &task.Periodic{
Interval: time.Minute,
Execute: s.Cleanup,
}
return s
}
// Name implements Server.
2019-06-29 11:43:30 -04:00
func (s *DoHNameServer) Name() string {
return s.name
}
2019-11-26 00:24:46 -05:00
// Cleanup clears expired items from cache
2019-06-29 11:43:30 -04:00
func (s *DoHNameServer) Cleanup() error {
now := time.Now()
s.Lock()
defer s.Unlock()
if len(s.ips) == 0 {
return newError("nothing to do. stopping...")
}
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 {
newError(s.name, " cleanup ", domain).AtDebug().WriteToLog()
delete(s.ips, domain)
} else {
s.ips[domain] = record
}
}
if len(s.ips) == 0 {
s.ips = make(map[string]record)
}
return nil
}
func (s *DoHNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) {
elapsed := time.Since(req.start)
s.Lock()
rec := s.ips[req.domain]
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
2019-06-29 11:43:30 -04:00
if isNewer(rec.AAAA, ipRec) {
rec.AAAA = ipRec
updated = true
}
}
2020-06-25 02:10:24 -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 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)
}
2019-06-29 11:43:30 -04:00
s.Unlock()
common.Must(s.cleanup.Start())
}
func (s *DoHNameServer) newReqID() uint16 {
return uint16(atomic.AddUint32(&s.reqID, 1))
}
func (s *DoHNameServer) 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: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx))
reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP))
2019-06-29 11:43:30 -04:00
var deadline time.Time
if d, ok := ctx.Deadline(); ok {
deadline = d
} else {
deadline = time.Now().Add(time.Second * 5)
2019-06-29 11:43:30 -04:00
}
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
2019-06-29 11:43:30 -04:00
// reserve internal dns server requested Inbound
if inbound := session.InboundFromContext(ctx); inbound != nil {
dnsCtx = session.ContextWithInbound(dnsCtx, inbound)
}
dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{
2020-12-30 05:35:19 -05:00
Protocol: "https",
SkipDNSResolve: true,
2019-06-29 11:43:30 -04:00
})
// forced to use mux for DOH
dnsCtx = session.ContextWithMuxPrefered(dnsCtx, true)
var cancel context.CancelFunc
dnsCtx, cancel = context.WithDeadline(dnsCtx, deadline)
2019-06-29 11:43:30 -04:00
defer cancel()
b, err := dns.PackMessage(r.msg)
if err != nil {
newError("failed to pack dns query").Base(err).AtError().WriteToLog()
return
}
2019-06-29 11:43:30 -04:00
resp, err := s.dohHTTPSContext(dnsCtx, b.Bytes())
if err != nil {
2020-06-24 00:57:03 -04:00
newError("failed to retrieve response").Base(err).AtError().WriteToLog()
2019-06-29 11:43:30 -04:00
return
}
rec, err := parseResponse(resp)
if err != nil {
newError("failed to handle DOH response").Base(err).AtError().WriteToLog()
return
}
s.updateIP(r, rec)
}(req)
}
}
func (s *DoHNameServer) dohHTTPSContext(ctx context.Context, b []byte) ([]byte, error) {
body := bytes.NewBuffer(b)
req, err := http.NewRequest("POST", s.dohURL, body)
if err != nil {
return nil, err
}
req.Header.Add("Accept", "application/dns-message")
req.Header.Add("Content-Type", "application/dns-message")
resp, err := s.httpClient.Do(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
2020-03-02 21:00:52 -05:00
io.Copy(ioutil.Discard, resp.Body) // flush resp.Body so that the conn is reusable
return nil, fmt.Errorf("DOH server returned code %d", resp.StatusCode)
2019-06-29 11:43:30 -04:00
}
return ioutil.ReadAll(resp.Body)
}
func (s *DoHNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) {
2019-06-29 11:43:30 -04:00
s.RLock()
record, found := s.ips[domain]
s.RUnlock()
if !found {
return nil, errRecordNotFound
}
var ips []net.Address
var lastErr error
if option.IPv6Enable && record.AAAA != nil && record.AAAA.RCode == dnsmessage.RCodeSuccess {
aaaa, err := record.AAAA.getIPs()
if err != nil {
lastErr = err
}
ips = append(ips, aaaa...)
}
if option.IPv4Enable && record.A != nil && record.A.RCode == dnsmessage.RCodeSuccess {
a, err := record.A.getIPs()
if err != nil {
lastErr = err
}
ips = append(ips, a...)
}
if len(ips) > 0 {
return toNetIP(ips)
2019-06-29 11:43:30 -04:00
}
if lastErr != nil {
return nil, lastErr
}
if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) {
return nil, dns_feature.ErrEmptyResponse
}
2019-06-29 11:43:30 -04:00
return nil, errRecordNotFound
}
// QueryIP implements Server.
func (s *DoHNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) { // nolint: dupl
2019-06-29 11:43:30 -04:00
fqdn := Fqdn(domain)
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
}
2019-06-29 11:43:30 -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)
2019-06-29 11:43:30 -04:00
for {
ips, err := s.findIPsForDomain(fqdn, option)
if err != errRecordNotFound {
return ips, err
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-done:
2019-06-29 11:43:30 -04:00
}
}
}