refactor: DNS

This commit is contained in:
世界 2025-03-16 14:50:44 +08:00
parent f4c29840c3
commit 0415782b2d
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
89 changed files with 4794 additions and 1733 deletions

View file

@ -1,29 +1,53 @@
package option
import (
"context"
"net/netip"
"net/url"
"os"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/experimental/deprecated"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/json"
"github.com/sagernet/sing/common/json/badjson"
"github.com/sagernet/sing/common/json/badoption"
M "github.com/sagernet/sing/common/metadata"
"github.com/sagernet/sing/service"
"github.com/miekg/dns"
)
type DNSOptions struct {
Servers []DNSServerOptions `json:"servers,omitempty"`
Rules []DNSRule `json:"rules,omitempty"`
Final string `json:"final,omitempty"`
ReverseMapping bool `json:"reverse_mapping,omitempty"`
FakeIP *DNSFakeIPOptions `json:"fakeip,omitempty"`
type RawDNSOptions struct {
Servers []NewDNSServerOptions `json:"servers,omitempty"`
Rules []DNSRule `json:"rules,omitempty"`
Final string `json:"final,omitempty"`
ReverseMapping bool `json:"reverse_mapping,omitempty"`
DNSClientOptions
}
type DNSServerOptions struct {
Tag string `json:"tag,omitempty"`
Address string `json:"address"`
AddressResolver string `json:"address_resolver,omitempty"`
AddressStrategy DomainStrategy `json:"address_strategy,omitempty"`
AddressFallbackDelay badoption.Duration `json:"address_fallback_delay,omitempty"`
Strategy DomainStrategy `json:"strategy,omitempty"`
Detour string `json:"detour,omitempty"`
ClientSubnet *badoption.Prefixable `json:"client_subnet,omitempty"`
type LegacyDNSOptions struct {
FakeIP *LegacyDNSFakeIPOptions `json:"fakeip,omitempty"`
}
type DNSOptions struct {
RawDNSOptions
LegacyDNSOptions
}
func (o *DNSOptions) UnmarshalJSONContext(ctx context.Context, content []byte) error {
err := json.UnmarshalContext(ctx, content, &o.LegacyDNSOptions)
if err != nil {
return err
}
if o.FakeIP != nil && o.FakeIP.Enabled {
deprecated.Report(ctx, deprecated.OptionLegacyDNSFakeIPOptions)
ctx = context.WithValue(ctx, (*LegacyDNSFakeIPOptions)(nil), o.FakeIP)
}
legacyOptions := o.LegacyDNSOptions
o.LegacyDNSOptions = LegacyDNSOptions{}
return badjson.UnmarshallExcludedContext(ctx, content, legacyOptions, &o.RawDNSOptions)
}
type DNSClientOptions struct {
@ -35,8 +59,261 @@ type DNSClientOptions struct {
ClientSubnet *badoption.Prefixable `json:"client_subnet,omitempty"`
}
type DNSFakeIPOptions struct {
Enabled bool `json:"enabled,omitempty"`
Inet4Range *netip.Prefix `json:"inet4_range,omitempty"`
Inet6Range *netip.Prefix `json:"inet6_range,omitempty"`
type LegacyDNSFakeIPOptions struct {
Enabled bool `json:"enabled,omitempty"`
Inet4Range *badoption.Prefix `json:"inet4_range,omitempty"`
Inet6Range *badoption.Prefix `json:"inet6_range,omitempty"`
}
type DNSTransportOptionsRegistry interface {
CreateOptions(transportType string) (any, bool)
}
type _NewDNSServerOptions struct {
Type string `json:"type,omitempty"`
Tag string `json:"tag,omitempty"`
Options any `json:"-"`
}
type NewDNSServerOptions _NewDNSServerOptions
func (o *NewDNSServerOptions) MarshalJSONContext(ctx context.Context) ([]byte, error) {
return badjson.MarshallObjectsContext(ctx, (*_NewDNSServerOptions)(o), o.Options)
}
func (o *NewDNSServerOptions) UnmarshalJSONContext(ctx context.Context, content []byte) error {
err := json.UnmarshalContext(ctx, content, (*_NewDNSServerOptions)(o))
if err != nil {
return err
}
registry := service.FromContext[DNSTransportOptionsRegistry](ctx)
if registry == nil {
return E.New("missing outbound options registry in context")
}
var options any
switch o.Type {
case "", C.DNSTypeLegacy:
o.Type = C.DNSTypeLegacy
options = new(LegacyDNSServerOptions)
deprecated.Report(ctx, deprecated.OptionLegacyDNSTransport)
default:
var loaded bool
options, loaded = registry.CreateOptions(o.Type)
if !loaded {
return E.New("unknown transport type: ", o.Type)
}
}
err = badjson.UnmarshallExcludedContext(ctx, content, (*_Outbound)(o), options)
if err != nil {
return err
}
o.Options = options
if o.Type == C.DNSTypeLegacy {
err = o.Upgrade(ctx)
if err != nil {
return err
}
}
return nil
}
func (o *NewDNSServerOptions) Upgrade(ctx context.Context) error {
if o.Type != C.DNSTypeLegacy {
return nil
}
defer func() {
encoder := json.NewEncoder(os.Stderr)
encoder.SetIndent("", " ")
encoder.Encode(o)
}()
options := o.Options.(*LegacyDNSServerOptions)
serverURL, _ := url.Parse(options.Address)
var serverType string
if serverURL.Scheme != "" {
serverType = serverURL.Scheme
} else {
switch options.Address {
case "local", "fakeip":
serverType = options.Address
default:
serverType = C.DNSTypeUDP
}
}
remoteOptions := RemoteDNSServerOptions{
LocalDNSServerOptions: LocalDNSServerOptions{
DialerOptions: DialerOptions{
Detour: options.Detour,
},
LegacyStrategy: options.Strategy,
LegacyDefaultDialer: options.Detour == "",
LegacyClientSubnet: options.ClientSubnet.Build(netip.Prefix{}),
},
AddressResolver: options.AddressResolver,
AddressStrategy: options.AddressStrategy,
AddressFallbackDelay: options.AddressFallbackDelay,
}
switch serverType {
case C.DNSTypeLocal:
o.Type = C.DNSTypeLocal
o.Options = &remoteOptions.LocalDNSServerOptions
case C.DNSTypeUDP:
o.Type = C.DNSTypeUDP
o.Options = &remoteOptions
var serverAddr M.Socksaddr
if serverURL.Scheme == "" {
serverAddr = M.ParseSocksaddr(options.Address)
} else {
serverAddr = M.ParseSocksaddr(serverURL.Host)
}
if !serverAddr.IsValid() {
return E.New("invalid server address")
}
remoteOptions.Server = serverAddr.Addr.String()
if serverAddr.Port != 0 && serverAddr.Port != 53 {
remoteOptions.ServerPort = serverAddr.Port
}
remoteOptions.Server = serverAddr.AddrString()
remoteOptions.ServerPort = serverAddr.Port
case C.DNSTypeTCP:
o.Type = C.DNSTypeTCP
o.Options = &remoteOptions
serverAddr := M.ParseSocksaddr(serverURL.Host)
if !serverAddr.IsValid() {
return E.New("invalid server address")
}
remoteOptions.Server = serverAddr.Addr.String()
if serverAddr.Port != 0 && serverAddr.Port != 53 {
remoteOptions.ServerPort = serverAddr.Port
}
remoteOptions.Server = serverAddr.AddrString()
remoteOptions.ServerPort = serverAddr.Port
case C.DNSTypeTLS, C.DNSTypeQUIC:
o.Type = serverType
serverAddr := M.ParseSocksaddr(serverURL.Host)
if !serverAddr.IsValid() {
return E.New("invalid server address")
}
remoteOptions.Server = serverAddr.Addr.String()
if serverAddr.Port != 0 && serverAddr.Port != 853 {
remoteOptions.ServerPort = serverAddr.Port
}
o.Options = &RemoteTLSDNSServerOptions{
RemoteDNSServerOptions: remoteOptions,
}
case C.DNSTypeHTTPS, C.DNSTypeHTTP3:
o.Type = serverType
httpsOptions := RemoteHTTPSDNSServerOptions{
RemoteTLSDNSServerOptions: RemoteTLSDNSServerOptions{
RemoteDNSServerOptions: remoteOptions,
},
}
o.Options = &httpsOptions
serverAddr := M.ParseSocksaddr(serverURL.Host)
if !serverAddr.IsValid() {
return E.New("invalid server address")
}
httpsOptions.Server = serverAddr.Addr.String()
if serverAddr.Port != 0 && serverAddr.Port != 443 {
httpsOptions.ServerPort = serverAddr.Port
}
if serverURL.Path != "/dns-query" {
httpsOptions.Path = serverURL.Path
}
case "rcode":
var rcode int
switch serverURL.Host {
case "success":
rcode = dns.RcodeSuccess
case "format_error":
rcode = dns.RcodeFormatError
case "server_failure":
rcode = dns.RcodeServerFailure
case "name_error":
rcode = dns.RcodeNameError
case "not_implemented":
rcode = dns.RcodeNotImplemented
case "refused":
rcode = dns.RcodeRefused
default:
return E.New("unknown rcode: ", serverURL.Host)
}
o.Type = C.DNSTypePreDefined
o.Options = &PredefinedDNSServerOptions{
Responses: []DNSResponseOptions{
{
RCode: common.Ptr(DNSRCode(rcode)),
},
},
}
case C.DNSTypeDHCP:
o.Type = C.DNSTypeDHCP
dhcpOptions := DHCPDNSServerOptions{}
if serverURL.Host != "" && serverURL.Host != "auto" {
dhcpOptions.Interface = serverURL.Host
}
o.Options = &dhcpOptions
case C.DNSTypeFakeIP:
o.Type = C.DNSTypeFakeIP
fakeipOptions := FakeIPDNSServerOptions{}
if legacyOptions, loaded := ctx.Value((*LegacyDNSFakeIPOptions)(nil)).(*LegacyDNSFakeIPOptions); loaded {
fakeipOptions.Inet4Range = legacyOptions.Inet4Range
fakeipOptions.Inet6Range = legacyOptions.Inet6Range
}
o.Options = &fakeipOptions
default:
return E.New("unsupported DNS server scheme: ", serverType)
}
return nil
}
type LegacyDNSServerOptions struct {
Address string `json:"address"`
AddressResolver string `json:"address_resolver,omitempty"`
AddressStrategy DomainStrategy `json:"address_strategy,omitempty"`
AddressFallbackDelay badoption.Duration `json:"address_fallback_delay,omitempty"`
Strategy DomainStrategy `json:"strategy,omitempty"`
Detour string `json:"detour,omitempty"`
ClientSubnet *badoption.Prefixable `json:"client_subnet,omitempty"`
}
type HostsDNSServerOptions struct {
Path badoption.Listable[string] `json:"path,omitempty"`
Predefined badjson.TypedMap[string, badoption.Listable[netip.Addr]] `json:"predefined,omitempty"`
}
type LocalDNSServerOptions struct {
DialerOptions
LegacyStrategy DomainStrategy `json:"-"`
LegacyDefaultDialer bool `json:"-"`
LegacyClientSubnet netip.Prefix `json:"-"`
}
type RemoteDNSServerOptions struct {
LocalDNSServerOptions
ServerOptions
AddressResolver string `json:"address_resolver,omitempty"`
AddressStrategy DomainStrategy `json:"address_strategy,omitempty"`
AddressFallbackDelay badoption.Duration `json:"address_fallback_delay,omitempty"`
}
type RemoteTLSDNSServerOptions struct {
RemoteDNSServerOptions
OutboundTLSOptionsContainer
}
type RemoteHTTPSDNSServerOptions struct {
RemoteTLSDNSServerOptions
Path string `json:"path,omitempty"`
Method string `json:"method,omitempty"`
Headers badoption.HTTPHeader `json:"headers,omitempty"`
}
type FakeIPDNSServerOptions struct {
Inet4Range *badoption.Prefix `json:"inet4_range,omitempty"`
Inet6Range *badoption.Prefix `json:"inet6_range,omitempty"`
}
type DHCPDNSServerOptions struct {
LocalDNSServerOptions
Interface string `json:"interface,omitempty"`
}

161
option/dns_record.go Normal file
View file

@ -0,0 +1,161 @@
package option
import (
"encoding/base64"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/json"
"github.com/sagernet/sing/common/json/badoption"
M "github.com/sagernet/sing/common/metadata"
"github.com/miekg/dns"
)
type PredefinedDNSServerOptions struct {
Responses []DNSResponseOptions `json:"responses,omitempty"`
}
type DNSResponseOptions struct {
Query badoption.Listable[string] `json:"query,omitempty"`
QueryType badoption.Listable[DNSQueryType] `json:"query_type,omitempty"`
RCode *DNSRCode `json:"rcode,omitempty"`
Answer badoption.Listable[DNSRecordOptions] `json:"answer,omitempty"`
Ns badoption.Listable[DNSRecordOptions] `json:"ns,omitempty"`
Extra badoption.Listable[DNSRecordOptions] `json:"extra,omitempty"`
}
type DNSRCode int
func (r DNSRCode) MarshalJSON() ([]byte, error) {
rCodeValue, loaded := dns.RcodeToString[int(r)]
if loaded {
return json.Marshal(rCodeValue)
}
return json.Marshal(int(r))
}
func (r *DNSRCode) UnmarshalJSON(bytes []byte) error {
var intValue int
err := json.Unmarshal(bytes, &intValue)
if err == nil {
*r = DNSRCode(intValue)
return nil
}
var stringValue string
err = json.Unmarshal(bytes, &stringValue)
if err != nil {
return err
}
rCodeValue, loaded := dns.StringToRcode[stringValue]
if !loaded {
return E.New("unknown rcode: " + stringValue)
}
*r = DNSRCode(rCodeValue)
return nil
}
func (r *DNSRCode) Build() int {
if r == nil {
return dns.RcodeSuccess
}
return int(*r)
}
func (o DNSResponseOptions) Build() ([]dns.Question, *dns.Msg, error) {
var questions []dns.Question
if len(o.Query) == 0 && len(o.QueryType) == 0 {
questions = []dns.Question{{Qclass: dns.ClassINET}}
} else if len(o.Query) == 0 {
for _, queryType := range o.QueryType {
questions = append(questions, dns.Question{
Qtype: uint16(queryType),
Qclass: dns.ClassINET,
})
}
} else if len(o.QueryType) == 0 {
for _, domain := range o.Query {
questions = append(questions, dns.Question{
Name: dns.Fqdn(domain),
Qclass: dns.ClassINET,
})
}
} else {
for _, queryType := range o.QueryType {
for _, domain := range o.Query {
questions = append(questions, dns.Question{
Name: dns.Fqdn(domain),
Qtype: uint16(queryType),
Qclass: dns.ClassINET,
})
}
}
}
return questions, &dns.Msg{
MsgHdr: dns.MsgHdr{
Response: true,
Rcode: o.RCode.Build(),
Authoritative: true,
RecursionDesired: true,
RecursionAvailable: true,
},
Answer: common.Map(o.Answer, DNSRecordOptions.build),
Ns: common.Map(o.Ns, DNSRecordOptions.build),
Extra: common.Map(o.Extra, DNSRecordOptions.build),
}, nil
}
type DNSRecordOptions struct {
dns.RR
fromBase64 bool
}
func (o DNSRecordOptions) MarshalJSON() ([]byte, error) {
if o.fromBase64 {
buffer := buf.Get(dns.Len(o.RR))
defer buf.Put(buffer)
offset, err := dns.PackRR(o.RR, buffer, 0, nil, false)
if err != nil {
return nil, err
}
return json.Marshal(base64.StdEncoding.EncodeToString(buffer[:offset]))
}
return json.Marshal(o.RR.String())
}
func (o *DNSRecordOptions) UnmarshalJSON(data []byte) error {
var stringValue string
err := json.Unmarshal(data, &stringValue)
if err != nil {
return err
}
binary, err := base64.StdEncoding.DecodeString(stringValue)
if err == nil {
return o.unmarshalBase64(binary)
}
record, err := dns.NewRR(stringValue)
if err != nil {
return err
}
if a, isA := record.(*dns.A); isA {
a.A = M.AddrFromIP(a.A).Unmap().AsSlice()
}
o.RR = record
return nil
}
func (o *DNSRecordOptions) unmarshalBase64(binary []byte) error {
record, _, err := dns.UnpackRR(binary, 0)
if err != nil {
return E.New("parse binary DNS record")
}
o.RR = record
o.fromBase64 = true
return nil
}
func (o DNSRecordOptions) build() dns.RR {
return o.RR
}

View file

@ -7,7 +7,6 @@ import (
"time"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-dns"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/json"
"github.com/sagernet/sing/common/json/badjson"
@ -168,12 +167,14 @@ func (r *RouteOptionsActionOptions) UnmarshalJSON(data []byte) error {
type DNSRouteActionOptions struct {
Server string `json:"server,omitempty"`
Strategy DomainStrategy `json:"strategy,omitempty"`
DisableCache bool `json:"disable_cache,omitempty"`
RewriteTTL *uint32 `json:"rewrite_ttl,omitempty"`
ClientSubnet *badoption.Prefixable `json:"client_subnet,omitempty"`
}
type _DNSRouteOptionsActionOptions struct {
Strategy DomainStrategy `json:"strategy,omitempty"`
DisableCache bool `json:"disable_cache,omitempty"`
RewriteTTL *uint32 `json:"rewrite_ttl,omitempty"`
ClientSubnet *badoption.Prefixable `json:"client_subnet,omitempty"`
@ -225,7 +226,7 @@ func (d DirectActionOptions) Descriptions() []string {
if d.UDPFragment != nil {
descriptions = append(descriptions, "udp_fragment="+fmt.Sprint(*d.UDPFragment))
}
if d.DomainStrategy != DomainStrategy(dns.DomainStrategyAsIS) {
if d.DomainStrategy != DomainStrategy(C.DomainStrategyAsIS) {
descriptions = append(descriptions, "domain_strategy="+d.DomainStrategy.String())
}
if d.FallbackDelay != 0 {
@ -252,6 +253,14 @@ type _RejectActionOptions struct {
type RejectActionOptions _RejectActionOptions
func (r RejectActionOptions) MarshalJSON() ([]byte, error) {
switch r.Method {
case C.RuleActionRejectMethodDefault:
r.Method = ""
}
return json.Marshal((_RejectActionOptions)(r))
}
func (r *RejectActionOptions) UnmarshalJSON(bytes []byte) error {
err := json.Unmarshal(bytes, (*_RejectActionOptions)(r))
if err != nil {

View file

@ -83,6 +83,7 @@ type RawDefaultDNSRule struct {
GeoIP badoption.Listable[string] `json:"geoip,omitempty"`
IPCIDR badoption.Listable[string] `json:"ip_cidr,omitempty"`
IPIsPrivate bool `json:"ip_is_private,omitempty"`
IPAcceptAny bool `json:"ip_accept_any,omitempty"`
SourceIPCIDR badoption.Listable[string] `json:"source_ip_cidr,omitempty"`
SourceIPIsPrivate bool `json:"source_ip_is_private,omitempty"`
SourcePort badoption.Listable[uint16] `json:"source_port,omitempty"`

View file

@ -4,7 +4,6 @@ import (
"strings"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-dns"
E "github.com/sagernet/sing/common/exceptions"
F "github.com/sagernet/sing/common/format"
"github.com/sagernet/sing/common/json"
@ -45,19 +44,19 @@ func (v NetworkList) Build() []string {
return strings.Split(string(v), "\n")
}
type DomainStrategy dns.DomainStrategy
type DomainStrategy C.DomainStrategy
func (s DomainStrategy) String() string {
switch dns.DomainStrategy(s) {
case dns.DomainStrategyAsIS:
switch C.DomainStrategy(s) {
case C.DomainStrategyAsIS:
return ""
case dns.DomainStrategyPreferIPv4:
case C.DomainStrategyPreferIPv4:
return "prefer_ipv4"
case dns.DomainStrategyPreferIPv6:
case C.DomainStrategyPreferIPv6:
return "prefer_ipv6"
case dns.DomainStrategyUseIPv4:
case C.DomainStrategyIPv4Only:
return "ipv4_only"
case dns.DomainStrategyUseIPv6:
case C.DomainStrategyIPv6Only:
return "ipv6_only"
default:
panic(E.New("unknown domain strategy: ", s))
@ -66,17 +65,17 @@ func (s DomainStrategy) String() string {
func (s DomainStrategy) MarshalJSON() ([]byte, error) {
var value string
switch dns.DomainStrategy(s) {
case dns.DomainStrategyAsIS:
switch C.DomainStrategy(s) {
case C.DomainStrategyAsIS:
value = ""
// value = "as_is"
case dns.DomainStrategyPreferIPv4:
case C.DomainStrategyPreferIPv4:
value = "prefer_ipv4"
case dns.DomainStrategyPreferIPv6:
case C.DomainStrategyPreferIPv6:
value = "prefer_ipv6"
case dns.DomainStrategyUseIPv4:
case C.DomainStrategyIPv4Only:
value = "ipv4_only"
case dns.DomainStrategyUseIPv6:
case C.DomainStrategyIPv6Only:
value = "ipv6_only"
default:
return nil, E.New("unknown domain strategy: ", s)
@ -92,15 +91,15 @@ func (s *DomainStrategy) UnmarshalJSON(bytes []byte) error {
}
switch value {
case "", "as_is":
*s = DomainStrategy(dns.DomainStrategyAsIS)
*s = DomainStrategy(C.DomainStrategyAsIS)
case "prefer_ipv4":
*s = DomainStrategy(dns.DomainStrategyPreferIPv4)
*s = DomainStrategy(C.DomainStrategyPreferIPv4)
case "prefer_ipv6":
*s = DomainStrategy(dns.DomainStrategyPreferIPv6)
*s = DomainStrategy(C.DomainStrategyPreferIPv6)
case "ipv4_only":
*s = DomainStrategy(dns.DomainStrategyUseIPv4)
*s = DomainStrategy(C.DomainStrategyIPv4Only)
case "ipv6_only":
*s = DomainStrategy(dns.DomainStrategyUseIPv6)
*s = DomainStrategy(C.DomainStrategyIPv6Only)
default:
return E.New("unknown domain strategy: ", value)
}