Repository navigation
fix(resolver): ask failing DNS servers instead of answering nothing #2294
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,266 @@ | ||
| package resolver | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "net" | ||
| "sync/atomic" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/miekg/dns" | ||
|
|
||
| "github.com/safing/portmaster/service/netenv" | ||
| ) | ||
|
|
||
| func TestHasHealthyResolver(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| healthy := newTestResolver(&net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 53}) | ||
| failing := newTestResolver(&net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 53}) | ||
| markFailing(t, failing) | ||
| linkLocalUnavailable := newTestResolver(&net.UDPAddr{IP: net.IPv4(169, 254, 0, 1), Port: 53}) | ||
| linkLocalUnavailable.LinkLocalUnavailable = true | ||
|
|
||
| tests := []struct { | ||
| name string | ||
| resolvers []*Resolver | ||
| want bool | ||
| }{ | ||
| {"no resolvers", nil, false}, | ||
| {"healthy resolver", []*Resolver{failing, healthy}, true}, | ||
| {"only failing resolvers", []*Resolver{failing, failing}, false}, | ||
| {"failing and unavailable link-local resolver", []*Resolver{failing, linkLocalUnavailable}, false}, | ||
| } | ||
| for _, tt := range tests { | ||
| if got := hasHealthyResolver(tt.resolvers); got != tt.want { | ||
| t.Errorf("%s: hasHealthyResolver() = %v, want %v", tt.name, got, tt.want) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // TestResolveAndCacheAsksFailingResolvers checks that a failing resolver is | ||
| // asked when no other resolver can be asked, instead of answering nothing. | ||
| // Which resolvers are skipped is covered by TestHasHealthyResolver. | ||
| // | ||
| // The test queries the online check domain, which is resolved even while the | ||
| // device is offline, so the result does not depend on the network of the test | ||
| // machine. The online status check of the running module may resolve the same | ||
| // domain at the same time, so the resolver is checked to be asked at least | ||
| // once. | ||
| func TestResolveAndCacheAsksFailingResolvers(t *testing.T) { //nolint:paralleltest // Replaces the global resolvers. | ||
| t.Run("only resolver is failing and answers", func(t *testing.T) { | ||
| addr, queries := startTestDNSServer(t, dns.RcodeSuccess) | ||
| failing := newTestResolver(addr) | ||
| markFailing(t, failing) | ||
| useGlobalResolvers(t, failing) | ||
|
|
||
| rrCache, err := resolveTestQuery(t, 5*time.Second) | ||
| if err != nil { | ||
| t.Fatalf("query failed: %s", err) | ||
| } | ||
| if rrCache.RCode != dns.RcodeSuccess || len(rrCache.Answer) == 0 { | ||
| t.Errorf("expected an answer, got RCode %s with %d records", dns.RcodeToString[rrCache.RCode], len(rrCache.Answer)) | ||
| } | ||
| if queries.Load() == 0 { | ||
| t.Error("failing resolver was not asked") | ||
| } | ||
| if failing.Conn.IsFailing() { | ||
| t.Error("failing state was not cleared by the answer") | ||
| } | ||
| }) | ||
|
|
||
| t.Run("only resolver is failing and does not answer", func(t *testing.T) { | ||
| addr, _ := startTestDNSServer(t, noReply) | ||
| failing := newTestResolver(addr) | ||
| markFailing(t, failing) | ||
| useGlobalResolvers(t, failing) | ||
|
|
||
| // Without the failing resolver being asked, the result would be | ||
| // ErrNotFound instead of the error of the query. | ||
| _, err := resolveTestQuery(t, 5*time.Second) | ||
| if err == nil { | ||
| t.Fatal("expected an error, got an answer") | ||
| } | ||
| if errors.Is(err, ErrNotFound) { | ||
| t.Errorf("expected a failure, got %q, which is answered as NXDOMAIN", err) | ||
| } | ||
| }) | ||
| } | ||
|
|
||
| // TestCheckFailingResolvers checks that the recovery check clears a failing | ||
| // resolver as soon as it answers, whatever the answer is, and keeps it failing | ||
| // while it does not answer. | ||
| func TestCheckFailingResolvers(t *testing.T) { //nolint:paralleltest // Replaces the global resolvers. | ||
| tests := []struct { | ||
| name string | ||
| rcode int | ||
| wantFailing bool | ||
| }{ | ||
| {"answers with another IP", dns.RcodeSuccess, false}, | ||
| {"answers with NXDOMAIN", dns.RcodeNameError, false}, | ||
| {"answers with REFUSED", dns.RcodeRefused, false}, | ||
| {"answers with SERVFAIL", dns.RcodeServerFailure, false}, | ||
| {"does not answer", noReply, true}, | ||
| } | ||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| addr, _ := startTestDNSServer(t, tt.rcode) | ||
| resolver := newTestResolver(addr) | ||
| markFailing(t, resolver) | ||
| useGlobalResolvers(t, resolver) | ||
|
|
||
| if err := module.mgr.Do("check failing resolvers", checkFailingResolvers); err != nil { | ||
| t.Fatalf("check failed: %s", err) | ||
| } | ||
| if got := resolver.Conn.IsFailing(); got != tt.wantFailing { | ||
| t.Errorf("resolver failing = %v, want %v", got, tt.wantFailing) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| // resolveTestQuery resolves the online check domain through the global | ||
| // resolvers, without caching. | ||
| func resolveTestQuery(t *testing.T, timeout time.Duration) (*RRCache, error) { | ||
| t.Helper() | ||
|
|
||
| ctx, cancel := context.WithTimeout(context.Background(), timeout) | ||
| defer cancel() | ||
|
|
||
| q := &Query{ | ||
| FQDN: netenv.DNSTestDomain, | ||
| QType: dns.Type(dns.TypeA), | ||
| NoCaching: true, | ||
| } | ||
| if !q.check() { | ||
| t.Fatalf("invalid query for %s", q.FQDN) | ||
| } | ||
| return resolveAndCache(ctx, q, nil) | ||
| } | ||
|
|
||
| // newTestResolver returns a plain DNS resolver for the given address. It is | ||
| // assigned by the operating system, so that clearing its failing state does | ||
| // not change the global netenv.ConnectedToDNS flag. | ||
| func newTestResolver(addr *net.UDPAddr) *Resolver { | ||
| resolver := &Resolver{ | ||
| ServerAddress: addr.String(), | ||
| Info: &ResolverInfo{ | ||
| Name: "test", | ||
| Type: ServerTypeDNS, | ||
| Source: ServerSourceOperatingSystem, | ||
| IP: addr.IP, | ||
| Port: uint16(addr.Port), //nolint:gosec // Ports of net.Addr are within the uint16 range. | ||
| }, | ||
| } | ||
| resolver.Conn = NewPlainResolver(resolver) | ||
| return resolver | ||
| } | ||
|
|
||
| // markFailing marks the resolver as failing, independent of the online | ||
| // status, which ReportFailure depends on. | ||
| func markFailing(t *testing.T, resolver *Resolver) { | ||
| t.Helper() | ||
|
|
||
| conn, ok := resolver.Conn.(*PlainResolver) | ||
| if !ok { | ||
| t.Fatalf("unexpected resolver connection type %T", resolver.Conn) | ||
| } | ||
| conn.failing.Set() | ||
| } | ||
|
|
||
| // useGlobalResolvers replaces the global resolvers for the duration of the | ||
| // test. | ||
| // | ||
| // It also clears the resolver config, so that the test resolvers never count | ||
| // as "all configured resolvers failing". Otherwise resolving would send a | ||
| // notification, and the notifications module is not running in these tests. | ||
| func useGlobalResolvers(t *testing.T, resolvers ...*Resolver) { | ||
| t.Helper() | ||
|
|
||
| resolversLock.Lock() | ||
| previous, previousConfig := globalResolvers, currentResolverConfig | ||
| globalResolvers, currentResolverConfig = resolvers, nil | ||
| resolversLock.Unlock() | ||
|
|
||
| t.Cleanup(func() { | ||
| resolversLock.Lock() | ||
| defer resolversLock.Unlock() | ||
| globalResolvers, currentResolverConfig = previous, previousConfig | ||
| }) | ||
| } | ||
|
|
||
| // noReply makes startTestDNSServer return an address nobody listens on. | ||
| const noReply = -1 | ||
|
|
||
| // startTestDNSServer starts a local DNS server for the duration of the test. | ||
| // It answers every query with the given RCode, adding 127.0.0.1 to successful | ||
| // answers. That is not the expected IP of the online check domain. It returns | ||
| // the server address and the number of queries received. | ||
| // | ||
| // With noReply, no server is started: queries to the address fail at once | ||
| // instead of waiting for a timeout. A waiting query, for example of the online | ||
| // status check of the running module, could still be running after the test. | ||
| func startTestDNSServer(t *testing.T, rcode int) (*net.UDPAddr, *atomic.Int32) { | ||
| t.Helper() | ||
|
|
||
| pc, err := net.ListenPacket("udp4", "127.0.0.1:0") | ||
| if err != nil { | ||
| t.Fatalf("failed to listen: %s", err) | ||
| } | ||
| addr, ok := pc.LocalAddr().(*net.UDPAddr) | ||
| if !ok { | ||
| t.Fatalf("unexpected local address type %T", pc.LocalAddr()) | ||
| } | ||
|
|
||
| queries := new(atomic.Int32) | ||
| if rcode == noReply { | ||
| if err := pc.Close(); err != nil { | ||
| t.Fatalf("failed to close listener: %s", err) | ||
| } | ||
| return addr, queries | ||
| } | ||
|
|
||
| started := make(chan struct{}) | ||
| server := &dns.Server{ | ||
| PacketConn: pc, | ||
| NotifyStartedFunc: func() { close(started) }, | ||
| Handler: dns.HandlerFunc(func(w dns.ResponseWriter, query *dns.Msg) { | ||
| queries.Add(1) | ||
| if len(query.Question) == 0 { | ||
| return | ||
| } | ||
|
|
||
| reply := new(dns.Msg).SetRcode(query, rcode) | ||
| if rcode == dns.RcodeSuccess { | ||
| reply.Answer = append(reply.Answer, &dns.A{ | ||
| Hdr: dns.RR_Header{ | ||
| Name: query.Question[0].Name, | ||
| Rrtype: dns.TypeA, | ||
| Class: dns.ClassINET, | ||
| Ttl: 60, | ||
| }, | ||
| A: net.IPv4(127, 0, 0, 1), | ||
| }) | ||
| } | ||
| if err := w.WriteMsg(reply); err != nil { | ||
| t.Errorf("failed to send reply: %s", err) | ||
| } | ||
| }), | ||
| } | ||
|
|
||
| serveErr := make(chan error, 1) | ||
| go func() { serveErr <- server.ActivateAndServe() }() | ||
| select { | ||
| case <-started: | ||
| case err := <-serveErr: | ||
| t.Fatalf("failed to start test DNS server: %s", err) | ||
| } | ||
| t.Cleanup(func() { | ||
| if err := server.Shutdown(); err != nil { | ||
| t.Errorf("failed to stop test DNS server: %s", err) | ||
| } | ||
| }) | ||
|
|
||
| return addr, queries | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: safing/portmaster
Length of output: 7074
🏁 Script executed:
Repository: safing/portmaster
Length of output: 8661
🏁 Script executed:
Repository: safing/portmaster
Length of output: 14212
🏁 Script executed:
Repository: safing/portmaster
Length of output: 3444
Retry failing resolvers after a zero-query pass.
skipFailingis computed once. If a concurrent resolution marks the only initially healthy resolver as failing before this query reaches it, every resolver can be skipped.resolveAndCachethen returns an error matchingErrNotFoundwithout sending a query. The nameserver maps that error to NXDOMAIN.If the first pass sends no query, retry failing resolvers that are not unavailable link-local resolvers in configured order before returning. Reuse the existing query and error handling.
🤖 Prompt for AI Agents