2022-08-03 18:55:39 +08:00
|
|
|
package route
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-02-03 17:45:27 +08:00
|
|
|
"errors"
|
2022-08-03 18:55:39 +08:00
|
|
|
"net/netip"
|
|
|
|
"strings"
|
2023-03-23 19:08:48 +08:00
|
|
|
"time"
|
2022-08-03 18:55:39 +08:00
|
|
|
|
2022-08-16 23:46:05 +08:00
|
|
|
"github.com/sagernet/sing-box/adapter"
|
2024-11-06 17:30:40 +08:00
|
|
|
C "github.com/sagernet/sing-box/constant"
|
2024-10-21 23:38:34 +08:00
|
|
|
R "github.com/sagernet/sing-box/route/rule"
|
2022-08-03 18:55:39 +08:00
|
|
|
"github.com/sagernet/sing-dns"
|
2024-11-06 17:30:40 +08:00
|
|
|
tun "github.com/sagernet/sing-tun"
|
2023-03-23 19:08:48 +08:00
|
|
|
"github.com/sagernet/sing/common/cache"
|
2022-08-03 18:55:39 +08:00
|
|
|
E "github.com/sagernet/sing/common/exceptions"
|
|
|
|
F "github.com/sagernet/sing/common/format"
|
2023-03-23 19:08:48 +08:00
|
|
|
M "github.com/sagernet/sing/common/metadata"
|
2022-08-03 18:55:39 +08:00
|
|
|
|
2022-09-13 16:18:39 +08:00
|
|
|
mDNS "github.com/miekg/dns"
|
2022-08-03 18:55:39 +08:00
|
|
|
)
|
|
|
|
|
2023-03-23 19:08:48 +08: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-10-21 23:38:34 +08:00
|
|
|
func (r *Router) matchDNS(ctx context.Context, allowFakeIP bool, ruleIndex int, isAddressQuery bool) (dns.Transport, dns.QueryOptions, adapter.DNSRule, int) {
|
2022-08-22 12:01:50 +08:00
|
|
|
metadata := adapter.ContextFrom(ctx)
|
|
|
|
if metadata == nil {
|
|
|
|
panic("no context")
|
|
|
|
}
|
2024-10-21 23:38:34 +08:00
|
|
|
var options dns.QueryOptions
|
|
|
|
if ruleIndex < len(r.dnsRules) {
|
2024-02-03 17:45:27 +08:00
|
|
|
dnsRules := r.dnsRules
|
2024-10-21 23:38:34 +08:00
|
|
|
if ruleIndex != -1 {
|
|
|
|
dnsRules = dnsRules[ruleIndex+1:]
|
2024-02-03 17:45:27 +08:00
|
|
|
}
|
2024-11-06 17:30:40 +08:00
|
|
|
for currentRuleIndex, currentRule := range dnsRules {
|
|
|
|
if currentRule.WithAddressLimit() && !isAddressQuery {
|
2024-06-23 01:04:22 +08:00
|
|
|
continue
|
|
|
|
}
|
2024-02-03 17:45:27 +08:00
|
|
|
metadata.ResetRuleCache()
|
2024-11-06 17:30:40 +08:00
|
|
|
if currentRule.Match(metadata) {
|
2024-10-21 23:38:34 +08:00
|
|
|
displayRuleIndex := currentRuleIndex
|
|
|
|
if displayRuleIndex != -1 {
|
|
|
|
displayRuleIndex += displayRuleIndex + 1
|
2024-02-03 17:45:27 +08:00
|
|
|
}
|
2024-11-06 17:30:40 +08:00
|
|
|
ruleDescription := currentRule.String()
|
|
|
|
if ruleDescription != "" {
|
|
|
|
r.logger.DebugContext(ctx, "match[", displayRuleIndex, "] ", currentRule, " => ", currentRule.Action())
|
|
|
|
} else {
|
|
|
|
r.logger.DebugContext(ctx, "match[", displayRuleIndex, "] => ", currentRule.Action())
|
|
|
|
}
|
|
|
|
switch action := currentRule.Action().(type) {
|
|
|
|
case *R.RuleActionDNSRoute:
|
|
|
|
transport, loaded := r.transportMap[action.Server]
|
2024-10-21 23:38:34 +08:00
|
|
|
if !loaded {
|
2024-11-06 17:30:40 +08:00
|
|
|
r.dnsLogger.ErrorContext(ctx, "transport not found: ", action.Server)
|
2024-10-21 23:38:34 +08:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
_, isFakeIP := transport.(adapter.FakeIPTransport)
|
|
|
|
if isFakeIP && !allowFakeIP {
|
|
|
|
continue
|
|
|
|
}
|
2024-11-06 17:30:40 +08:00
|
|
|
if isFakeIP || action.DisableCache {
|
|
|
|
options.DisableCache = true
|
|
|
|
}
|
|
|
|
if action.RewriteTTL != nil {
|
|
|
|
options.RewriteTTL = action.RewriteTTL
|
|
|
|
}
|
|
|
|
if action.ClientSubnet.IsValid() {
|
|
|
|
options.ClientSubnet = action.ClientSubnet
|
|
|
|
}
|
2024-10-21 23:38:34 +08:00
|
|
|
if domainStrategy, dsLoaded := r.transportDomainStrategy[transport]; dsLoaded {
|
|
|
|
options.Strategy = domainStrategy
|
|
|
|
} else {
|
|
|
|
options.Strategy = r.defaultDomainStrategy
|
|
|
|
}
|
2024-11-06 17:30:40 +08:00
|
|
|
r.logger.DebugContext(ctx, "match[", displayRuleIndex, "] => ", currentRule.Action())
|
|
|
|
return transport, options, currentRule, currentRuleIndex
|
|
|
|
case *R.RuleActionDNSRouteOptions:
|
|
|
|
if action.DisableCache {
|
|
|
|
options.DisableCache = true
|
|
|
|
}
|
|
|
|
if action.RewriteTTL != nil {
|
|
|
|
options.RewriteTTL = action.RewriteTTL
|
|
|
|
}
|
|
|
|
if action.ClientSubnet.IsValid() {
|
|
|
|
options.ClientSubnet = action.ClientSubnet
|
|
|
|
}
|
|
|
|
r.logger.DebugContext(ctx, "match[", displayRuleIndex, "] => ", currentRule.Action())
|
|
|
|
case *R.RuleActionReject:
|
|
|
|
r.logger.DebugContext(ctx, "match[", displayRuleIndex, "] => ", currentRule.Action())
|
|
|
|
return nil, options, currentRule, currentRuleIndex
|
2024-02-03 17:45:27 +08:00
|
|
|
}
|
2022-08-22 12:01:50 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-11-19 22:39:30 +08:00
|
|
|
if domainStrategy, dsLoaded := r.transportDomainStrategy[r.defaultTransport]; dsLoaded {
|
2024-10-21 23:38:34 +08:00
|
|
|
options.Strategy = domainStrategy
|
2022-11-19 22:39:30 +08:00
|
|
|
} else {
|
2024-10-21 23:38:34 +08:00
|
|
|
options.Strategy = r.defaultDomainStrategy
|
2022-11-19 22:39:30 +08:00
|
|
|
}
|
2024-10-21 23:38:34 +08:00
|
|
|
return r.defaultTransport, options, nil, -1
|
2022-08-22 12:01:50 +08:00
|
|
|
}
|
|
|
|
|
2022-09-13 16:18:39 +08: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 18:55:39 +08:00
|
|
|
}
|
2023-04-26 04:53:25 +08:00
|
|
|
var (
|
2024-02-05 02:42:15 +08:00
|
|
|
response *mDNS.Msg
|
|
|
|
cached bool
|
|
|
|
transport dns.Transport
|
|
|
|
err error
|
2023-04-26 04:53:25 +08:00
|
|
|
)
|
|
|
|
response, cached = r.dnsClient.ExchangeCache(ctx, message)
|
|
|
|
if !cached {
|
2024-02-03 17:45:27 +08:00
|
|
|
var metadata *adapter.InboundContext
|
2024-06-24 09:41:00 +08:00
|
|
|
ctx, metadata = adapter.ExtendContext(ctx)
|
|
|
|
metadata.Destination = M.Socksaddr{}
|
2023-04-26 04:53:25 +08: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 17:45:27 +08:00
|
|
|
var (
|
2024-10-21 23:38:34 +08:00
|
|
|
options dns.QueryOptions
|
2024-02-03 17:45:27 +08:00
|
|
|
rule adapter.DNSRule
|
|
|
|
ruleIndex int
|
|
|
|
)
|
|
|
|
ruleIndex = -1
|
|
|
|
for {
|
2024-10-21 23:38:34 +08:00
|
|
|
dnsCtx := adapter.OverrideContext(ctx)
|
|
|
|
var addressLimit bool
|
|
|
|
transport, options, rule, ruleIndex = r.matchDNS(ctx, true, ruleIndex, isAddressQuery(message))
|
2024-11-06 17:30:40 +08:00
|
|
|
if rule != nil {
|
|
|
|
switch action := rule.Action().(type) {
|
|
|
|
case *R.RuleActionReject:
|
|
|
|
switch action.Method {
|
|
|
|
case C.RuleActionRejectMethodDefault:
|
|
|
|
return dns.FixedResponse(message.Id, message.Question[0], nil, 0), nil
|
|
|
|
case C.RuleActionRejectMethodDrop:
|
|
|
|
return nil, tun.ErrDrop
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-06-23 01:04:22 +08:00
|
|
|
if rule != nil && rule.WithAddressLimit() {
|
2024-02-03 17:45:27 +08:00
|
|
|
addressLimit = true
|
2024-10-21 23:38:34 +08:00
|
|
|
response, err = r.dnsClient.ExchangeWithResponseCheck(dnsCtx, transport, message, options, func(response *mDNS.Msg) bool {
|
2024-06-24 09:41:00 +08:00
|
|
|
addresses, addrErr := dns.MessageToAddresses(response)
|
|
|
|
if addrErr != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
metadata.DestinationAddresses = addresses
|
2024-02-03 17:45:27 +08:00
|
|
|
return rule.MatchAddressLimit(metadata)
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
addressLimit = false
|
2024-10-21 23:38:34 +08:00
|
|
|
response, err = r.dnsClient.Exchange(dnsCtx, transport, message, options)
|
2024-02-03 17:45:27 +08:00
|
|
|
}
|
2024-03-15 17:21:52 +08:00
|
|
|
var rejected bool
|
2024-02-03 17:45:27 +08:00
|
|
|
if err != nil {
|
2024-02-14 20:42:58 +08:00
|
|
|
if errors.Is(err, dns.ErrResponseRejectedCached) {
|
2024-03-15 17:21:52 +08:00
|
|
|
rejected = true
|
2024-02-14 20:42:58 +08: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 17:21:52 +08:00
|
|
|
rejected = true
|
2024-02-03 17:45:27 +08: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 17:21:52 +08:00
|
|
|
if addressLimit && rejected {
|
|
|
|
continue
|
2024-02-03 17:45:27 +08:00
|
|
|
}
|
2024-03-15 17:21:52 +08:00
|
|
|
break
|
2022-08-16 23:46:05 +08:00
|
|
|
}
|
2022-08-03 18:55:39 +08:00
|
|
|
}
|
2024-02-05 02:42:15 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-03-23 19:08:48 +08:00
|
|
|
if r.dnsReverseMapping != nil && len(message.Question) > 0 && response != nil && len(response.Answer) > 0 {
|
2024-02-05 02:42:15 +08: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 19:08:48 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-02-05 02:42:15 +08:00
|
|
|
return response, nil
|
2022-08-03 18:55:39 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Router) Lookup(ctx context.Context, domain string, strategy dns.DomainStrategy) ([]netip.Addr, error) {
|
2024-02-14 20:42:58 +08:00
|
|
|
var (
|
|
|
|
responseAddrs []netip.Addr
|
|
|
|
cached bool
|
|
|
|
err error
|
|
|
|
)
|
2024-10-22 22:01:28 +08:00
|
|
|
printResult := func() {
|
|
|
|
if err != nil {
|
|
|
|
if errors.Is(err, dns.ErrResponseRejectedCached) {
|
|
|
|
r.dnsLogger.DebugContext(ctx, "response rejected for ", domain, " (cached)")
|
|
|
|
} else if errors.Is(err, dns.ErrResponseRejected) {
|
|
|
|
r.dnsLogger.DebugContext(ctx, "response rejected for ", domain)
|
|
|
|
} else {
|
|
|
|
r.dnsLogger.ErrorContext(ctx, E.Cause(err, "lookup failed for ", domain))
|
|
|
|
}
|
|
|
|
} else if len(responseAddrs) == 0 {
|
|
|
|
r.dnsLogger.ErrorContext(ctx, "lookup failed for ", domain, ": empty result")
|
|
|
|
err = dns.RCodeNameError
|
|
|
|
}
|
|
|
|
}
|
2024-02-14 20:42:58 +08:00
|
|
|
responseAddrs, cached = r.dnsClient.LookupCache(ctx, domain, strategy)
|
|
|
|
if cached {
|
2024-08-20 23:17:02 +08:00
|
|
|
if len(responseAddrs) == 0 {
|
|
|
|
return nil, dns.RCodeNameError
|
|
|
|
}
|
2024-02-14 20:42:58 +08:00
|
|
|
return responseAddrs, nil
|
|
|
|
}
|
2022-08-03 21:51:34 +08:00
|
|
|
r.dnsLogger.DebugContext(ctx, "lookup domain ", domain)
|
2024-06-24 09:41:00 +08:00
|
|
|
ctx, metadata := adapter.ExtendContext(ctx)
|
|
|
|
metadata.Destination = M.Socksaddr{}
|
2022-09-04 12:39:43 +08:00
|
|
|
metadata.Domain = domain
|
2024-10-22 22:01:28 +08:00
|
|
|
if metadata.DNSServer != "" {
|
|
|
|
transport, loaded := r.transportMap[metadata.DNSServer]
|
|
|
|
if !loaded {
|
|
|
|
return nil, E.New("transport not found: ", metadata.DNSServer)
|
2024-02-03 17:45:27 +08:00
|
|
|
}
|
2024-10-22 22:01:28 +08:00
|
|
|
if strategy == dns.DomainStrategyAsIS {
|
|
|
|
if transportDomainStrategy, loaded := r.transportDomainStrategy[transport]; loaded {
|
|
|
|
strategy = transportDomainStrategy
|
2024-02-03 17:45:27 +08:00
|
|
|
} else {
|
2024-10-22 22:01:28 +08:00
|
|
|
strategy = r.defaultDomainStrategy
|
2024-02-03 17:45:27 +08:00
|
|
|
}
|
|
|
|
}
|
2024-10-22 22:01:28 +08:00
|
|
|
responseAddrs, err = r.dnsClient.Lookup(ctx, transport, domain, dns.QueryOptions{Strategy: strategy})
|
|
|
|
} else {
|
|
|
|
var (
|
|
|
|
transport dns.Transport
|
|
|
|
options dns.QueryOptions
|
|
|
|
rule adapter.DNSRule
|
|
|
|
ruleIndex int
|
|
|
|
)
|
|
|
|
ruleIndex = -1
|
|
|
|
for {
|
|
|
|
dnsCtx := adapter.OverrideContext(ctx)
|
|
|
|
var addressLimit bool
|
|
|
|
transport, options, rule, ruleIndex = r.matchDNS(ctx, false, ruleIndex, true)
|
|
|
|
if strategy != dns.DomainStrategyAsIS {
|
|
|
|
options.Strategy = strategy
|
|
|
|
}
|
2024-11-06 17:30:40 +08:00
|
|
|
if rule != nil {
|
|
|
|
switch action := rule.Action().(type) {
|
|
|
|
case *R.RuleActionReject:
|
|
|
|
switch action.Method {
|
|
|
|
case C.RuleActionRejectMethodDefault:
|
|
|
|
return nil, nil
|
|
|
|
case C.RuleActionRejectMethodDrop:
|
|
|
|
return nil, tun.ErrDrop
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-10-22 22:01:28 +08:00
|
|
|
if rule != nil && rule.WithAddressLimit() {
|
|
|
|
addressLimit = true
|
|
|
|
responseAddrs, err = r.dnsClient.LookupWithResponseCheck(dnsCtx, transport, domain, options, func(responseAddrs []netip.Addr) bool {
|
|
|
|
metadata.DestinationAddresses = responseAddrs
|
|
|
|
return rule.MatchAddressLimit(metadata)
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
addressLimit = false
|
|
|
|
responseAddrs, err = r.dnsClient.Lookup(dnsCtx, transport, domain, options)
|
|
|
|
}
|
|
|
|
if !addressLimit || err == nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
printResult()
|
2024-02-03 17:45:27 +08:00
|
|
|
}
|
2022-08-22 12:01:50 +08:00
|
|
|
}
|
2024-10-22 22:01:28 +08:00
|
|
|
printResult()
|
2024-02-14 20:42:58 +08:00
|
|
|
if len(responseAddrs) > 0 {
|
|
|
|
r.dnsLogger.InfoContext(ctx, "lookup succeed for ", domain, ": ", strings.Join(F.MapToString(responseAddrs), " "))
|
2022-08-03 18:55:39 +08:00
|
|
|
}
|
2024-02-14 20:42:58 +08:00
|
|
|
return responseAddrs, err
|
2022-08-03 18:55:39 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Router) LookupDefault(ctx context.Context, domain string) ([]netip.Addr, error) {
|
2022-08-22 12:01:50 +08:00
|
|
|
return r.Lookup(ctx, domain, dns.DomainStrategyAsIS)
|
2022-08-03 18:55:39 +08:00
|
|
|
}
|
|
|
|
|
2023-08-24 21:52:38 +08:00
|
|
|
func (r *Router) ClearDNSCache() {
|
|
|
|
r.dnsClient.ClearCache()
|
|
|
|
if r.platformInterface != nil {
|
|
|
|
r.platformInterface.ClearDNSCache()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-03 17:45:27 +08:00
|
|
|
func isAddressQuery(message *mDNS.Msg) bool {
|
|
|
|
for _, question := range message.Question {
|
2024-06-23 01:04:22 +08:00
|
|
|
if question.Qtype == mDNS.TypeA || question.Qtype == mDNS.TypeAAAA || question.Qtype == mDNS.TypeHTTPS {
|
2024-02-03 17:45:27 +08:00
|
|
|
return true
|
|
|
|
}
|
2022-08-03 18:55:39 +08:00
|
|
|
}
|
2024-02-03 17:45:27 +08:00
|
|
|
return false
|
2022-08-03 18:55:39 +08:00
|
|
|
}
|
|
|
|
|
2022-09-13 16:18:39 +08:00
|
|
|
func fqdnToDomain(fqdn string) string {
|
|
|
|
if mDNS.IsFqdn(fqdn) {
|
|
|
|
return fqdn[:len(fqdn)-1]
|
2022-08-03 18:55:39 +08:00
|
|
|
}
|
2022-09-13 16:18:39 +08:00
|
|
|
return fqdn
|
2022-08-03 18:55:39 +08:00
|
|
|
}
|
|
|
|
|
2022-09-13 16:18:39 +08: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 18:55:39 +08:00
|
|
|
}
|
2022-09-13 16:18:39 +08:00
|
|
|
return string
|
2022-08-03 18:55:39 +08:00
|
|
|
}
|