Fix hosts DNS server

This commit is contained in:
Kevin Zhou 2025-03-09 15:44:03 +08:00 committed by 世界
parent fc41577066
commit c7ba57b6a4
No known key found for this signature in database
GPG Key ID: CD109927C34A63C4
3 changed files with 15 additions and 7 deletions

View File

@ -2,6 +2,7 @@ package hosts
import (
"context"
"net/netip"
"os"
"github.com/sagernet/sing-box/adapter"
@ -9,6 +10,8 @@ import (
"github.com/sagernet/sing-box/dns"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing/common/json/badjson"
"github.com/sagernet/sing/common/json/badoption"
"github.com/sagernet/sing/service/filemanager"
mDNS "github.com/miekg/dns"
@ -23,6 +26,7 @@ var _ adapter.DNSTransport = (*Transport)(nil)
type Transport struct {
dns.TransportAdapter
files []*File
predefined badjson.TypedMap[string, badoption.Listable[netip.Addr]]
}
func NewTransport(ctx context.Context, logger log.ContextLogger, tag string, options option.HostsDNSServerOptions) (adapter.DNSTransport, error) {
@ -37,6 +41,7 @@ func NewTransport(ctx context.Context, logger log.ContextLogger, tag string, opt
return &Transport{
TransportAdapter: dns.NewTransportAdapter(C.DNSTypeHosts, tag, nil),
files: files,
predefined: options.Predefined,
}, nil
}
@ -47,6 +52,10 @@ func (t *Transport) Exchange(ctx context.Context, message *mDNS.Msg) (*mDNS.Msg,
question := message.Question[0]
domain := dns.FqdnToDomain(question.Name)
if question.Qtype == mDNS.TypeA || question.Qtype == mDNS.TypeAAAA {
if addresses, ok := t.predefined.Get(domain); ok {
return dns.FixedResponse(message.Id, question, addresses, C.DefaultDNSTTL), nil
}
for _, file := range t.files {
addresses := file.Lookup(domain)
if len(addresses) > 0 {

View File

@ -9,8 +9,6 @@ import (
"strings"
"sync"
"time"
"github.com/miekg/dns"
)
const cacheMaxAge = 5 * time.Second
@ -91,8 +89,9 @@ func (f *File) update() {
continue
}
for index := 1; index < len(fields); index++ {
canonicalName := dns.CanonicalName(fields[index])
byName[canonicalName] = append(byName[canonicalName], addr)
// canonicalName := dns.CanonicalName(fields[index])
domain := fields[index]
byName[domain] = append(byName[domain], addr)
}
}
f.expire = now.Add(cacheMaxAge)

View File

@ -11,6 +11,6 @@ import (
func TestHosts(t *testing.T) {
t.Parallel()
require.Equal(t, []netip.Addr{netip.AddrFrom4([4]byte{127, 0, 0, 1}), netip.IPv6Loopback()}, hosts.NewFile("testdata/hosts").Lookup("localhost."))
require.NotEmpty(t, hosts.NewFile(hosts.DefaultPath).Lookup("localhost."))
require.Equal(t, []netip.Addr{netip.AddrFrom4([4]byte{127, 0, 0, 1}), netip.IPv6Loopback()}, hosts.NewFile("testdata/hosts").Lookup("localhost"))
require.NotEmpty(t, hosts.NewFile(hosts.DefaultPath).Lookup("localhost"))
}