2022-08-03 10:55:39 +00:00
|
|
|
package route
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-02-03 09:45:27 +00:00
|
|
|
"errors"
|
2022-08-03 10:55:39 +00:00
|
|
|
"net/netip"
|
|
|
|
"strings"
|
2023-03-23 11:08:48 +00:00
|
|
|
"time"
|
2022-08-03 10:55:39 +00:00
|
|
|
|
2022-08-16 15:46:05 +00:00
|
|
|
"github.com/sagernet/sing-box/adapter"
|
2022-08-03 10:55:39 +00:00
|
|
|
"github.com/sagernet/sing-dns"
|
2023-03-23 11:08:48 +00:00
|
|
|
"github.com/sagernet/sing/common/cache"
|
2022-08-03 10:55:39 +00:00
|
|
|
E "github.com/sagernet/sing/common/exceptions"
|
|
|
|
F "github.com/sagernet/sing/common/format"
|
2023-03-23 11:08:48 +00:00
|
|
|
M "github.com/sagernet/sing/common/metadata"
|
2022-08-03 10:55:39 +00:00
|
|
|
|
2022-09-13 08:18:39 +00:00
|
|
|
mDNS "github.com/miekg/dns"
|
2022-08-03 10:55:39 +00:00
|
|
|
)
|
|
|
|
|
2023-03-23 11:08:48 +00:00
|
|
|
type DNSReverseMapping struct {
|
|
|
|
cache *cache.LruCache[netip.Addr, string]
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewDNSReverseMapping() *DNSReverseMapping {
|
|
|
|
return &DNSReverseMapping{
|
|
|
|
cache: cache.New[netip.Addr, string](),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *DNSReverseMapping) Save(address netip.Addr, domain string, ttl int) {
|
|
|
|
m.cache.StoreWithExpire(address, domain, time.Now().Add(time.Duration(ttl)*time.Second))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *DNSReverseMapping) Query(address netip.Addr) (string, bool) {
|
|
|
|
domain, loaded := m.cache.Load(address)
|
|
|
|
return domain, loaded
|
|
|
|
}
|
|
|
|
|
2024-06-22 17:04:22 +00:00
|
|
|
func (r *Router) matchDNS(ctx context.Context, allowFakeIP bool, index int, isAddressQuery bool) (context.Context, dns.Transport, dns.DomainStrategy, adapter.DNSRule, int) {
|
2022-08-22 04:01:50 +00:00
|
|
|
metadata := adapter.ContextFrom(ctx)
|
|
|
|
if metadata == nil {
|
|
|
|
panic("no context")
|
|
|
|
}
|
2024-02-03 09:45:27 +00:00
|
|
|
if index < len(r.dnsRules) {
|
|
|
|
dnsRules := r.dnsRules
|
|
|
|
if index != -1 {
|
|
|
|
dnsRules = dnsRules[index+1:]
|
|
|
|
}
|
2024-03-19 04:04:16 +00:00
|
|
|
for currentRuleIndex, rule := range dnsRules {
|
2024-06-22 17:04:22 +00:00
|
|
|
if rule.WithAddressLimit() && !isAddressQuery {
|
|
|
|
continue
|
|
|
|
}
|
2024-02-03 09:45:27 +00:00
|
|
|
metadata.ResetRuleCache()
|
|
|
|
if rule.Match(metadata) {
|
|
|
|
detour := rule.Outbound()
|
|
|
|
transport, loaded := r.transportMap[detour]
|
|
|
|
if !loaded {
|
|
|
|
r.dnsLogger.ErrorContext(ctx, "transport not found: ", detour)
|
|
|
|
continue
|
|
|
|
}
|
2024-02-04 18:42:15 +00:00
|
|
|
_, isFakeIP := transport.(adapter.FakeIPTransport)
|
|
|
|
if isFakeIP && !allowFakeIP {
|
2024-02-03 09:45:27 +00:00
|
|
|
continue
|
|
|
|
}
|
2024-03-19 04:04:16 +00:00
|
|
|
ruleIndex := currentRuleIndex
|
2024-02-03 09:45:27 +00:00
|
|
|
if index != -1 {
|
2024-03-19 04:04:16 +00:00
|
|
|
ruleIndex += index + 1
|
2024-02-03 09:45:27 +00:00
|
|
|
}
|
2024-03-19 04:04:16 +00:00
|
|
|
r.dnsLogger.DebugContext(ctx, "match[", ruleIndex, "] ", rule.String(), " => ", detour)
|
2024-04-28 10:43:27 +00:00
|
|
|
if isFakeIP || rule.DisableCache() {
|
2024-02-03 09:45:27 +00:00
|
|
|
ctx = dns.ContextWithDisableCache(ctx, true)
|
|
|
|
}
|
|
|
|
if rewriteTTL := rule.RewriteTTL(); rewriteTTL != nil {
|
|
|
|
ctx = dns.ContextWithRewriteTTL(ctx, *rewriteTTL)
|
|
|
|
}
|
2024-02-09 10:37:25 +00:00
|
|
|
if clientSubnet := rule.ClientSubnet(); clientSubnet != nil {
|
|
|
|
ctx = dns.ContextWithClientSubnet(ctx, *clientSubnet)
|
|
|
|
}
|
2024-02-03 09:45:27 +00:00
|
|
|
if domainStrategy, dsLoaded := r.transportDomainStrategy[transport]; dsLoaded {
|
|
|
|
return ctx, transport, domainStrategy, rule, ruleIndex
|
|
|
|
} else {
|
|
|
|
return ctx, transport, r.defaultDomainStrategy, rule, ruleIndex
|
|
|
|
}
|
2022-08-22 04:01:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-11-19 14:39:30 +00:00
|
|
|
if domainStrategy, dsLoaded := r.transportDomainStrategy[r.defaultTransport]; dsLoaded {
|
2024-02-03 09:45:27 +00:00
|
|
|
return ctx, r.defaultTransport, domainStrategy, nil, -1
|
2022-11-19 14:39:30 +00:00
|
|
|
} else {
|
2024-02-03 09:45:27 +00:00
|
|
|
return ctx, r.defaultTransport, r.defaultDomainStrategy, nil, -1
|
2022-11-19 14:39:30 +00:00
|
|
|
}
|
2022-08-22 04:01:50 +00:00
|
|
|
}
|
|
|
|
|
2022-09-13 08:18:39 +00:00
|
|
|
func (r *Router) Exchange(ctx context.Context, message *mDNS.Msg) (*mDNS.Msg, error) {
|
|
|
|
if len(message.Question) > 0 {
|
|
|
|
r.dnsLogger.DebugContext(ctx, "exchange ", formatQuestion(message.Question[0].String()))
|
2022-08-03 10:55:39 +00:00
|
|
|
}
|
2023-04-25 20:53:25 +00:00
|
|
|
var (
|
2024-02-04 18:42:15 +00:00
|
|
|
response *mDNS.Msg
|
|
|
|
cached bool
|
|
|
|
transport dns.Transport
|
|
|
|
err error
|
2023-04-25 20:53:25 +00:00
|
|
|
)
|
|
|
|
response, cached = r.dnsClient.ExchangeCache(ctx, message)
|
|
|
|
if !cached {
|
2024-02-03 09:45:27 +00:00
|
|
|
var metadata *adapter.InboundContext
|
2024-06-24 01:41:00 +00:00
|
|
|
ctx, metadata = adapter.ExtendContext(ctx)
|
|
|
|
metadata.Destination = M.Socksaddr{}
|
2023-04-25 20:53:25 +00:00
|
|
|
if len(message.Question) > 0 {
|
|
|
|
metadata.QueryType = message.Question[0].Qtype
|
|
|
|
switch metadata.QueryType {
|
|
|
|
case mDNS.TypeA:
|
|
|
|
metadata.IPVersion = 4
|
|
|
|
case mDNS.TypeAAAA:
|
|
|
|
metadata.IPVersion = 6
|
|
|
|
}
|
|
|
|
metadata.Domain = fqdnToDomain(message.Question[0].Name)
|
|
|
|
}
|
2024-02-03 09:45:27 +00:00
|
|
|
var (
|
|
|
|
strategy dns.DomainStrategy
|
|
|
|
rule adapter.DNSRule
|
|
|
|
ruleIndex int
|
|
|
|
)
|
|
|
|
ruleIndex = -1
|
|
|
|
for {
|
|
|
|
var (
|
|
|
|
dnsCtx context.Context
|
|
|
|
addressLimit bool
|
|
|
|
)
|
2024-06-22 17:04:22 +00:00
|
|
|
dnsCtx, transport, strategy, rule, ruleIndex = r.matchDNS(ctx, true, ruleIndex, isAddressQuery(message))
|
2024-06-24 01:41:00 +00:00
|
|
|
dnsCtx = adapter.OverrideContext(dnsCtx)
|
2024-06-22 17:04:22 +00:00
|
|
|
if rule != nil && rule.WithAddressLimit() {
|
2024-02-03 09:45:27 +00:00
|
|
|
addressLimit = true
|
|
|
|
response, err = r.dnsClient.ExchangeWithResponseCheck(dnsCtx, transport, message, strategy, func(response *mDNS.Msg) bool {
|
2024-06-24 01:41:00 +00:00
|
|
|
addresses, addrErr := dns.MessageToAddresses(response)
|
|
|
|
if addrErr != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
metadata.DestinationAddresses = addresses
|
2024-02-03 09:45:27 +00:00
|
|
|
return rule.MatchAddressLimit(metadata)
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
addressLimit = false
|
|
|
|
response, err = r.dnsClient.Exchange(dnsCtx, transport, message, strategy)
|
|
|
|
}
|
2024-03-15 09:21:52 +00:00
|
|
|
var rejected bool
|
2024-02-03 09:45:27 +00:00
|
|
|
if err != nil {
|
2024-02-14 12:42:58 +00:00
|
|
|
if errors.Is(err, dns.ErrResponseRejectedCached) {
|
2024-03-15 09:21:52 +00:00
|
|
|
rejected = true
|
2024-02-14 12:42:58 +00:00
|
|
|
r.dnsLogger.DebugContext(ctx, E.Cause(err, "response rejected for ", formatQuestion(message.Question[0].String())), " (cached)")
|
|
|
|
} else if errors.Is(err, dns.ErrResponseRejected) {
|
2024-03-15 09:21:52 +00:00
|
|
|
rejected = true
|
2024-02-03 09:45:27 +00:00
|
|
|
r.dnsLogger.DebugContext(ctx, E.Cause(err, "response rejected for ", formatQuestion(message.Question[0].String())))
|
|
|
|
} else if len(message.Question) > 0 {
|
|
|
|
r.dnsLogger.ErrorContext(ctx, E.Cause(err, "exchange failed for ", formatQuestion(message.Question[0].String())))
|
|
|
|
} else {
|
|
|
|
r.dnsLogger.ErrorContext(ctx, E.Cause(err, "exchange failed for <empty query>"))
|
|
|
|
}
|
|
|
|
}
|
2024-03-15 09:21:52 +00:00
|
|
|
if addressLimit && rejected {
|
|
|
|
continue
|
2024-02-03 09:45:27 +00:00
|
|
|
}
|
2024-03-15 09:21:52 +00:00
|
|
|
break
|
2022-08-16 15:46:05 +00:00
|
|
|
}
|
2022-08-03 10:55:39 +00:00
|
|
|
}
|
2024-02-04 18:42:15 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-03-23 11:08:48 +00:00
|
|
|
if r.dnsReverseMapping != nil && len(message.Question) > 0 && response != nil && len(response.Answer) > 0 {
|
2024-02-04 18:42:15 +00:00
|
|
|
if _, isFakeIP := transport.(adapter.FakeIPTransport); !isFakeIP {
|
|
|
|
for _, answer := range response.Answer {
|
|
|
|
switch record := answer.(type) {
|
|
|
|
case *mDNS.A:
|
|
|
|
r.dnsReverseMapping.Save(M.AddrFromIP(record.A), fqdnToDomain(record.Hdr.Name), int(record.Hdr.Ttl))
|
|
|
|
case *mDNS.AAAA:
|
|
|
|
r.dnsReverseMapping.Save(M.AddrFromIP(record.AAAA), fqdnToDomain(record.Hdr.Name), int(record.Hdr.Ttl))
|
|
|
|
}
|
2023-03-23 11:08:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-02-04 18:42:15 +00:00
|
|
|
return response, nil
|
2022-08-03 10:55:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Router) Lookup(ctx context.Context, domain string, strategy dns.DomainStrategy) ([]netip.Addr, error) {
|
2024-02-14 12:42:58 +00:00
|
|
|
var (
|
|
|
|
responseAddrs []netip.Addr
|
|
|
|
cached bool
|
|
|
|
err error
|
|
|
|
)
|
|
|
|
responseAddrs, cached = r.dnsClient.LookupCache(ctx, domain, strategy)
|
|
|
|
if cached {
|
|
|
|
return responseAddrs, nil
|
|
|
|
}
|
2022-08-03 13:51:34 +00:00
|
|
|
r.dnsLogger.DebugContext(ctx, "lookup domain ", domain)
|
2024-06-24 01:41:00 +00:00
|
|
|
ctx, metadata := adapter.ExtendContext(ctx)
|
|
|
|
metadata.Destination = M.Socksaddr{}
|
2022-09-04 04:39:43 +00:00
|
|
|
metadata.Domain = domain
|
2024-02-03 09:45:27 +00:00
|
|
|
var (
|
|
|
|
transport dns.Transport
|
|
|
|
transportStrategy dns.DomainStrategy
|
|
|
|
rule adapter.DNSRule
|
|
|
|
ruleIndex int
|
|
|
|
)
|
|
|
|
ruleIndex = -1
|
|
|
|
for {
|
|
|
|
var (
|
|
|
|
dnsCtx context.Context
|
|
|
|
addressLimit bool
|
|
|
|
)
|
2024-06-22 17:04:22 +00:00
|
|
|
dnsCtx, transport, transportStrategy, rule, ruleIndex = r.matchDNS(ctx, false, ruleIndex, true)
|
2024-06-24 01:41:00 +00:00
|
|
|
dnsCtx = adapter.OverrideContext(dnsCtx)
|
2024-02-03 09:45:27 +00:00
|
|
|
if strategy == dns.DomainStrategyAsIS {
|
|
|
|
strategy = transportStrategy
|
|
|
|
}
|
|
|
|
if rule != nil && rule.WithAddressLimit() {
|
|
|
|
addressLimit = true
|
2024-02-14 12:42:58 +00:00
|
|
|
responseAddrs, err = r.dnsClient.LookupWithResponseCheck(dnsCtx, transport, domain, strategy, func(responseAddrs []netip.Addr) bool {
|
2024-02-03 09:45:27 +00:00
|
|
|
metadata.DestinationAddresses = responseAddrs
|
|
|
|
return rule.MatchAddressLimit(metadata)
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
addressLimit = false
|
2024-02-14 12:42:58 +00:00
|
|
|
responseAddrs, err = r.dnsClient.Lookup(dnsCtx, transport, domain, strategy)
|
2024-02-03 09:45:27 +00:00
|
|
|
}
|
|
|
|
if err != nil {
|
2024-02-14 12:42:58 +00:00
|
|
|
if errors.Is(err, dns.ErrResponseRejectedCached) {
|
|
|
|
r.dnsLogger.DebugContext(ctx, "response rejected for ", domain, " (cached)")
|
|
|
|
} else if errors.Is(err, dns.ErrResponseRejected) {
|
2024-02-03 09:45:27 +00:00
|
|
|
r.dnsLogger.DebugContext(ctx, "response rejected for ", domain)
|
|
|
|
} else {
|
|
|
|
r.dnsLogger.ErrorContext(ctx, E.Cause(err, "lookup failed for ", domain))
|
|
|
|
}
|
2024-02-14 12:42:58 +00:00
|
|
|
} else if len(responseAddrs) == 0 {
|
2024-02-03 09:45:27 +00:00
|
|
|
r.dnsLogger.ErrorContext(ctx, "lookup failed for ", domain, ": empty result")
|
|
|
|
err = dns.RCodeNameError
|
|
|
|
}
|
|
|
|
if !addressLimit || err == nil {
|
|
|
|
break
|
|
|
|
}
|
2022-08-22 04:01:50 +00:00
|
|
|
}
|
2024-02-14 12:42:58 +00:00
|
|
|
if len(responseAddrs) > 0 {
|
|
|
|
r.dnsLogger.InfoContext(ctx, "lookup succeed for ", domain, ": ", strings.Join(F.MapToString(responseAddrs), " "))
|
2022-08-03 10:55:39 +00:00
|
|
|
}
|
2024-02-14 12:42:58 +00:00
|
|
|
return responseAddrs, err
|
2022-08-03 10:55:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Router) LookupDefault(ctx context.Context, domain string) ([]netip.Addr, error) {
|
2022-08-22 04:01:50 +00:00
|
|
|
return r.Lookup(ctx, domain, dns.DomainStrategyAsIS)
|
2022-08-03 10:55:39 +00:00
|
|
|
}
|
|
|
|
|
2023-08-24 13:52:38 +00:00
|
|
|
func (r *Router) ClearDNSCache() {
|
|
|
|
r.dnsClient.ClearCache()
|
|
|
|
if r.platformInterface != nil {
|
|
|
|
r.platformInterface.ClearDNSCache()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-03 09:45:27 +00:00
|
|
|
func isAddressQuery(message *mDNS.Msg) bool {
|
|
|
|
for _, question := range message.Question {
|
2024-06-22 17:04:22 +00:00
|
|
|
if question.Qtype == mDNS.TypeA || question.Qtype == mDNS.TypeAAAA || question.Qtype == mDNS.TypeHTTPS {
|
2024-02-03 09:45:27 +00:00
|
|
|
return true
|
|
|
|
}
|
2022-08-03 10:55:39 +00:00
|
|
|
}
|
2024-02-03 09:45:27 +00:00
|
|
|
return false
|
2022-08-03 10:55:39 +00:00
|
|
|
}
|
|
|
|
|
2022-09-13 08:18:39 +00:00
|
|
|
func fqdnToDomain(fqdn string) string {
|
|
|
|
if mDNS.IsFqdn(fqdn) {
|
|
|
|
return fqdn[:len(fqdn)-1]
|
2022-08-03 10:55:39 +00:00
|
|
|
}
|
2022-09-13 08:18:39 +00:00
|
|
|
return fqdn
|
2022-08-03 10:55:39 +00:00
|
|
|
}
|
|
|
|
|
2022-09-13 08:18:39 +00:00
|
|
|
func formatQuestion(string string) string {
|
|
|
|
if strings.HasPrefix(string, ";") {
|
|
|
|
string = string[1:]
|
|
|
|
}
|
|
|
|
string = strings.ReplaceAll(string, "\t", " ")
|
|
|
|
for strings.Contains(string, " ") {
|
|
|
|
string = strings.ReplaceAll(string, " ", " ")
|
2022-08-03 10:55:39 +00:00
|
|
|
}
|
2022-09-13 08:18:39 +00:00
|
|
|
return string
|
2022-08-03 10:55:39 +00:00
|
|
|
}
|