• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17 
18 #define LOG_TAG "resolv_integration_test"
19 
20 #include <android-base/logging.h>
21 #include <android-base/parseint.h>
22 #include <android-base/properties.h>
23 #include <android-base/stringprintf.h>
24 #include <android-base/unique_fd.h>
25 #include <android/multinetwork.h>  // ResNsendFlags
26 #include <arpa/inet.h>
27 #include <arpa/nameser.h>
28 #include <binder/ProcessState.h>
29 #include <bpf/BpfUtils.h>
30 #include <cutils/sockets.h>
31 #include <gmock/gmock-matchers.h>
32 #include <gtest/gtest.h>
33 #include <netdb.h>
34 #include <netdutils/InternetAddresses.h>
35 #include <netdutils/NetworkConstants.h>  // SHA256_SIZE
36 #include <netdutils/ResponseCode.h>
37 #include <netdutils/Slice.h>
38 #include <netdutils/SocketOption.h>
39 #include <netdutils/Stopwatch.h>
40 #include <netinet/in.h>
41 #include <poll.h> /* poll */
42 #include <private/android_filesystem_config.h>
43 #include <resolv.h>
44 #include <stdarg.h>
45 #include <stdlib.h>
46 #include <sys/socket.h>
47 #include <sys/un.h>
48 #include <unistd.h>
49 
50 #include <algorithm>
51 #include <chrono>
52 #include <iterator>
53 #include <numeric>
54 #include <thread>
55 
56 #include <DnsProxydProtocol.h>  // NETID_USE_LOCAL_NAMESERVERS
57 #include <aidl/android/net/IDnsResolver.h>
58 #include <android/binder_manager.h>
59 #include <android/binder_process.h>
60 #include "NetdClient.h"
61 #include "ResolverStats.h"
62 #include "netid_client.h"  // NETID_UNSET
63 #include "params.h"        // MAXNS
64 #include "test_utils.h"
65 #include "tests/dns_metrics_listener/dns_metrics_listener.h"
66 #include "tests/dns_responder/dns_responder.h"
67 #include "tests/dns_responder/dns_responder_client_ndk.h"
68 #include "tests/dns_responder/dns_tls_certificate.h"
69 #include "tests/dns_responder/dns_tls_frontend.h"
70 #include "tests/resolv_test_utils.h"
71 
72 // Valid VPN netId range is 100 ~ 65535
73 constexpr int TEST_VPN_NETID = 65502;
74 constexpr int MAXPACKET = (8 * 1024);
75 
76 // Semi-public Bionic hook used by the NDK (frameworks/base/native/android/net.c)
77 // Tested here for convenience.
78 extern "C" int android_getaddrinfofornet(const char* hostname, const char* servname,
79                                          const addrinfo* hints, unsigned netid, unsigned mark,
80                                          struct addrinfo** result);
81 
82 using namespace std::chrono_literals;
83 
84 using aidl::android::net::IDnsResolver;
85 using aidl::android::net::INetd;
86 using aidl::android::net::ResolverParamsParcel;
87 using android::base::ParseInt;
88 using android::base::StringPrintf;
89 using android::base::unique_fd;
90 using android::net::ResolverStats;
91 using android::net::metrics::DnsMetricsListener;
92 using android::netdutils::enableSockopt;
93 using android::netdutils::makeSlice;
94 using android::netdutils::ResponseCode;
95 using android::netdutils::ScopedAddrinfo;
96 using android::netdutils::Stopwatch;
97 using android::netdutils::toHex;
98 
99 // TODO: move into libnetdutils?
100 namespace {
101 
safe_getaddrinfo(const char * node,const char * service,const struct addrinfo * hints)102 ScopedAddrinfo safe_getaddrinfo(const char* node, const char* service,
103                                 const struct addrinfo* hints) {
104     addrinfo* result = nullptr;
105     if (getaddrinfo(node, service, hints, &result) != 0) {
106         result = nullptr;  // Should already be the case, but...
107     }
108     return ScopedAddrinfo(result);
109 }
110 
safe_getaddrinfo_time_taken(const char * node,const char * service,const addrinfo & hints)111 std::pair<ScopedAddrinfo, int> safe_getaddrinfo_time_taken(const char* node, const char* service,
112                                                            const addrinfo& hints) {
113     Stopwatch s;
114     ScopedAddrinfo result = safe_getaddrinfo(node, service, &hints);
115     return {std::move(result), s.timeTakenUs() / 1000};
116 }
117 
118 struct NameserverStats {
119     NameserverStats() = delete;
NameserverStats__anonaf7621960111::NameserverStats120     NameserverStats(const std::string server) : server(server) {}
setSuccesses__anonaf7621960111::NameserverStats121     NameserverStats& setSuccesses(int val) {
122         successes = val;
123         return *this;
124     }
setErrors__anonaf7621960111::NameserverStats125     NameserverStats& setErrors(int val) {
126         errors = val;
127         return *this;
128     }
setTimeouts__anonaf7621960111::NameserverStats129     NameserverStats& setTimeouts(int val) {
130         timeouts = val;
131         return *this;
132     }
setInternalErrors__anonaf7621960111::NameserverStats133     NameserverStats& setInternalErrors(int val) {
134         internal_errors = val;
135         return *this;
136     }
137 
138     const std::string server;
139     int successes = 0;
140     int errors = 0;
141     int timeouts = 0;
142     int internal_errors = 0;
143 };
144 
145 }  // namespace
146 
147 class ResolverTest : public ::testing::Test {
148   public:
SetUpTestSuite()149     static void SetUpTestSuite() {
150         // Get binder service.
151         // Note that |mDnsClient| is not used for getting binder service in this static function.
152         // The reason is that wants to keep |mDnsClient| as a non-static data member. |mDnsClient|
153         // which sets up device network configuration could be independent from every test.
154         // TODO: Perhaps add a static function in resolv_test_binder_utils.{cpp,h} to get binder
155         // service.
156 
157         AIBinder* binder = AServiceManager_getService("dnsresolver");
158         ndk::SpAIBinder resolvBinder = ndk::SpAIBinder(binder);
159         auto resolvService = aidl::android::net::IDnsResolver::fromBinder(resolvBinder);
160         ASSERT_NE(nullptr, resolvService.get());
161 
162         // Subscribe the death recipient to the service IDnsResolver for detecting Netd death.
163         // GTEST assertion macros are not invoked for generating a test failure in the death
164         // recipient because the macros can't indicate failed test if Netd died between tests.
165         // Moreover, continuing testing may have no meaningful after Netd death. Therefore, the
166         // death recipient aborts process by GTEST_LOG_(FATAL) once Netd died.
167         sResolvDeathRecipient = AIBinder_DeathRecipient_new([](void*) {
168             constexpr char errorMessage[] = "Netd died";
169             LOG(ERROR) << errorMessage;
170             GTEST_LOG_(FATAL) << errorMessage;
171         });
172         ASSERT_EQ(STATUS_OK, AIBinder_linkToDeath(binder, sResolvDeathRecipient, nullptr));
173 
174         // Subscribe the DNS listener for verifying DNS metrics event contents.
175         sDnsMetricsListener = ndk::SharedRefBase::make<DnsMetricsListener>(
176                 TEST_NETID /*monitor specific network*/);
177         ASSERT_TRUE(resolvService->registerEventListener(sDnsMetricsListener).isOk());
178 
179         // Start the binder thread pool for listening DNS metrics events and receiving death
180         // recipient.
181         ABinderProcess_startThreadPool();
182     }
TearDownTestSuite()183     static void TearDownTestSuite() { AIBinder_DeathRecipient_delete(sResolvDeathRecipient); }
184 
185   protected:
SetUp()186     void SetUp() {
187         mDnsClient.SetUp();
188         sDnsMetricsListener->reset();
189     }
190 
TearDown()191     void TearDown() {
192         // Ensure the dump works at the end of each test.
193         DumpResolverService();
194 
195         mDnsClient.TearDown();
196     }
197 
resetNetwork()198     void resetNetwork() {
199         mDnsClient.TearDown();
200         mDnsClient.SetupOemNetwork();
201     }
202 
StartDns(test::DNSResponder & dns,const std::vector<DnsRecord> & records)203     void StartDns(test::DNSResponder& dns, const std::vector<DnsRecord>& records) {
204         for (const auto& r : records) {
205             dns.addMapping(r.host_name, r.type, r.addr);
206         }
207 
208         ASSERT_TRUE(dns.startServer());
209         dns.clearQueries();
210     }
211 
DumpResolverService()212     void DumpResolverService() {
213         unique_fd fd(open("/dev/null", O_WRONLY));
214         EXPECT_EQ(mDnsClient.resolvService()->dump(fd, nullptr, 0), 0);
215 
216         const char* querylogCmd[] = {"querylog"};  // Keep it sync with DnsQueryLog::DUMP_KEYWORD.
217         EXPECT_EQ(mDnsClient.resolvService()->dump(fd, querylogCmd, std::size(querylogCmd)), 0);
218     }
219 
WaitForNat64Prefix(ExpectNat64PrefixStatus status,std::chrono::milliseconds timeout=std::chrono::milliseconds (1000))220     bool WaitForNat64Prefix(ExpectNat64PrefixStatus status,
221                             std::chrono::milliseconds timeout = std::chrono::milliseconds(1000)) {
222         return sDnsMetricsListener->waitForNat64Prefix(status, timeout);
223     }
224 
WaitForPrivateDnsValidation(std::string serverAddr,bool validated)225     bool WaitForPrivateDnsValidation(std::string serverAddr, bool validated) {
226         return sDnsMetricsListener->waitForPrivateDnsValidation(serverAddr, validated);
227     }
228 
hasUncaughtPrivateDnsValidation(const std::string & serverAddr)229     bool hasUncaughtPrivateDnsValidation(const std::string& serverAddr) {
230         return sDnsMetricsListener->findValidationRecord(serverAddr);
231     }
232 
expectStatsFromGetResolverInfo(const std::vector<NameserverStats> & nameserversStats)233     bool expectStatsFromGetResolverInfo(const std::vector<NameserverStats>& nameserversStats) {
234         std::vector<std::string> res_servers;
235         std::vector<std::string> res_domains;
236         std::vector<std::string> res_tls_servers;
237         res_params res_params;
238         std::vector<ResolverStats> res_stats;
239         int wait_for_pending_req_timeout_count;
240 
241         if (!DnsResponderClient::GetResolverInfo(mDnsClient.resolvService(), TEST_NETID,
242                                                  &res_servers, &res_domains, &res_tls_servers,
243                                                  &res_params, &res_stats,
244                                                  &wait_for_pending_req_timeout_count)) {
245             ADD_FAILURE() << "GetResolverInfo failed";
246             return false;
247         }
248 
249         if (res_servers.size() != res_stats.size()) {
250             ADD_FAILURE() << fmt::format("res_servers.size() != res_stats.size(): {} != {}",
251                                          res_servers.size(), res_stats.size());
252             return false;
253         }
254         if (res_servers.size() != nameserversStats.size()) {
255             ADD_FAILURE() << fmt::format("res_servers.size() != nameserversStats.size(): {} != {}",
256                                          res_servers.size(), nameserversStats.size());
257             return false;
258         }
259 
260         for (const auto& stats : nameserversStats) {
261             SCOPED_TRACE(stats.server);
262             const auto it = std::find(res_servers.begin(), res_servers.end(), stats.server);
263             if (it == res_servers.end()) {
264                 ADD_FAILURE() << fmt::format("nameserver {} not found in the list {{{}}}",
265                                              stats.server, fmt::join(res_servers, ", "));
266                 return false;
267             }
268             const int index = std::distance(res_servers.begin(), it);
269 
270             // The check excludes rtt_avg, last_sample_time, and usable since they will be obsolete
271             // after |res_stats| is retrieved from NetConfig.dnsStats rather than NetConfig.nsstats.
272             EXPECT_EQ(res_stats[index].successes, stats.successes);
273             EXPECT_EQ(res_stats[index].errors, stats.errors);
274             EXPECT_EQ(res_stats[index].timeouts, stats.timeouts);
275             EXPECT_EQ(res_stats[index].internal_errors, stats.internal_errors);
276         }
277 
278         return true;
279     }
280 
281     // Since there's no way to terminate private DNS validation threads at any time. Tests that
282     // focus on the results of private DNS validation can interfere with each other if they use the
283     // same IP address for test servers. getUniqueIPv4Address() is a workaround to reduce the
284     // possibility of tests being flaky. A feasible solution is to forbid the validation threads,
285     // which are considered as outdated (e.g. switch the resolver to private DNS OFF mode), updating
286     // the result to the PrivateDnsConfiguration instance.
getUniqueIPv4Address()287     static std::string getUniqueIPv4Address() {
288         static int counter = 0;
289         return fmt::format("127.0.100.{}", (++counter & 0xff));
290     }
291 
292     DnsResponderClient mDnsClient;
293 
294     // Use a shared static DNS listener for all tests to avoid registering lots of listeners
295     // which may be released late until process terminated. Currently, registered DNS listener
296     // is removed by binder death notification which is fired when the process hosting an
297     // IBinder has gone away. If every test in ResolverTest registers its DNS listener, Netd
298     // may temporarily hold lots of dead listeners until the unit test process terminates.
299     // TODO: Perhaps add an unregistering listener binder call or fork a listener process which
300     // could be terminated earlier.
301     static std::shared_ptr<DnsMetricsListener>
302             sDnsMetricsListener;  // Initialized in SetUpTestSuite.
303 
304     // Use a shared static death recipient to monitor the service death. The static death
305     // recipient could monitor the death not only during the test but also between tests.
306     static AIBinder_DeathRecipient* sResolvDeathRecipient;  // Initialized in SetUpTestSuite.
307 };
308 
309 // Initialize static member of class.
310 std::shared_ptr<DnsMetricsListener> ResolverTest::sDnsMetricsListener;
311 AIBinder_DeathRecipient* ResolverTest::sResolvDeathRecipient;
312 
TEST_F(ResolverTest,GetHostByName)313 TEST_F(ResolverTest, GetHostByName) {
314     constexpr char nonexistent_host_name[] = "nonexistent.example.com.";
315 
316     test::DNSResponder dns;
317     StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.3"}});
318     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
319 
320     const hostent* result;
321     result = gethostbyname("nonexistent");
322     EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, nonexistent_host_name));
323     ASSERT_TRUE(result == nullptr);
324     ASSERT_EQ(HOST_NOT_FOUND, h_errno);
325 
326     dns.clearQueries();
327     result = gethostbyname("hello");
328     EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, kHelloExampleCom));
329     ASSERT_FALSE(result == nullptr);
330     ASSERT_EQ(4, result->h_length);
331     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
332     EXPECT_EQ("1.2.3.3", ToString(result));
333     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
334 }
335 
TEST_F(ResolverTest,GetHostByName_cnames)336 TEST_F(ResolverTest, GetHostByName_cnames) {
337     constexpr char host_name[] = "host.example.com.";
338     size_t cnamecount = 0;
339     test::DNSResponder dns;
340 
341     const std::vector<DnsRecord> records = {
342             {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
343             {"a.example.com.", ns_type::ns_t_cname, "b.example.com."},
344             {"b.example.com.", ns_type::ns_t_cname, "c.example.com."},
345             {"c.example.com.", ns_type::ns_t_cname, "d.example.com."},
346             {"d.example.com.", ns_type::ns_t_cname, "e.example.com."},
347             {"e.example.com.", ns_type::ns_t_cname, host_name},
348             {host_name, ns_type::ns_t_a, "1.2.3.3"},
349             {host_name, ns_type::ns_t_aaaa, "2001:db8::42"},
350     };
351     StartDns(dns, records);
352     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
353 
354     // using gethostbyname2() to resolve ipv4 hello.example.com. to 1.2.3.3
355     // Ensure the v4 address and cnames are correct
356     const hostent* result;
357     result = gethostbyname2("hello", AF_INET);
358     ASSERT_FALSE(result == nullptr);
359 
360     for (int i = 0; result != nullptr && result->h_aliases[i] != nullptr; i++) {
361         std::string domain_name = records[i].host_name.substr(0, records[i].host_name.size() - 1);
362         EXPECT_EQ(result->h_aliases[i], domain_name);
363         cnamecount++;
364     }
365     // The size of "Non-cname type" record in DNS records is 2
366     ASSERT_EQ(cnamecount, records.size() - 2);
367     ASSERT_EQ(4, result->h_length);
368     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
369     EXPECT_EQ("1.2.3.3", ToString(result));
370     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
371     EXPECT_EQ(1U, dns.queries().size()) << dns.dumpQueries();
372 
373     // using gethostbyname2() to resolve ipv6 hello.example.com. to 2001:db8::42
374     // Ensure the v6 address and cnames are correct
375     cnamecount = 0;
376     dns.clearQueries();
377     result = gethostbyname2("hello", AF_INET6);
378     for (unsigned i = 0; result != nullptr && result->h_aliases[i] != nullptr; i++) {
379         std::string domain_name = records[i].host_name.substr(0, records[i].host_name.size() - 1);
380         EXPECT_EQ(result->h_aliases[i], domain_name);
381         cnamecount++;
382     }
383     // The size of "Non-cname type" DNS record in records is 2
384     ASSERT_EQ(cnamecount, records.size() - 2);
385     ASSERT_FALSE(result == nullptr);
386     ASSERT_EQ(16, result->h_length);
387     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
388     EXPECT_EQ("2001:db8::42", ToString(result));
389     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
390 }
391 
TEST_F(ResolverTest,GetHostByName_cnamesInfiniteLoop)392 TEST_F(ResolverTest, GetHostByName_cnamesInfiniteLoop) {
393     test::DNSResponder dns;
394     const std::vector<DnsRecord> records = {
395             {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
396             {"a.example.com.", ns_type::ns_t_cname, kHelloExampleCom},
397     };
398     StartDns(dns, records);
399     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
400 
401     const hostent* result;
402     result = gethostbyname2("hello", AF_INET);
403     ASSERT_TRUE(result == nullptr);
404 
405     dns.clearQueries();
406     result = gethostbyname2("hello", AF_INET6);
407     ASSERT_TRUE(result == nullptr);
408 }
409 
TEST_F(ResolverTest,GetHostByName_localhost)410 TEST_F(ResolverTest, GetHostByName_localhost) {
411     constexpr char name_camelcase[] = "LocalHost";
412     constexpr char name_ip6_dot[] = "ip6-localhost.";
413     constexpr char name_ip6_fqdn[] = "ip6-localhost.example.com.";
414 
415     // Add a dummy nameserver which shouldn't receive any queries
416     test::DNSResponder dns;
417     StartDns(dns, {});
418     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
419 
420     // Expect no DNS queries; localhost is resolved via /etc/hosts
421     const hostent* result = gethostbyname(kLocalHost);
422     EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
423     ASSERT_FALSE(result == nullptr);
424     ASSERT_EQ(4, result->h_length);
425     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
426     EXPECT_EQ(kLocalHostAddr, ToString(result));
427     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
428 
429     // Ensure the hosts file resolver ignores case of hostnames
430     result = gethostbyname(name_camelcase);
431     EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
432     ASSERT_FALSE(result == nullptr);
433     ASSERT_EQ(4, result->h_length);
434     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
435     EXPECT_EQ(kLocalHostAddr, ToString(result));
436     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
437 
438     // The hosts file also contains ip6-localhost, but gethostbyname() won't
439     // return it. This would be easy to
440     // change, but there's no point in changing the legacy behavior; new code
441     // should be calling getaddrinfo() anyway.
442     // So we check the legacy behavior, which results in amusing A-record
443     // lookups for ip6-localhost, with and without search domains appended.
444     dns.clearQueries();
445     result = gethostbyname(kIp6LocalHost);
446     EXPECT_EQ(2U, dns.queries().size()) << dns.dumpQueries();
447     EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, name_ip6_dot)) << dns.dumpQueries();
448     EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, name_ip6_fqdn)) << dns.dumpQueries();
449     ASSERT_TRUE(result == nullptr);
450 
451     // Finally, use gethostbyname2() to resolve ip6-localhost to ::1 from
452     // the hosts file.
453     dns.clearQueries();
454     result = gethostbyname2(kIp6LocalHost, AF_INET6);
455     EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
456     ASSERT_FALSE(result == nullptr);
457     ASSERT_EQ(16, result->h_length);
458     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
459     EXPECT_EQ(kIp6LocalHostAddr, ToString(result));
460     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
461 }
462 
TEST_F(ResolverTest,GetHostByName_numeric)463 TEST_F(ResolverTest, GetHostByName_numeric) {
464     // Add a dummy nameserver which shouldn't receive any queries
465     test::DNSResponder dns;
466     StartDns(dns, {});
467     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
468 
469     // Numeric v4 address: expect no DNS queries
470     constexpr char numeric_v4[] = "192.168.0.1";
471     const hostent* result = gethostbyname(numeric_v4);
472     EXPECT_EQ(0U, dns.queries().size());
473     ASSERT_FALSE(result == nullptr);
474     ASSERT_EQ(4, result->h_length);  // v4
475     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
476     EXPECT_EQ(numeric_v4, ToString(result));
477     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
478 
479     // gethostbyname() recognizes a v6 address, and fails with no DNS queries
480     constexpr char numeric_v6[] = "2001:db8::42";
481     dns.clearQueries();
482     result = gethostbyname(numeric_v6);
483     EXPECT_EQ(0U, dns.queries().size());
484     EXPECT_TRUE(result == nullptr);
485 
486     // Numeric v6 address with gethostbyname2(): succeeds with no DNS queries
487     dns.clearQueries();
488     result = gethostbyname2(numeric_v6, AF_INET6);
489     EXPECT_EQ(0U, dns.queries().size());
490     ASSERT_FALSE(result == nullptr);
491     ASSERT_EQ(16, result->h_length);  // v6
492     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
493     EXPECT_EQ(numeric_v6, ToString(result));
494     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
495 
496     // Numeric v6 address with scope work with getaddrinfo(),
497     // but gethostbyname2() does not understand them; it issues two dns
498     // queries, then fails. This hardly ever happens, there's no point
499     // in fixing this. This test simply verifies the current (bogus)
500     // behavior to avoid further regressions (like crashes, or leaks).
501     constexpr char numeric_v6_scope[] = "fe80::1%lo";
502     dns.clearQueries();
503     result = gethostbyname2(numeric_v6_scope, AF_INET6);
504     EXPECT_EQ(2U, dns.queries().size());  // OUCH!
505     ASSERT_TRUE(result == nullptr);
506 }
507 
TEST_F(ResolverTest,BinderSerialization)508 TEST_F(ResolverTest, BinderSerialization) {
509     std::vector<int> params_offsets = {
510             IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY,
511             IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD,
512             IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES,
513             IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES,
514             IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC,
515             IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT,
516     };
517     const int size = static_cast<int>(params_offsets.size());
518     EXPECT_EQ(size, IDnsResolver::RESOLVER_PARAMS_COUNT);
519     std::sort(params_offsets.begin(), params_offsets.end());
520     for (int i = 0; i < size; ++i) {
521         EXPECT_EQ(params_offsets[i], i);
522     }
523 }
524 
TEST_F(ResolverTest,GetHostByName_Binder)525 TEST_F(ResolverTest, GetHostByName_Binder) {
526     std::vector<std::string> domains = {"example.com"};
527     std::vector<std::unique_ptr<test::DNSResponder>> dns;
528     std::vector<std::string> servers;
529     std::vector<DnsResponderClient::Mapping> mappings;
530     ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(1, domains, &mappings));
531     ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(4, mappings, &dns, &servers));
532     ASSERT_EQ(1U, mappings.size());
533     const DnsResponderClient::Mapping& mapping = mappings[0];
534 
535     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains, kDefaultParams));
536 
537     const hostent* result = gethostbyname(mapping.host.c_str());
538     const size_t total_queries =
539             std::accumulate(dns.begin(), dns.end(), 0, [&mapping](size_t total, auto& d) {
540                 return total + GetNumQueriesForType(*d, ns_type::ns_t_a, mapping.entry.c_str());
541             });
542 
543     EXPECT_LE(1U, total_queries);
544     ASSERT_FALSE(result == nullptr);
545     ASSERT_EQ(4, result->h_length);
546     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
547     EXPECT_EQ(mapping.ip4, ToString(result));
548     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
549 
550     std::vector<std::string> res_servers;
551     std::vector<std::string> res_domains;
552     std::vector<std::string> res_tls_servers;
553     res_params res_params;
554     std::vector<ResolverStats> res_stats;
555     int wait_for_pending_req_timeout_count;
556     ASSERT_TRUE(DnsResponderClient::GetResolverInfo(
557             mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains, &res_tls_servers,
558             &res_params, &res_stats, &wait_for_pending_req_timeout_count));
559     EXPECT_EQ(servers.size(), res_servers.size());
560     EXPECT_EQ(domains.size(), res_domains.size());
561     EXPECT_EQ(0U, res_tls_servers.size());
562     ASSERT_EQ(static_cast<size_t>(IDnsResolver::RESOLVER_PARAMS_COUNT), kDefaultParams.size());
563     EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY],
564               res_params.sample_validity);
565     EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD],
566               res_params.success_threshold);
567     EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES], res_params.min_samples);
568     EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES], res_params.max_samples);
569     EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
570               res_params.base_timeout_msec);
571     EXPECT_EQ(servers.size(), res_stats.size());
572 
573     EXPECT_THAT(res_servers, testing::UnorderedElementsAreArray(servers));
574     EXPECT_THAT(res_domains, testing::UnorderedElementsAreArray(domains));
575 }
576 
TEST_F(ResolverTest,GetAddrInfo)577 TEST_F(ResolverTest, GetAddrInfo) {
578     constexpr char listen_addr[] = "127.0.0.4";
579     constexpr char listen_addr2[] = "127.0.0.5";
580     constexpr char host_name[] = "howdy.example.com.";
581 
582     const std::vector<DnsRecord> records = {
583             {host_name, ns_type::ns_t_a, "1.2.3.4"},
584             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
585     };
586     test::DNSResponder dns(listen_addr);
587     test::DNSResponder dns2(listen_addr2);
588     StartDns(dns, records);
589     StartDns(dns2, records);
590 
591     ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr}));
592     dns.clearQueries();
593     dns2.clearQueries();
594 
595     ScopedAddrinfo result = safe_getaddrinfo("howdy", nullptr, nullptr);
596     EXPECT_TRUE(result != nullptr);
597     size_t found = GetNumQueries(dns, host_name);
598     EXPECT_LE(1U, found);
599     // Could be A or AAAA
600     std::string result_str = ToString(result);
601     EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
602             << ", result_str='" << result_str << "'";
603 
604     // Verify that the name is cached.
605     size_t old_found = found;
606     result = safe_getaddrinfo("howdy", nullptr, nullptr);
607     EXPECT_TRUE(result != nullptr);
608     found = GetNumQueries(dns, host_name);
609     EXPECT_LE(1U, found);
610     EXPECT_EQ(old_found, found);
611     result_str = ToString(result);
612     EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4") << result_str;
613 
614     // Change the DNS resolver, ensure that queries are still cached.
615     ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr2}));
616     dns.clearQueries();
617     dns2.clearQueries();
618 
619     result = safe_getaddrinfo("howdy", nullptr, nullptr);
620     EXPECT_TRUE(result != nullptr);
621     found = GetNumQueries(dns, host_name);
622     size_t found2 = GetNumQueries(dns2, host_name);
623     EXPECT_EQ(0U, found);
624     EXPECT_LE(0U, found2);
625 
626     // Could be A or AAAA
627     result_str = ToString(result);
628     EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
629             << ", result_str='" << result_str << "'";
630 }
631 
TEST_F(ResolverTest,GetAddrInfoV4)632 TEST_F(ResolverTest, GetAddrInfoV4) {
633     test::DNSResponder dns;
634     StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.5"}});
635     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
636 
637     const addrinfo hints = {.ai_family = AF_INET};
638     ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
639     EXPECT_TRUE(result != nullptr);
640     EXPECT_EQ(1U, GetNumQueries(dns, kHelloExampleCom));
641     EXPECT_EQ("1.2.3.5", ToString(result));
642 }
643 
TEST_F(ResolverTest,GetAddrInfo_localhost)644 TEST_F(ResolverTest, GetAddrInfo_localhost) {
645     // Add a dummy nameserver which shouldn't receive any queries
646     test::DNSResponder dns;
647     StartDns(dns, {});
648     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
649 
650     ScopedAddrinfo result = safe_getaddrinfo(kLocalHost, nullptr, nullptr);
651     EXPECT_TRUE(result != nullptr);
652     // Expect no DNS queries; localhost is resolved via /etc/hosts
653     EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
654     EXPECT_EQ(kLocalHostAddr, ToString(result));
655 
656     result = safe_getaddrinfo(kIp6LocalHost, nullptr, nullptr);
657     EXPECT_TRUE(result != nullptr);
658     // Expect no DNS queries; ip6-localhost is resolved via /etc/hosts
659     EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
660     EXPECT_EQ(kIp6LocalHostAddr, ToString(result));
661 }
662 
TEST_F(ResolverTest,GetAddrInfo_InvalidSocketType)663 TEST_F(ResolverTest, GetAddrInfo_InvalidSocketType) {
664     test::DNSResponder dns;
665     StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.5"}});
666     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
667 
668     // TODO: Test other invalid socket types.
669     const addrinfo hints = {
670             .ai_family = AF_UNSPEC,
671             .ai_socktype = SOCK_PACKET,
672     };
673     addrinfo* result = nullptr;
674     // This is a valid hint, but the query won't be sent because the socket type is
675     // not supported.
676     EXPECT_EQ(EAI_NODATA, getaddrinfo("hello", nullptr, &hints, &result));
677     ScopedAddrinfo result_cleanup(result);
678     EXPECT_EQ(nullptr, result);
679 }
680 
681 // Verify if the resolver correctly handle multiple queries simultaneously
682 // step 1: set dns server#1 into deferred responding mode.
683 // step 2: thread#1 query "hello.example.com." --> resolver send query to server#1.
684 // step 3: thread#2 query "hello.example.com." --> resolver hold the request and wait for
685 //           response of previous pending query sent by thread#1.
686 // step 4: thread#3 query "konbanha.example.com." --> resolver send query to server#3. Server
687 //           respond to resolver immediately.
688 // step 5: check if server#1 get 1 query by thread#1, server#2 get 0 query, server#3 get 1 query.
689 // step 6: resume dns server#1 to respond dns query in step#2.
690 // step 7: thread#1 and #2 should get returned from DNS query after step#6. Also, check the
691 //           number of queries in server#2 is 0 to ensure thread#2 does not wake up unexpectedly
692 //           before signaled by thread#1.
TEST_F(ResolverTest,GetAddrInfoV4_deferred_resp)693 TEST_F(ResolverTest, GetAddrInfoV4_deferred_resp) {
694     const char* listen_addr1 = "127.0.0.9";
695     const char* listen_addr2 = "127.0.0.10";
696     const char* listen_addr3 = "127.0.0.11";
697     const char* listen_srv = "53";
698     const char* host_name_deferred = "hello.example.com.";
699     const char* host_name_normal = "konbanha.example.com.";
700     test::DNSResponder dns1(listen_addr1, listen_srv, ns_rcode::ns_r_servfail);
701     test::DNSResponder dns2(listen_addr2, listen_srv, ns_rcode::ns_r_servfail);
702     test::DNSResponder dns3(listen_addr3, listen_srv, ns_rcode::ns_r_servfail);
703     dns1.addMapping(host_name_deferred, ns_type::ns_t_a, "1.2.3.4");
704     dns2.addMapping(host_name_deferred, ns_type::ns_t_a, "1.2.3.4");
705     dns3.addMapping(host_name_normal, ns_type::ns_t_a, "1.2.3.5");
706     ASSERT_TRUE(dns1.startServer());
707     ASSERT_TRUE(dns2.startServer());
708     ASSERT_TRUE(dns3.startServer());
709     const std::vector<std::string> servers_for_t1 = {listen_addr1};
710     const std::vector<std::string> servers_for_t2 = {listen_addr2};
711     const std::vector<std::string> servers_for_t3 = {listen_addr3};
712     addrinfo hints = {.ai_family = AF_INET};
713     const std::vector<int> params = {300, 25, 8, 8, 5000};
714     bool t3_task_done = false;
715 
716     dns1.setDeferredResp(true);
717     std::thread t1([&, this]() {
718         ASSERT_TRUE(
719                 mDnsClient.SetResolversForNetwork(servers_for_t1, kDefaultSearchDomains, params));
720         ScopedAddrinfo result = safe_getaddrinfo(host_name_deferred, nullptr, &hints);
721         // t3's dns query should got returned first
722         EXPECT_TRUE(t3_task_done);
723         EXPECT_EQ(1U, GetNumQueries(dns1, host_name_deferred));
724         EXPECT_TRUE(result != nullptr);
725         EXPECT_EQ("1.2.3.4", ToString(result));
726     });
727 
728     // ensuring t1 and t2 handler functions are processed in order
729     usleep(100 * 1000);
730     std::thread t2([&, this]() {
731         ASSERT_TRUE(
732                 mDnsClient.SetResolversForNetwork(servers_for_t2, kDefaultSearchDomains, params));
733         ScopedAddrinfo result = safe_getaddrinfo(host_name_deferred, nullptr, &hints);
734         EXPECT_TRUE(t3_task_done);
735         EXPECT_EQ(0U, GetNumQueries(dns2, host_name_deferred));
736         EXPECT_TRUE(result != nullptr);
737         EXPECT_EQ("1.2.3.4", ToString(result));
738 
739         std::vector<std::string> res_servers;
740         std::vector<std::string> res_domains;
741         std::vector<std::string> res_tls_servers;
742         res_params res_params;
743         std::vector<ResolverStats> res_stats;
744         int wait_for_pending_req_timeout_count;
745         ASSERT_TRUE(DnsResponderClient::GetResolverInfo(
746                 mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
747                 &res_tls_servers, &res_params, &res_stats, &wait_for_pending_req_timeout_count));
748         EXPECT_EQ(0, wait_for_pending_req_timeout_count);
749     });
750 
751     // ensuring t2 and t3 handler functions are processed in order
752     usleep(100 * 1000);
753     std::thread t3([&, this]() {
754         ASSERT_TRUE(
755                 mDnsClient.SetResolversForNetwork(servers_for_t3, kDefaultSearchDomains, params));
756         ScopedAddrinfo result = safe_getaddrinfo(host_name_normal, nullptr, &hints);
757         EXPECT_EQ(1U, GetNumQueries(dns1, host_name_deferred));
758         EXPECT_EQ(0U, GetNumQueries(dns2, host_name_deferred));
759         EXPECT_EQ(1U, GetNumQueries(dns3, host_name_normal));
760         EXPECT_TRUE(result != nullptr);
761         EXPECT_EQ("1.2.3.5", ToString(result));
762 
763         t3_task_done = true;
764         dns1.setDeferredResp(false);
765     });
766     t3.join();
767     t1.join();
768     t2.join();
769 }
770 
TEST_F(ResolverTest,GetAddrInfo_cnames)771 TEST_F(ResolverTest, GetAddrInfo_cnames) {
772     constexpr char host_name[] = "host.example.com.";
773     test::DNSResponder dns;
774     const std::vector<DnsRecord> records = {
775             {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
776             {"a.example.com.", ns_type::ns_t_cname, "b.example.com."},
777             {"b.example.com.", ns_type::ns_t_cname, "c.example.com."},
778             {"c.example.com.", ns_type::ns_t_cname, "d.example.com."},
779             {"d.example.com.", ns_type::ns_t_cname, "e.example.com."},
780             {"e.example.com.", ns_type::ns_t_cname, host_name},
781             {host_name, ns_type::ns_t_a, "1.2.3.3"},
782             {host_name, ns_type::ns_t_aaaa, "2001:db8::42"},
783     };
784     StartDns(dns, records);
785     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
786 
787     addrinfo hints = {.ai_family = AF_INET};
788     ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
789     EXPECT_TRUE(result != nullptr);
790     EXPECT_EQ("1.2.3.3", ToString(result));
791 
792     dns.clearQueries();
793     hints = {.ai_family = AF_INET6};
794     result = safe_getaddrinfo("hello", nullptr, &hints);
795     EXPECT_TRUE(result != nullptr);
796     EXPECT_EQ("2001:db8::42", ToString(result));
797 }
798 
TEST_F(ResolverTest,GetAddrInfo_cnamesNoIpAddress)799 TEST_F(ResolverTest, GetAddrInfo_cnamesNoIpAddress) {
800     test::DNSResponder dns;
801     const std::vector<DnsRecord> records = {
802             {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
803     };
804     StartDns(dns, records);
805     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
806 
807     addrinfo hints = {.ai_family = AF_INET};
808     ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
809     EXPECT_TRUE(result == nullptr);
810 
811     dns.clearQueries();
812     hints = {.ai_family = AF_INET6};
813     result = safe_getaddrinfo("hello", nullptr, &hints);
814     EXPECT_TRUE(result == nullptr);
815 }
816 
TEST_F(ResolverTest,GetAddrInfo_cnamesIllegalRdata)817 TEST_F(ResolverTest, GetAddrInfo_cnamesIllegalRdata) {
818     test::DNSResponder dns;
819     const std::vector<DnsRecord> records = {
820             {kHelloExampleCom, ns_type::ns_t_cname, ".!#?"},
821     };
822     StartDns(dns, records);
823     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
824 
825     addrinfo hints = {.ai_family = AF_INET};
826     ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
827     EXPECT_TRUE(result == nullptr);
828 
829     dns.clearQueries();
830     hints = {.ai_family = AF_INET6};
831     result = safe_getaddrinfo("hello", nullptr, &hints);
832     EXPECT_TRUE(result == nullptr);
833 }
834 
TEST_F(ResolverTest,MultidomainResolution)835 TEST_F(ResolverTest, MultidomainResolution) {
836     constexpr char host_name[] = "nihao.example2.com.";
837     std::vector<std::string> searchDomains = {"example1.com", "example2.com", "example3.com"};
838 
839     test::DNSResponder dns("127.0.0.6");
840     StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.3"}});
841     ASSERT_TRUE(mDnsClient.SetResolversForNetwork({"127.0.0.6"}, searchDomains));
842 
843     const hostent* result = gethostbyname("nihao");
844 
845     EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
846     ASSERT_FALSE(result == nullptr);
847     ASSERT_EQ(4, result->h_length);
848     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
849     EXPECT_EQ("1.2.3.3", ToString(result));
850     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
851 }
852 
TEST_F(ResolverTest,GetAddrInfoV6_numeric)853 TEST_F(ResolverTest, GetAddrInfoV6_numeric) {
854     constexpr char host_name[] = "ohayou.example.com.";
855     constexpr char numeric_addr[] = "fe80::1%lo";
856 
857     test::DNSResponder dns;
858     dns.setResponseProbability(0.0);
859     StartDns(dns, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
860     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
861 
862     addrinfo hints = {.ai_family = AF_INET6};
863     ScopedAddrinfo result = safe_getaddrinfo(numeric_addr, nullptr, &hints);
864     EXPECT_TRUE(result != nullptr);
865     EXPECT_EQ(numeric_addr, ToString(result));
866     EXPECT_TRUE(dns.queries().empty());  // Ensure no DNS queries were sent out
867 
868     // Now try a non-numeric hostname query with the AI_NUMERICHOST flag set.
869     // We should fail without sending out a DNS query.
870     hints.ai_flags |= AI_NUMERICHOST;
871     result = safe_getaddrinfo(host_name, nullptr, &hints);
872     EXPECT_TRUE(result == nullptr);
873     EXPECT_TRUE(dns.queries().empty());  // Ensure no DNS queries were sent out
874 }
875 
TEST_F(ResolverTest,GetAddrInfoV6_failing)876 TEST_F(ResolverTest, GetAddrInfoV6_failing) {
877     constexpr char listen_addr0[] = "127.0.0.7";
878     constexpr char listen_addr1[] = "127.0.0.8";
879     const char* host_name = "ohayou.example.com.";
880 
881     test::DNSResponder dns0(listen_addr0);
882     test::DNSResponder dns1(listen_addr1);
883     dns0.setResponseProbability(0.0);
884     StartDns(dns0, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
885     StartDns(dns1, {{host_name, ns_type::ns_t_aaaa, "2001:db8::6"}});
886 
887     std::vector<std::string> servers = {listen_addr0, listen_addr1};
888     // <sample validity in s> <success threshold in percent> <min samples> <max samples>
889     int sample_count = 8;
890     const std::vector<int> params = {300, 25, sample_count, sample_count};
891     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, kDefaultSearchDomains, params));
892 
893     // Repeatedly perform resolutions for non-existing domains until MAXNSSAMPLES resolutions have
894     // reached the dns0, which is set to fail. No more requests should then arrive at that server
895     // for the next sample_lifetime seconds.
896     // TODO: This approach is implementation-dependent, change once metrics reporting is available.
897     const addrinfo hints = {.ai_family = AF_INET6};
898     for (int i = 0; i < sample_count; ++i) {
899         std::string domain = StringPrintf("nonexistent%d", i);
900         ScopedAddrinfo result = safe_getaddrinfo(domain.c_str(), nullptr, &hints);
901     }
902     // Due to 100% errors for all possible samples, the server should be ignored from now on and
903     // only the second one used for all following queries, until NSSAMPLE_VALIDITY is reached.
904     dns0.clearQueries();
905     dns1.clearQueries();
906     ScopedAddrinfo result = safe_getaddrinfo("ohayou", nullptr, &hints);
907     EXPECT_TRUE(result != nullptr);
908     EXPECT_EQ(0U, GetNumQueries(dns0, host_name));
909     EXPECT_EQ(1U, GetNumQueries(dns1, host_name));
910 }
911 
TEST_F(ResolverTest,GetAddrInfoV6_nonresponsive)912 TEST_F(ResolverTest, GetAddrInfoV6_nonresponsive) {
913     constexpr char listen_addr0[] = "127.0.0.7";
914     constexpr char listen_addr1[] = "127.0.0.8";
915     constexpr char listen_srv[] = "53";
916     constexpr char host_name1[] = "ohayou.example.com.";
917     constexpr char host_name2[] = "ciao.example.com.";
918     const std::vector<std::string> defaultSearchDomain = {"example.com"};
919     // The minimal timeout is 1000ms, so we can't decrease timeout
920     // So reduce retry count.
921     const std::vector<int> reduceRetryParams = {
922             300,      // sample validity in seconds
923             25,       // success threshod in percent
924             8,    8,  // {MIN,MAX}_SAMPLES
925             1000,     // BASE_TIMEOUT_MSEC
926             1,        // retry count
927     };
928     const std::vector<DnsRecord> records0 = {
929             {host_name1, ns_type::ns_t_aaaa, "2001:db8::5"},
930             {host_name2, ns_type::ns_t_aaaa, "2001:db8::5"},
931     };
932     const std::vector<DnsRecord> records1 = {
933             {host_name1, ns_type::ns_t_aaaa, "2001:db8::6"},
934             {host_name2, ns_type::ns_t_aaaa, "2001:db8::6"},
935     };
936 
937     // dns0 does not respond with 100% probability, while
938     // dns1 responds normally, at least initially.
939     test::DNSResponder dns0(listen_addr0, listen_srv, static_cast<ns_rcode>(-1));
940     test::DNSResponder dns1(listen_addr1, listen_srv, static_cast<ns_rcode>(-1));
941     dns0.setResponseProbability(0.0);
942     StartDns(dns0, records0);
943     StartDns(dns1, records1);
944     ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr0, listen_addr1}, defaultSearchDomain,
945                                                   reduceRetryParams));
946 
947     // Specify ai_socktype to make getaddrinfo will only query 1 time
948     const addrinfo hints = {.ai_family = AF_INET6, .ai_socktype = SOCK_STREAM};
949 
950     // dns0 will ignore the request, and we'll fallback to dns1 after the first
951     // retry.
952     ScopedAddrinfo result = safe_getaddrinfo(host_name1, nullptr, &hints);
953     EXPECT_TRUE(result != nullptr);
954     EXPECT_EQ(1U, GetNumQueries(dns0, host_name1));
955     EXPECT_EQ(1U, GetNumQueries(dns1, host_name1));
956 
957     // Now make dns1 also ignore 100% requests... The resolve should alternate
958     // queries between the nameservers and fail
959     dns1.setResponseProbability(0.0);
960     addrinfo* result2 = nullptr;
961     EXPECT_EQ(EAI_NODATA, getaddrinfo(host_name2, nullptr, &hints, &result2));
962     EXPECT_EQ(nullptr, result2);
963     EXPECT_EQ(1U, GetNumQueries(dns0, host_name2));
964     EXPECT_EQ(1U, GetNumQueries(dns1, host_name2));
965 }
966 
TEST_F(ResolverTest,GetAddrInfoV6_concurrent)967 TEST_F(ResolverTest, GetAddrInfoV6_concurrent) {
968     constexpr char listen_addr0[] = "127.0.0.9";
969     constexpr char listen_addr1[] = "127.0.0.10";
970     constexpr char listen_addr2[] = "127.0.0.11";
971     constexpr char host_name[] = "konbanha.example.com.";
972 
973     test::DNSResponder dns0(listen_addr0);
974     test::DNSResponder dns1(listen_addr1);
975     test::DNSResponder dns2(listen_addr2);
976     StartDns(dns0, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
977     StartDns(dns1, {{host_name, ns_type::ns_t_aaaa, "2001:db8::6"}});
978     StartDns(dns2, {{host_name, ns_type::ns_t_aaaa, "2001:db8::7"}});
979 
980     const std::vector<std::string> servers = {listen_addr0, listen_addr1, listen_addr2};
981     std::vector<std::thread> threads(10);
982     for (std::thread& thread : threads) {
983         thread = std::thread([this, &servers]() {
984             unsigned delay = arc4random_uniform(1 * 1000 * 1000);  // <= 1s
985             usleep(delay);
986             std::vector<std::string> serverSubset;
987             for (const auto& server : servers) {
988                 if (arc4random_uniform(2)) {
989                     serverSubset.push_back(server);
990                 }
991             }
992             if (serverSubset.empty()) serverSubset = servers;
993             ASSERT_TRUE(mDnsClient.SetResolversForNetwork(serverSubset));
994             const addrinfo hints = {.ai_family = AF_INET6};
995             addrinfo* result = nullptr;
996             int rv = getaddrinfo("konbanha", nullptr, &hints, &result);
997             EXPECT_EQ(0, rv) << "error [" << rv << "] " << gai_strerror(rv);
998             if (result) {
999                 freeaddrinfo(result);
1000                 result = nullptr;
1001             }
1002         });
1003     }
1004     for (std::thread& thread : threads) {
1005         thread.join();
1006     }
1007 
1008     std::vector<std::string> res_servers;
1009     std::vector<std::string> res_domains;
1010     std::vector<std::string> res_tls_servers;
1011     res_params res_params;
1012     std::vector<ResolverStats> res_stats;
1013     int wait_for_pending_req_timeout_count;
1014     ASSERT_TRUE(DnsResponderClient::GetResolverInfo(
1015             mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains, &res_tls_servers,
1016             &res_params, &res_stats, &wait_for_pending_req_timeout_count));
1017     EXPECT_EQ(0, wait_for_pending_req_timeout_count);
1018 }
1019 
TEST_F(ResolverTest,SkipBadServersDueToInternalError)1020 TEST_F(ResolverTest, SkipBadServersDueToInternalError) {
1021     constexpr char listen_addr1[] = "fe80::1";
1022     constexpr char listen_addr2[] = "255.255.255.255";
1023     constexpr char listen_addr3[] = "127.0.0.3";
1024 
1025     test::DNSResponder dns(listen_addr3);
1026     ASSERT_TRUE(dns.startServer());
1027 
1028     ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
1029     parcel.servers = {listen_addr1, listen_addr2, listen_addr3};
1030 
1031     // Bad servers can be distinguished after two attempts.
1032     parcel.minSamples = 2;
1033     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
1034 
1035     // Start querying five times.
1036     for (int i = 0; i < 5; i++) {
1037         std::string hostName = StringPrintf("hello%d.com.", i);
1038         dns.addMapping(hostName, ns_type::ns_t_a, "1.2.3.4");
1039         const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
1040         EXPECT_TRUE(safe_getaddrinfo(hostName.c_str(), nullptr, &hints) != nullptr);
1041     }
1042 
1043     const std::vector<NameserverStats> expectedCleartextDnsStats = {
1044             NameserverStats(listen_addr1).setInternalErrors(2),
1045             NameserverStats(listen_addr2).setInternalErrors(2),
1046             NameserverStats(listen_addr3).setSuccesses(5),
1047     };
1048     EXPECT_TRUE(expectStatsFromGetResolverInfo(expectedCleartextDnsStats));
1049 }
1050 
TEST_F(ResolverTest,SkipBadServersDueToTimeout)1051 TEST_F(ResolverTest, SkipBadServersDueToTimeout) {
1052     constexpr char listen_addr1[] = "127.0.0.3";
1053     constexpr char listen_addr2[] = "127.0.0.4";
1054 
1055     // Set dns1 non-responsive and dns2 workable.
1056     test::DNSResponder dns1(listen_addr1, test::kDefaultListenService, static_cast<ns_rcode>(-1));
1057     test::DNSResponder dns2(listen_addr2);
1058     dns1.setResponseProbability(0.0);
1059     ASSERT_TRUE(dns1.startServer());
1060     ASSERT_TRUE(dns2.startServer());
1061 
1062     ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
1063     parcel.servers = {listen_addr1, listen_addr2};
1064 
1065     // Bad servers can be distinguished after two attempts.
1066     parcel.minSamples = 2;
1067     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
1068 
1069     // Start querying five times.
1070     for (int i = 0; i < 5; i++) {
1071         std::string hostName = StringPrintf("hello%d.com.", i);
1072         dns1.addMapping(hostName, ns_type::ns_t_a, "1.2.3.4");
1073         dns2.addMapping(hostName, ns_type::ns_t_a, "1.2.3.5");
1074         const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
1075         EXPECT_TRUE(safe_getaddrinfo(hostName.c_str(), nullptr, &hints) != nullptr);
1076     }
1077 
1078     const std::vector<NameserverStats> expectedCleartextDnsStats = {
1079             NameserverStats(listen_addr1).setTimeouts(2),
1080             NameserverStats(listen_addr2).setSuccesses(5),
1081     };
1082     EXPECT_TRUE(expectStatsFromGetResolverInfo(expectedCleartextDnsStats));
1083     EXPECT_EQ(dns1.queries().size(), 2U);
1084     EXPECT_EQ(dns2.queries().size(), 5U);
1085 }
1086 
TEST_F(ResolverTest,GetAddrInfoFromCustTable_InvalidInput)1087 TEST_F(ResolverTest, GetAddrInfoFromCustTable_InvalidInput) {
1088     constexpr char hostnameNoip[] = "noip.example.com.";
1089     constexpr char hostnameInvalidip[] = "invalidip.example.com.";
1090     const std::vector<aidl::android::net::ResolverHostsParcel> invalidCustHosts = {
1091             {"", hostnameNoip},
1092             {"wrong IP", hostnameInvalidip},
1093     };
1094     test::DNSResponder dns;
1095     StartDns(dns, {});
1096     auto resolverParams = DnsResponderClient::GetDefaultResolverParamsParcel();
1097     resolverParams.resolverOptions.hosts = invalidCustHosts;
1098     ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(resolverParams).isOk());
1099     for (const auto& hostname : {hostnameNoip, hostnameInvalidip}) {
1100         // The query won't get data from customized table because of invalid customized table
1101         // and DNSResponder also has no records. hostnameNoip has never registered and
1102         // hostnameInvalidip has registered but wrong IP.
1103         const addrinfo hints = {.ai_family = AF_UNSPEC};
1104         ScopedAddrinfo result = safe_getaddrinfo(hostname, nullptr, &hints);
1105         ASSERT_TRUE(result == nullptr);
1106         EXPECT_EQ(4U, GetNumQueries(dns, hostname));
1107     }
1108 }
1109 
TEST_F(ResolverTest,GetAddrInfoFromCustTable)1110 TEST_F(ResolverTest, GetAddrInfoFromCustTable) {
1111     constexpr char hostnameV4[] = "v4only.example.com.";
1112     constexpr char hostnameV6[] = "v6only.example.com.";
1113     constexpr char hostnameV4V6[] = "v4v6.example.com.";
1114     constexpr char custAddrV4[] = "1.2.3.4";
1115     constexpr char custAddrV6[] = "::1.2.3.4";
1116     constexpr char dnsSvAddrV4[] = "1.2.3.5";
1117     constexpr char dnsSvAddrV6[] = "::1.2.3.5";
1118     const std::vector<aidl::android::net::ResolverHostsParcel> custHostV4 = {
1119             {custAddrV4, hostnameV4},
1120     };
1121     const std::vector<aidl::android::net::ResolverHostsParcel> custHostV6 = {
1122             {custAddrV6, hostnameV6},
1123     };
1124     const std::vector<aidl::android::net::ResolverHostsParcel> custHostV4V6 = {
1125             {custAddrV4, hostnameV4V6},
1126             {custAddrV6, hostnameV4V6},
1127     };
1128     const std::vector<DnsRecord> dnsSvHostV4 = {
1129             {hostnameV4, ns_type::ns_t_a, dnsSvAddrV4},
1130     };
1131     const std::vector<DnsRecord> dnsSvHostV6 = {
1132             {hostnameV6, ns_type::ns_t_aaaa, dnsSvAddrV6},
1133     };
1134     const std::vector<DnsRecord> dnsSvHostV4V6 = {
1135             {hostnameV4V6, ns_type::ns_t_a, dnsSvAddrV4},
1136             {hostnameV4V6, ns_type::ns_t_aaaa, dnsSvAddrV6},
1137     };
1138     struct TestConfig {
1139         const std::string name;
1140         const std::vector<aidl::android::net::ResolverHostsParcel> customizedHosts;
1141         const std::vector<DnsRecord> dnsserverHosts;
1142         const std::vector<std::string> queryResult;
1143         std::string asParameters() const {
1144             return StringPrintf("name: %s, customizedHosts: %s, dnsserverHosts: %s", name.c_str(),
1145                                 customizedHosts.empty() ? "No" : "Yes",
1146                                 dnsserverHosts.empty() ? "No" : "Yes");
1147         }
1148     } testConfigs[]{
1149             // clang-format off
1150             {hostnameV4,    {},            {},             {}},
1151             {hostnameV4,    {},            dnsSvHostV4,    {dnsSvAddrV4}},
1152             {hostnameV4,    custHostV4,    {},             {custAddrV4}},
1153             {hostnameV4,    custHostV4,    dnsSvHostV4,    {custAddrV4}},
1154             {hostnameV6,    {},            {},             {}},
1155             {hostnameV6,    {},            dnsSvHostV6,    {dnsSvAddrV6}},
1156             {hostnameV6,    custHostV6,    {},             {custAddrV6}},
1157             {hostnameV6,    custHostV6,    dnsSvHostV6,    {custAddrV6}},
1158             {hostnameV4V6,  {},            {},             {}},
1159             {hostnameV4V6,  {},            dnsSvHostV4V6,  {dnsSvAddrV4, dnsSvAddrV6}},
1160             {hostnameV4V6,  custHostV4V6,  {},             {custAddrV4, custAddrV6}},
1161             {hostnameV4V6,  custHostV4V6,  dnsSvHostV4V6,  {custAddrV4, custAddrV6}},
1162             // clang-format on
1163     };
1164 
1165     for (const auto& config : testConfigs) {
1166         SCOPED_TRACE(config.asParameters());
1167 
1168         test::DNSResponder dns;
1169         StartDns(dns, config.dnsserverHosts);
1170 
1171         auto resolverParams = DnsResponderClient::GetDefaultResolverParamsParcel();
1172         resolverParams.resolverOptions.hosts = config.customizedHosts;
1173         ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(resolverParams).isOk());
1174         const addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_STREAM};
1175         ScopedAddrinfo result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
1176         if (config.customizedHosts.empty() && config.dnsserverHosts.empty()) {
1177             ASSERT_TRUE(result == nullptr);
1178             EXPECT_EQ(2U, GetNumQueries(dns, config.name.c_str()));
1179         } else {
1180             ASSERT_TRUE(result != nullptr);
1181             EXPECT_THAT(ToStrings(result), testing::UnorderedElementsAreArray(config.queryResult));
1182             EXPECT_EQ(config.customizedHosts.empty() ? 2U : 0U,
1183                       GetNumQueries(dns, config.name.c_str()));
1184         }
1185 
1186         EXPECT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
1187     }
1188 }
1189 
TEST_F(ResolverTest,GetAddrInfoFromCustTable_Modify)1190 TEST_F(ResolverTest, GetAddrInfoFromCustTable_Modify) {
1191     constexpr char hostnameV4V6[] = "v4v6.example.com.";
1192     constexpr char custAddrV4[] = "1.2.3.4";
1193     constexpr char custAddrV6[] = "::1.2.3.4";
1194     constexpr char dnsSvAddrV4[] = "1.2.3.5";
1195     constexpr char dnsSvAddrV6[] = "::1.2.3.5";
1196     const std::vector<DnsRecord> dnsSvHostV4V6 = {
1197             {hostnameV4V6, ns_type::ns_t_a, dnsSvAddrV4},
1198             {hostnameV4V6, ns_type::ns_t_aaaa, dnsSvAddrV6},
1199     };
1200     const std::vector<aidl::android::net::ResolverHostsParcel> custHostV4V6 = {
1201             {custAddrV4, hostnameV4V6},
1202             {custAddrV6, hostnameV4V6},
1203     };
1204     test::DNSResponder dns;
1205     StartDns(dns, dnsSvHostV4V6);
1206     auto resolverParams = DnsResponderClient::GetDefaultResolverParamsParcel();
1207 
1208     resolverParams.resolverOptions.hosts = custHostV4V6;
1209     ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(resolverParams).isOk());
1210     const addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_STREAM};
1211     ScopedAddrinfo result = safe_getaddrinfo(hostnameV4V6, nullptr, &hints);
1212     ASSERT_TRUE(result != nullptr);
1213     EXPECT_THAT(ToStrings(result), testing::UnorderedElementsAreArray({custAddrV4, custAddrV6}));
1214     EXPECT_EQ(0U, GetNumQueries(dns, hostnameV4V6));
1215 
1216     resolverParams.resolverOptions.hosts = {};
1217     ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(resolverParams).isOk());
1218     result = safe_getaddrinfo(hostnameV4V6, nullptr, &hints);
1219     ASSERT_TRUE(result != nullptr);
1220     EXPECT_THAT(ToStrings(result), testing::UnorderedElementsAreArray({dnsSvAddrV4, dnsSvAddrV6}));
1221     EXPECT_EQ(2U, GetNumQueries(dns, hostnameV4V6));
1222 }
1223 
TEST_F(ResolverTest,EmptySetup)1224 TEST_F(ResolverTest, EmptySetup) {
1225     std::vector<std::string> servers;
1226     std::vector<std::string> domains;
1227     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
1228     std::vector<std::string> res_servers;
1229     std::vector<std::string> res_domains;
1230     std::vector<std::string> res_tls_servers;
1231     res_params res_params;
1232     std::vector<ResolverStats> res_stats;
1233     int wait_for_pending_req_timeout_count;
1234     ASSERT_TRUE(DnsResponderClient::GetResolverInfo(
1235             mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains, &res_tls_servers,
1236             &res_params, &res_stats, &wait_for_pending_req_timeout_count));
1237     EXPECT_EQ(0U, res_servers.size());
1238     EXPECT_EQ(0U, res_domains.size());
1239     EXPECT_EQ(0U, res_tls_servers.size());
1240     ASSERT_EQ(static_cast<size_t>(IDnsResolver::RESOLVER_PARAMS_COUNT), kDefaultParams.size());
1241     EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY],
1242               res_params.sample_validity);
1243     EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD],
1244               res_params.success_threshold);
1245     EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES], res_params.min_samples);
1246     EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES], res_params.max_samples);
1247     EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
1248               res_params.base_timeout_msec);
1249     EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT], res_params.retry_count);
1250 }
1251 
TEST_F(ResolverTest,SearchPathChange)1252 TEST_F(ResolverTest, SearchPathChange) {
1253     constexpr char listen_addr[] = "127.0.0.13";
1254     constexpr char host_name1[] = "test13.domain1.org.";
1255     constexpr char host_name2[] = "test13.domain2.org.";
1256     std::vector<std::string> servers = {listen_addr};
1257     std::vector<std::string> domains = {"domain1.org"};
1258 
1259     const std::vector<DnsRecord> records = {
1260             {host_name1, ns_type::ns_t_aaaa, "2001:db8::13"},
1261             {host_name2, ns_type::ns_t_aaaa, "2001:db8::1:13"},
1262     };
1263     test::DNSResponder dns(listen_addr);
1264     StartDns(dns, records);
1265     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
1266 
1267     const addrinfo hints = {.ai_family = AF_INET6};
1268     ScopedAddrinfo result = safe_getaddrinfo("test13", nullptr, &hints);
1269     EXPECT_TRUE(result != nullptr);
1270     EXPECT_EQ(1U, dns.queries().size());
1271     EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
1272     EXPECT_EQ("2001:db8::13", ToString(result));
1273 
1274     // Test that changing the domain search path on its own works.
1275     domains = {"domain2.org"};
1276     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
1277     dns.clearQueries();
1278 
1279     result = safe_getaddrinfo("test13", nullptr, &hints);
1280     EXPECT_TRUE(result != nullptr);
1281     EXPECT_EQ(1U, dns.queries().size());
1282     EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
1283     EXPECT_EQ("2001:db8::1:13", ToString(result));
1284 }
1285 
1286 namespace {
1287 
getResolverDomains(aidl::android::net::IDnsResolver * dnsResolverService,unsigned netId)1288 std::vector<std::string> getResolverDomains(aidl::android::net::IDnsResolver* dnsResolverService,
1289                                             unsigned netId) {
1290     std::vector<std::string> res_servers;
1291     std::vector<std::string> res_domains;
1292     std::vector<std::string> res_tls_servers;
1293     res_params res_params;
1294     std::vector<ResolverStats> res_stats;
1295     int wait_for_pending_req_timeout_count;
1296     DnsResponderClient::GetResolverInfo(dnsResolverService, netId, &res_servers, &res_domains,
1297                                         &res_tls_servers, &res_params, &res_stats,
1298                                         &wait_for_pending_req_timeout_count);
1299     return res_domains;
1300 }
1301 
1302 }  // namespace
1303 
TEST_F(ResolverTest,SearchPathPrune)1304 TEST_F(ResolverTest, SearchPathPrune) {
1305     constexpr size_t DUPLICATED_DOMAIN_NUM = 3;
1306     constexpr char listen_addr[] = "127.0.0.13";
1307     constexpr char domian_name1[] = "domain13.org.";
1308     constexpr char domian_name2[] = "domain14.org.";
1309     constexpr char host_name1[] = "test13.domain13.org.";
1310     constexpr char host_name2[] = "test14.domain14.org.";
1311     std::vector<std::string> servers = {listen_addr};
1312 
1313     std::vector<std::string> testDomains1;
1314     std::vector<std::string> testDomains2;
1315     // Domain length should be <= 255
1316     // Max number of domains in search path is 6
1317     for (size_t i = 0; i < MAXDNSRCH + 1; i++) {
1318         // Fill up with invalid domain
1319         testDomains1.push_back(std::string(300, i + '0'));
1320         // Fill up with valid but duplicated domain
1321         testDomains2.push_back(StringPrintf("domain%zu.org", i % DUPLICATED_DOMAIN_NUM));
1322     }
1323 
1324     // Add valid domain used for query.
1325     testDomains1.push_back(domian_name1);
1326 
1327     // Add valid domain twice used for query.
1328     testDomains2.push_back(domian_name2);
1329     testDomains2.push_back(domian_name2);
1330 
1331     const std::vector<DnsRecord> records = {
1332             {host_name1, ns_type::ns_t_aaaa, "2001:db8::13"},
1333             {host_name2, ns_type::ns_t_aaaa, "2001:db8::1:13"},
1334     };
1335     test::DNSResponder dns(listen_addr);
1336     StartDns(dns, records);
1337     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, testDomains1));
1338 
1339     const addrinfo hints = {.ai_family = AF_INET6};
1340     ScopedAddrinfo result = safe_getaddrinfo("test13", nullptr, &hints);
1341 
1342     EXPECT_TRUE(result != nullptr);
1343 
1344     EXPECT_EQ(1U, dns.queries().size());
1345     EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
1346     EXPECT_EQ("2001:db8::13", ToString(result));
1347 
1348     const auto& res_domains1 = getResolverDomains(mDnsClient.resolvService(), TEST_NETID);
1349     // Expect 1 valid domain, invalid domains are removed.
1350     ASSERT_EQ(1U, res_domains1.size());
1351     EXPECT_EQ(domian_name1, res_domains1[0]);
1352 
1353     dns.clearQueries();
1354 
1355     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, testDomains2));
1356 
1357     result = safe_getaddrinfo("test14", nullptr, &hints);
1358     EXPECT_TRUE(result != nullptr);
1359 
1360     // (3 domains * 2 retries) + 1 success query = 7
1361     EXPECT_EQ(7U, dns.queries().size());
1362     EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
1363     EXPECT_EQ("2001:db8::1:13", ToString(result));
1364 
1365     const auto& res_domains2 = getResolverDomains(mDnsClient.resolvService(), TEST_NETID);
1366     // Expect 4 valid domain, duplicate domains are removed.
1367     EXPECT_EQ(DUPLICATED_DOMAIN_NUM + 1U, res_domains2.size());
1368     EXPECT_THAT(
1369             std::vector<std::string>({"domain0.org", "domain1.org", "domain2.org", domian_name2}),
1370             testing::ElementsAreArray(res_domains2));
1371 }
1372 
1373 // If we move this function to dns_responder_client, it will complicate the dependency need of
1374 // dns_tls_frontend.h.
setupTlsServers(const std::vector<std::string> & servers,std::vector<std::unique_ptr<test::DnsTlsFrontend>> * tls)1375 static void setupTlsServers(const std::vector<std::string>& servers,
1376                             std::vector<std::unique_ptr<test::DnsTlsFrontend>>* tls) {
1377     constexpr char listen_udp[] = "53";
1378     constexpr char listen_tls[] = "853";
1379 
1380     for (const auto& server : servers) {
1381         auto t = std::make_unique<test::DnsTlsFrontend>(server, listen_tls, server, listen_udp);
1382         t = std::make_unique<test::DnsTlsFrontend>(server, listen_tls, server, listen_udp);
1383         t->startServer();
1384         tls->push_back(std::move(t));
1385     }
1386 }
1387 
TEST_F(ResolverTest,MaxServerPrune_Binder)1388 TEST_F(ResolverTest, MaxServerPrune_Binder) {
1389     std::vector<std::string> domains;
1390     std::vector<std::unique_ptr<test::DNSResponder>> dns;
1391     std::vector<std::unique_ptr<test::DnsTlsFrontend>> tls;
1392     std::vector<std::string> servers;
1393     std::vector<DnsResponderClient::Mapping> mappings;
1394 
1395     for (unsigned i = 0; i < MAXDNSRCH + 1; i++) {
1396         domains.push_back(StringPrintf("example%u.com", i));
1397     }
1398     ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(1, domains, &mappings));
1399     ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(MAXNS + 1, mappings, &dns, &servers));
1400     ASSERT_NO_FATAL_FAILURE(setupTlsServers(servers, &tls));
1401 
1402     ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, domains, kDefaultParams,
1403                                                kDefaultPrivateDnsHostName));
1404 
1405     // If the private DNS validation hasn't completed yet before backend DNS servers stop,
1406     // TLS servers will get stuck in handleOneRequest(), which causes this test stuck in
1407     // ~DnsTlsFrontend() because the TLS server loop threads can't be terminated.
1408     // So, wait for private DNS validation done before stopping backend DNS servers.
1409     for (int i = 0; i < MAXNS; i++) {
1410         LOG(INFO) << "Waiting for private DNS validation on " << tls[i]->listen_address() << ".";
1411         EXPECT_TRUE(WaitForPrivateDnsValidation(tls[i]->listen_address(), true));
1412         LOG(INFO) << "private DNS validation on " << tls[i]->listen_address() << " done.";
1413     }
1414 
1415     std::vector<std::string> res_servers;
1416     std::vector<std::string> res_domains;
1417     std::vector<std::string> res_tls_servers;
1418     res_params res_params;
1419     std::vector<ResolverStats> res_stats;
1420     int wait_for_pending_req_timeout_count;
1421     ASSERT_TRUE(DnsResponderClient::GetResolverInfo(
1422             mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains, &res_tls_servers,
1423             &res_params, &res_stats, &wait_for_pending_req_timeout_count));
1424 
1425     // Check the size of the stats and its contents.
1426     EXPECT_EQ(static_cast<size_t>(MAXNS), res_servers.size());
1427     EXPECT_EQ(static_cast<size_t>(MAXNS), res_tls_servers.size());
1428     EXPECT_EQ(static_cast<size_t>(MAXDNSRCH), res_domains.size());
1429     EXPECT_TRUE(std::equal(servers.begin(), servers.begin() + MAXNS, res_servers.begin()));
1430     EXPECT_TRUE(std::equal(servers.begin(), servers.begin() + MAXNS, res_tls_servers.begin()));
1431     EXPECT_TRUE(std::equal(domains.begin(), domains.begin() + MAXDNSRCH, res_domains.begin()));
1432 }
1433 
TEST_F(ResolverTest,ResolverStats)1434 TEST_F(ResolverTest, ResolverStats) {
1435     constexpr char listen_addr1[] = "127.0.0.4";
1436     constexpr char listen_addr2[] = "127.0.0.5";
1437     constexpr char listen_addr3[] = "127.0.0.6";
1438 
1439     // Set server 1 timeout.
1440     test::DNSResponder dns1(listen_addr1, "53", static_cast<ns_rcode>(-1));
1441     dns1.setResponseProbability(0.0);
1442     ASSERT_TRUE(dns1.startServer());
1443 
1444     // Set server 2 responding server failure.
1445     test::DNSResponder dns2(listen_addr2);
1446     dns2.setResponseProbability(0.0);
1447     ASSERT_TRUE(dns2.startServer());
1448 
1449     // Set server 3 workable.
1450     test::DNSResponder dns3(listen_addr3);
1451     dns3.addMapping(kHelloExampleCom, ns_type::ns_t_a, "1.2.3.4");
1452     ASSERT_TRUE(dns3.startServer());
1453 
1454     std::vector<std::string> servers = {listen_addr1, listen_addr2, listen_addr3};
1455     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
1456 
1457     dns3.clearQueries();
1458     const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
1459     ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
1460     size_t found = GetNumQueries(dns3, kHelloExampleCom);
1461     EXPECT_LE(1U, found);
1462     std::string result_str = ToString(result);
1463     EXPECT_TRUE(result_str == "1.2.3.4") << ", result_str='" << result_str << "'";
1464 
1465     const std::vector<NameserverStats> expectedCleartextDnsStats = {
1466             NameserverStats(listen_addr1).setTimeouts(1),
1467             NameserverStats(listen_addr2).setErrors(1),
1468             NameserverStats(listen_addr3).setSuccesses(1),
1469     };
1470     EXPECT_TRUE(expectStatsFromGetResolverInfo(expectedCleartextDnsStats));
1471 }
1472 
TEST_F(ResolverTest,AlwaysUseLatestSetupParamsInLookups)1473 TEST_F(ResolverTest, AlwaysUseLatestSetupParamsInLookups) {
1474     constexpr char listen_addr1[] = "127.0.0.3";
1475     constexpr char listen_addr2[] = "255.255.255.255";
1476     constexpr char listen_addr3[] = "127.0.0.4";
1477     constexpr char hostname[] = "hello";
1478     constexpr char fqdn_with_search_domain[] = "hello.domain2.com.";
1479 
1480     test::DNSResponder dns1(listen_addr1, test::kDefaultListenService, static_cast<ns_rcode>(-1));
1481     dns1.setResponseProbability(0.0);
1482     ASSERT_TRUE(dns1.startServer());
1483 
1484     test::DNSResponder dns3(listen_addr3);
1485     StartDns(dns3, {{fqdn_with_search_domain, ns_type::ns_t_a, "1.2.3.4"}});
1486 
1487     ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
1488     parcel.tlsServers.clear();
1489     parcel.servers = {listen_addr1, listen_addr2};
1490     parcel.domains = {"domain1.com", "domain2.com"};
1491     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
1492 
1493     // Expect the things happening in t1:
1494     //   1. The lookup starts using the first domain for query. It sends queries to the populated
1495     //      nameserver list {listen_addr1, listen_addr2} for the hostname "hello.domain1.com".
1496     //   2. A different list of nameservers is updated to the resolver. Revision ID is incremented.
1497     //   3. The query for the hostname times out. The lookup fails to add the timeout record to the
1498     //      the stats because of the unmatched revision ID.
1499     //   4. The lookup starts using the second domain for query. It sends queries to the populated
1500     //      nameserver list {listen_addr3, listen_addr1, listen_addr2} for another hostname
1501     //      "hello.domain2.com".
1502     //   5. The lookup gets the answer and updates a success record to the stats.
1503     std::thread t1([&hostname]() {
1504         const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
1505         ScopedAddrinfo result = safe_getaddrinfo(hostname, nullptr, &hints);
1506         EXPECT_NE(result.get(), nullptr);
1507         EXPECT_EQ(ToString(result), "1.2.3.4");
1508     });
1509 
1510     // Wait for t1 to start the step 1.
1511     while (dns1.queries().size() == 0) {
1512         usleep(1000);
1513     }
1514 
1515     // Update the resolver with three nameservers. This will increment the revision ID.
1516     parcel.servers = {listen_addr3, listen_addr1, listen_addr2};
1517     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
1518 
1519     t1.join();
1520     EXPECT_EQ(0U, GetNumQueriesForType(dns3, ns_type::ns_t_aaaa, fqdn_with_search_domain));
1521     EXPECT_EQ(1U, GetNumQueriesForType(dns3, ns_type::ns_t_a, fqdn_with_search_domain));
1522 
1523     const std::vector<NameserverStats> expectedCleartextDnsStats = {
1524             NameserverStats(listen_addr1),
1525             NameserverStats(listen_addr2),
1526             NameserverStats(listen_addr3).setSuccesses(1),
1527     };
1528     EXPECT_TRUE(expectStatsFromGetResolverInfo(expectedCleartextDnsStats));
1529 }
1530 
1531 // Test what happens if the specified TLS server is nonexistent.
TEST_F(ResolverTest,GetHostByName_TlsMissing)1532 TEST_F(ResolverTest, GetHostByName_TlsMissing) {
1533     constexpr char listen_addr[] = "127.0.0.3";
1534     constexpr char host_name[] = "tlsmissing.example.com.";
1535 
1536     test::DNSResponder dns;
1537     StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.3"}});
1538     std::vector<std::string> servers = {listen_addr};
1539 
1540     // There's nothing listening on this address, so validation will either fail or
1541     /// hang.  Either way, queries will continue to flow to the DNSResponder.
1542     ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
1543 
1544     const hostent* result;
1545 
1546     result = gethostbyname("tlsmissing");
1547     ASSERT_FALSE(result == nullptr);
1548     EXPECT_EQ("1.2.3.3", ToString(result));
1549 
1550     // Clear TLS bit.
1551     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1552 }
1553 
1554 // Test what happens if the specified TLS server replies with garbage.
TEST_F(ResolverTest,GetHostByName_TlsBroken)1555 TEST_F(ResolverTest, GetHostByName_TlsBroken) {
1556     constexpr char listen_addr[] = "127.0.0.3";
1557     constexpr char host_name1[] = "tlsbroken1.example.com.";
1558     constexpr char host_name2[] = "tlsbroken2.example.com.";
1559     const std::vector<DnsRecord> records = {
1560             {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1561             {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1562     };
1563 
1564     test::DNSResponder dns;
1565     StartDns(dns, records);
1566     std::vector<std::string> servers = {listen_addr};
1567 
1568     // Bind the specified private DNS socket but don't respond to any client sockets yet.
1569     int s = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP);
1570     ASSERT_TRUE(s >= 0);
1571     struct sockaddr_in tlsServer = {
1572             .sin_family = AF_INET,
1573             .sin_port = htons(853),
1574     };
1575     ASSERT_TRUE(inet_pton(AF_INET, listen_addr, &tlsServer.sin_addr));
1576     ASSERT_TRUE(enableSockopt(s, SOL_SOCKET, SO_REUSEPORT).ok());
1577     ASSERT_TRUE(enableSockopt(s, SOL_SOCKET, SO_REUSEADDR).ok());
1578     ASSERT_FALSE(bind(s, reinterpret_cast<struct sockaddr*>(&tlsServer), sizeof(tlsServer)));
1579     ASSERT_FALSE(listen(s, 1));
1580 
1581     // Trigger TLS validation.
1582     ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
1583 
1584     struct sockaddr_storage cliaddr;
1585     socklen_t sin_size = sizeof(cliaddr);
1586     int new_fd = accept4(s, reinterpret_cast<struct sockaddr*>(&cliaddr), &sin_size, SOCK_CLOEXEC);
1587     ASSERT_TRUE(new_fd > 0);
1588 
1589     // We've received the new file descriptor but not written to it or closed, so the
1590     // validation is still pending.  Queries should still flow correctly because the
1591     // server is not used until validation succeeds.
1592     const hostent* result;
1593     result = gethostbyname("tlsbroken1");
1594     ASSERT_FALSE(result == nullptr);
1595     EXPECT_EQ("1.2.3.1", ToString(result));
1596 
1597     // Now we cause the validation to fail.
1598     std::string garbage = "definitely not a valid TLS ServerHello";
1599     write(new_fd, garbage.data(), garbage.size());
1600     close(new_fd);
1601 
1602     // Validation failure shouldn't interfere with lookups, because lookups won't be sent
1603     // to the TLS server unless validation succeeds.
1604     result = gethostbyname("tlsbroken2");
1605     ASSERT_FALSE(result == nullptr);
1606     EXPECT_EQ("1.2.3.2", ToString(result));
1607 
1608     // Clear TLS bit.
1609     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1610     close(s);
1611 }
1612 
TEST_F(ResolverTest,GetHostByName_Tls)1613 TEST_F(ResolverTest, GetHostByName_Tls) {
1614     constexpr char listen_addr[] = "127.0.0.3";
1615     constexpr char listen_udp[] = "53";
1616     constexpr char listen_tls[] = "853";
1617     constexpr char host_name1[] = "tls1.example.com.";
1618     constexpr char host_name2[] = "tls2.example.com.";
1619     constexpr char host_name3[] = "tls3.example.com.";
1620     const std::vector<DnsRecord> records = {
1621             {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1622             {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1623             {host_name3, ns_type::ns_t_a, "1.2.3.3"},
1624     };
1625 
1626     test::DNSResponder dns;
1627     StartDns(dns, records);
1628     std::vector<std::string> servers = {listen_addr};
1629 
1630     test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1631     ASSERT_TRUE(tls.startServer());
1632     ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
1633     EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
1634 
1635     const hostent* result = gethostbyname("tls1");
1636     ASSERT_FALSE(result == nullptr);
1637     EXPECT_EQ("1.2.3.1", ToString(result));
1638 
1639     // Wait for query to get counted.
1640     EXPECT_TRUE(tls.waitForQueries(2));
1641 
1642     // Stop the TLS server.  Since we're in opportunistic mode, queries will
1643     // fall back to the locally-assigned (clear text) nameservers.
1644     tls.stopServer();
1645 
1646     dns.clearQueries();
1647     result = gethostbyname("tls2");
1648     EXPECT_FALSE(result == nullptr);
1649     EXPECT_EQ("1.2.3.2", ToString(result));
1650     const auto queries = dns.queries();
1651     EXPECT_EQ(1U, queries.size());
1652     EXPECT_EQ("tls2.example.com.", queries[0].name);
1653     EXPECT_EQ(ns_t_a, queries[0].type);
1654 
1655     // Reset the resolvers without enabling TLS.  Queries should still be routed
1656     // to the UDP endpoint.
1657     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1658 
1659     result = gethostbyname("tls3");
1660     ASSERT_FALSE(result == nullptr);
1661     EXPECT_EQ("1.2.3.3", ToString(result));
1662 }
1663 
TEST_F(ResolverTest,GetHostByName_TlsFailover)1664 TEST_F(ResolverTest, GetHostByName_TlsFailover) {
1665     constexpr char listen_addr1[] = "127.0.0.3";
1666     constexpr char listen_addr2[] = "127.0.0.4";
1667     constexpr char listen_udp[] = "53";
1668     constexpr char listen_tls[] = "853";
1669     constexpr char host_name1[] = "tlsfailover1.example.com.";
1670     constexpr char host_name2[] = "tlsfailover2.example.com.";
1671     const std::vector<DnsRecord> records1 = {
1672             {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1673             {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1674     };
1675     const std::vector<DnsRecord> records2 = {
1676             {host_name1, ns_type::ns_t_a, "1.2.3.3"},
1677             {host_name2, ns_type::ns_t_a, "1.2.3.4"},
1678     };
1679 
1680     test::DNSResponder dns1(listen_addr1);
1681     test::DNSResponder dns2(listen_addr2);
1682     StartDns(dns1, records1);
1683     StartDns(dns2, records2);
1684 
1685     std::vector<std::string> servers = {listen_addr1, listen_addr2};
1686 
1687     test::DnsTlsFrontend tls1(listen_addr1, listen_tls, listen_addr1, listen_udp);
1688     test::DnsTlsFrontend tls2(listen_addr2, listen_tls, listen_addr2, listen_udp);
1689     ASSERT_TRUE(tls1.startServer());
1690     ASSERT_TRUE(tls2.startServer());
1691     ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
1692                                                kDefaultPrivateDnsHostName));
1693     EXPECT_TRUE(WaitForPrivateDnsValidation(tls1.listen_address(), true));
1694     EXPECT_TRUE(WaitForPrivateDnsValidation(tls2.listen_address(), true));
1695 
1696     const hostent* result = gethostbyname("tlsfailover1");
1697     ASSERT_FALSE(result == nullptr);
1698     EXPECT_EQ("1.2.3.1", ToString(result));
1699 
1700     // Wait for query to get counted.
1701     EXPECT_TRUE(tls1.waitForQueries(2));
1702     // No new queries should have reached tls2.
1703     EXPECT_TRUE(tls2.waitForQueries(1));
1704 
1705     // Stop tls1.  Subsequent queries should attempt to reach tls1, fail, and retry to tls2.
1706     tls1.stopServer();
1707 
1708     result = gethostbyname("tlsfailover2");
1709     EXPECT_EQ("1.2.3.4", ToString(result));
1710 
1711     // Wait for query to get counted.
1712     EXPECT_TRUE(tls2.waitForQueries(2));
1713 
1714     // No additional queries should have reached the insecure servers.
1715     EXPECT_EQ(2U, dns1.queries().size());
1716     EXPECT_EQ(2U, dns2.queries().size());
1717 
1718     // Clear TLS bit.
1719     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
1720 }
1721 
TEST_F(ResolverTest,GetHostByName_BadTlsName)1722 TEST_F(ResolverTest, GetHostByName_BadTlsName) {
1723     constexpr char listen_addr[] = "127.0.0.3";
1724     constexpr char listen_udp[] = "53";
1725     constexpr char listen_tls[] = "853";
1726     constexpr char host_name[] = "badtlsname.example.com.";
1727 
1728     test::DNSResponder dns;
1729     StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.1"}});
1730     std::vector<std::string> servers = {listen_addr};
1731 
1732     test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1733     ASSERT_TRUE(tls.startServer());
1734     ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
1735                                                kDefaultIncorrectPrivateDnsHostName));
1736 
1737     // The TLS handshake would fail because the name of TLS server doesn't
1738     // match with TLS server's certificate.
1739     EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), false));
1740 
1741     // The query should fail hard, because a name was specified.
1742     EXPECT_EQ(nullptr, gethostbyname("badtlsname"));
1743 
1744     // Clear TLS bit.
1745     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1746 }
1747 
TEST_F(ResolverTest,GetAddrInfo_Tls)1748 TEST_F(ResolverTest, GetAddrInfo_Tls) {
1749     constexpr char listen_addr[] = "127.0.0.3";
1750     constexpr char listen_udp[] = "53";
1751     constexpr char listen_tls[] = "853";
1752     constexpr char host_name[] = "addrinfotls.example.com.";
1753     const std::vector<DnsRecord> records = {
1754             {host_name, ns_type::ns_t_a, "1.2.3.4"},
1755             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1756     };
1757 
1758     test::DNSResponder dns;
1759     StartDns(dns, records);
1760     std::vector<std::string> servers = {listen_addr};
1761 
1762     test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1763     ASSERT_TRUE(tls.startServer());
1764     ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
1765                                                kDefaultPrivateDnsHostName));
1766     EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
1767 
1768     dns.clearQueries();
1769     ScopedAddrinfo result = safe_getaddrinfo("addrinfotls", nullptr, nullptr);
1770     EXPECT_TRUE(result != nullptr);
1771     size_t found = GetNumQueries(dns, host_name);
1772     EXPECT_LE(1U, found);
1773     // Could be A or AAAA
1774     std::string result_str = ToString(result);
1775     EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
1776             << ", result_str='" << result_str << "'";
1777     // Wait for both A and AAAA queries to get counted.
1778     EXPECT_TRUE(tls.waitForQueries(3));
1779 
1780     // Clear TLS bit.
1781     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1782 }
1783 
TEST_F(ResolverTest,TlsBypass)1784 TEST_F(ResolverTest, TlsBypass) {
1785     const char OFF[] = "off";
1786     const char OPPORTUNISTIC[] = "opportunistic";
1787     const char STRICT[] = "strict";
1788 
1789     const char GETHOSTBYNAME[] = "gethostbyname";
1790     const char GETADDRINFO[] = "getaddrinfo";
1791     const char GETADDRINFOFORNET[] = "getaddrinfofornet";
1792 
1793     const unsigned BYPASS_NETID = NETID_USE_LOCAL_NAMESERVERS | TEST_NETID;
1794 
1795     const char ADDR4[] = "192.0.2.1";
1796     const char ADDR6[] = "2001:db8::1";
1797 
1798     const char cleartext_addr[] = "127.0.0.53";
1799     const char cleartext_port[] = "53";
1800     const char tls_port[] = "853";
1801     const std::vector<std::string> servers = {cleartext_addr};
1802 
1803     test::DNSResponder dns(cleartext_addr);
1804     ASSERT_TRUE(dns.startServer());
1805 
1806     test::DnsTlsFrontend tls(cleartext_addr, tls_port, cleartext_addr, cleartext_port);
1807     ASSERT_TRUE(tls.startServer());
1808 
1809     // clang-format off
1810     struct TestConfig {
1811         const std::string mode;
1812         const bool withWorkingTLS;
1813         const std::string method;
1814 
1815         std::string asHostName() const {
1816             return StringPrintf("%s.%s.%s.", mode.c_str(), withWorkingTLS ? "tlsOn" : "tlsOff",
1817                                 method.c_str());
1818         }
1819     } testConfigs[]{
1820         {OFF,           true,  GETHOSTBYNAME},
1821         {OPPORTUNISTIC, true,  GETHOSTBYNAME},
1822         {STRICT,        true,  GETHOSTBYNAME},
1823         {OFF,           true,  GETADDRINFO},
1824         {OPPORTUNISTIC, true,  GETADDRINFO},
1825         {STRICT,        true,  GETADDRINFO},
1826         {OFF,           true,  GETADDRINFOFORNET},
1827         {OPPORTUNISTIC, true,  GETADDRINFOFORNET},
1828         {STRICT,        true,  GETADDRINFOFORNET},
1829         {OFF,           false, GETHOSTBYNAME},
1830         {OPPORTUNISTIC, false, GETHOSTBYNAME},
1831         {STRICT,        false, GETHOSTBYNAME},
1832         {OFF,           false, GETADDRINFO},
1833         {OPPORTUNISTIC, false, GETADDRINFO},
1834         {STRICT,        false, GETADDRINFO},
1835         {OFF,           false, GETADDRINFOFORNET},
1836         {OPPORTUNISTIC, false, GETADDRINFOFORNET},
1837         {STRICT,        false, GETADDRINFOFORNET},
1838     };
1839     // clang-format on
1840 
1841     for (const auto& config : testConfigs) {
1842         const std::string testHostName = config.asHostName();
1843         SCOPED_TRACE(testHostName);
1844 
1845         // Don't tempt test bugs due to caching.
1846         const char* host_name = testHostName.c_str();
1847         dns.addMapping(host_name, ns_type::ns_t_a, ADDR4);
1848         dns.addMapping(host_name, ns_type::ns_t_aaaa, ADDR6);
1849 
1850         if (config.withWorkingTLS) {
1851             if (!tls.running()) {
1852                 ASSERT_TRUE(tls.startServer());
1853             }
1854         } else {
1855             if (tls.running()) {
1856                 ASSERT_TRUE(tls.stopServer());
1857             }
1858         }
1859 
1860         if (config.mode == OFF) {
1861             ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, kDefaultSearchDomains,
1862                                                           kDefaultParams));
1863         } else /* OPPORTUNISTIC or STRICT */ {
1864             const char* tls_hostname = (config.mode == STRICT) ? kDefaultPrivateDnsHostName : "";
1865             ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
1866                                                        kDefaultParams, tls_hostname));
1867 
1868             // Wait for the validation event. If the server is running, the validation should
1869             // succeed; otherwise, the validation should fail.
1870             EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), config.withWorkingTLS));
1871             if (config.withWorkingTLS) {
1872                 EXPECT_TRUE(tls.waitForQueries(1));
1873                 tls.clearQueries();
1874             }
1875         }
1876 
1877         const hostent* h_result = nullptr;
1878         ScopedAddrinfo ai_result;
1879 
1880         if (config.method == GETHOSTBYNAME) {
1881             ASSERT_EQ(0, setNetworkForResolv(BYPASS_NETID));
1882             h_result = gethostbyname(host_name);
1883 
1884             EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
1885             ASSERT_FALSE(h_result == nullptr);
1886             ASSERT_EQ(4, h_result->h_length);
1887             ASSERT_FALSE(h_result->h_addr_list[0] == nullptr);
1888             EXPECT_EQ(ADDR4, ToString(h_result));
1889             EXPECT_TRUE(h_result->h_addr_list[1] == nullptr);
1890         } else if (config.method == GETADDRINFO) {
1891             ASSERT_EQ(0, setNetworkForResolv(BYPASS_NETID));
1892             ai_result = safe_getaddrinfo(host_name, nullptr, nullptr);
1893             EXPECT_TRUE(ai_result != nullptr);
1894 
1895             EXPECT_LE(1U, GetNumQueries(dns, host_name));
1896             // Could be A or AAAA
1897             const std::string result_str = ToString(ai_result);
1898             EXPECT_TRUE(result_str == ADDR4 || result_str == ADDR6)
1899                     << ", result_str='" << result_str << "'";
1900         } else if (config.method == GETADDRINFOFORNET) {
1901             addrinfo* raw_ai_result = nullptr;
1902             EXPECT_EQ(0, android_getaddrinfofornet(host_name, /*servname=*/nullptr,
1903                                                    /*hints=*/nullptr, BYPASS_NETID, MARK_UNSET,
1904                                                    &raw_ai_result));
1905             ai_result.reset(raw_ai_result);
1906 
1907             EXPECT_LE(1U, GetNumQueries(dns, host_name));
1908             // Could be A or AAAA
1909             const std::string result_str = ToString(ai_result);
1910             EXPECT_TRUE(result_str == ADDR4 || result_str == ADDR6)
1911                     << ", result_str='" << result_str << "'";
1912         }
1913 
1914         EXPECT_EQ(0, tls.queries());
1915 
1916         // Clear per-process resolv netid.
1917         ASSERT_EQ(0, setNetworkForResolv(NETID_UNSET));
1918         dns.clearQueries();
1919     }
1920 }
1921 
TEST_F(ResolverTest,StrictMode_NoTlsServers)1922 TEST_F(ResolverTest, StrictMode_NoTlsServers) {
1923     constexpr char cleartext_addr[] = "127.0.0.53";
1924     const std::vector<std::string> servers = {cleartext_addr};
1925     constexpr char host_name[] = "strictmode.notlsips.example.com.";
1926     const std::vector<DnsRecord> records = {
1927             {host_name, ns_type::ns_t_a, "1.2.3.4"},
1928             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1929     };
1930 
1931     test::DNSResponder dns(cleartext_addr);
1932     StartDns(dns, records);
1933 
1934     ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
1935                                                kDefaultIncorrectPrivateDnsHostName));
1936 
1937     addrinfo* ai_result = nullptr;
1938     EXPECT_NE(0, getaddrinfo(host_name, nullptr, nullptr, &ai_result));
1939     EXPECT_EQ(0U, GetNumQueries(dns, host_name));
1940 }
1941 
1942 namespace {
1943 
getAsyncResponse(int fd,int * rcode,uint8_t * buf,int bufLen)1944 int getAsyncResponse(int fd, int* rcode, uint8_t* buf, int bufLen) {
1945     struct pollfd wait_fd[1];
1946     wait_fd[0].fd = fd;
1947     wait_fd[0].events = POLLIN;
1948     short revents;
1949     int ret;
1950 
1951     ret = poll(wait_fd, 1, -1);
1952     revents = wait_fd[0].revents;
1953     if (revents & POLLIN) {
1954         int n = resNetworkResult(fd, rcode, buf, bufLen);
1955         // Verify that resNetworkResult() closed the fd
1956         char dummy;
1957         EXPECT_EQ(-1, read(fd, &dummy, sizeof dummy));
1958         EXPECT_EQ(EBADF, errno);
1959         return n;
1960     }
1961     return -1;
1962 }
1963 
toString(uint8_t * buf,int bufLen,int ipType)1964 std::string toString(uint8_t* buf, int bufLen, int ipType) {
1965     ns_msg handle;
1966     int ancount, n = 0;
1967     ns_rr rr;
1968 
1969     if (ns_initparse((const uint8_t*)buf, bufLen, &handle) >= 0) {
1970         ancount = ns_msg_count(handle, ns_s_an);
1971         if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1972             const uint8_t* rdata = ns_rr_rdata(rr);
1973             char buffer[INET6_ADDRSTRLEN];
1974             if (inet_ntop(ipType, (const char*)rdata, buffer, sizeof(buffer))) {
1975                 return buffer;
1976             }
1977         }
1978     }
1979     return "";
1980 }
1981 
dns_open_proxy()1982 int dns_open_proxy() {
1983     int s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
1984     if (s == -1) {
1985         return -1;
1986     }
1987     const int one = 1;
1988     setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
1989 
1990     static const struct sockaddr_un proxy_addr = {
1991             .sun_family = AF_UNIX,
1992             .sun_path = "/dev/socket/dnsproxyd",
1993     };
1994 
1995     if (TEMP_FAILURE_RETRY(connect(s, (const struct sockaddr*)&proxy_addr, sizeof(proxy_addr))) !=
1996         0) {
1997         close(s);
1998         return -1;
1999     }
2000 
2001     return s;
2002 }
2003 
expectAnswersValid(int fd,int ipType,const std::string & expectedAnswer)2004 void expectAnswersValid(int fd, int ipType, const std::string& expectedAnswer) {
2005     int rcode = -1;
2006     uint8_t buf[MAXPACKET] = {};
2007 
2008     int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2009     EXPECT_GT(res, 0);
2010     EXPECT_EQ(expectedAnswer, toString(buf, res, ipType));
2011 }
2012 
expectAnswersNotValid(int fd,int expectedErrno)2013 void expectAnswersNotValid(int fd, int expectedErrno) {
2014     int rcode = -1;
2015     uint8_t buf[MAXPACKET] = {};
2016 
2017     int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2018     EXPECT_EQ(expectedErrno, res);
2019 }
2020 
2021 }  // namespace
2022 
TEST_F(ResolverTest,Async_NormalQueryV4V6)2023 TEST_F(ResolverTest, Async_NormalQueryV4V6) {
2024     constexpr char listen_addr[] = "127.0.0.4";
2025     constexpr char host_name[] = "howdy.example.com.";
2026     const std::vector<DnsRecord> records = {
2027             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2028             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2029     };
2030 
2031     test::DNSResponder dns(listen_addr);
2032     StartDns(dns, records);
2033     std::vector<std::string> servers = {listen_addr};
2034     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2035 
2036     int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2037     int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2038     EXPECT_TRUE(fd1 != -1);
2039     EXPECT_TRUE(fd2 != -1);
2040 
2041     uint8_t buf[MAXPACKET] = {};
2042     int rcode;
2043     int res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
2044     EXPECT_GT(res, 0);
2045     EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
2046 
2047     res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
2048     EXPECT_GT(res, 0);
2049     EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2050 
2051     EXPECT_EQ(2U, GetNumQueries(dns, host_name));
2052 
2053     // Re-query verify cache works
2054     fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2055     fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2056 
2057     EXPECT_TRUE(fd1 != -1);
2058     EXPECT_TRUE(fd2 != -1);
2059 
2060     res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
2061     EXPECT_GT(res, 0);
2062     EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
2063 
2064     res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
2065     EXPECT_GT(res, 0);
2066     EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2067 
2068     EXPECT_EQ(2U, GetNumQueries(dns, host_name));
2069 }
2070 
TEST_F(ResolverTest,Async_BadQuery)2071 TEST_F(ResolverTest, Async_BadQuery) {
2072     constexpr char listen_addr[] = "127.0.0.4";
2073     constexpr char host_name[] = "howdy.example.com.";
2074     const std::vector<DnsRecord> records = {
2075             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2076             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2077     };
2078 
2079     test::DNSResponder dns(listen_addr);
2080     StartDns(dns, records);
2081     std::vector<std::string> servers = {listen_addr};
2082     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2083 
2084     static struct {
2085         int fd;
2086         const char* dname;
2087         const int queryType;
2088         const int expectRcode;
2089     } kTestData[] = {
2090             {-1, "", ns_t_aaaa, 0},
2091             {-1, "as65ass46", ns_t_aaaa, 0},
2092             {-1, "454564564564", ns_t_aaaa, 0},
2093             {-1, "h645235", ns_t_a, 0},
2094             {-1, "www.google.com", ns_t_a, 0},
2095     };
2096 
2097     for (auto& td : kTestData) {
2098         SCOPED_TRACE(td.dname);
2099         td.fd = resNetworkQuery(TEST_NETID, td.dname, ns_c_in, td.queryType, 0);
2100         EXPECT_TRUE(td.fd != -1);
2101     }
2102 
2103     // dns_responder return empty resp(packet only contains query part) with no error currently
2104     for (const auto& td : kTestData) {
2105         uint8_t buf[MAXPACKET] = {};
2106         int rcode;
2107         SCOPED_TRACE(td.dname);
2108         int res = getAsyncResponse(td.fd, &rcode, buf, MAXPACKET);
2109         EXPECT_GT(res, 0);
2110         EXPECT_EQ(rcode, td.expectRcode);
2111     }
2112 }
2113 
TEST_F(ResolverTest,Async_EmptyAnswer)2114 TEST_F(ResolverTest, Async_EmptyAnswer) {
2115     constexpr char listen_addr[] = "127.0.0.4";
2116     constexpr char host_name[] = "howdy.example.com.";
2117     const std::vector<DnsRecord> records = {
2118             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2119             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2120     };
2121 
2122     test::DNSResponder dns(listen_addr);
2123     StartDns(dns, records);
2124     std::vector<std::string> servers = {listen_addr};
2125     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2126 
2127     // TODO: Disable retry to make this test explicit.
2128     auto& cv = dns.getCv();
2129     auto& cvMutex = dns.getCvMutex();
2130     int fd1;
2131     // Wait on the condition variable to ensure that the DNS server has handled our first query.
2132     {
2133         std::unique_lock lk(cvMutex);
2134         fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2135         EXPECT_TRUE(fd1 != -1);
2136         EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lk, std::chrono::seconds(1)));
2137     }
2138 
2139     dns.setResponseProbability(0.0);
2140 
2141     int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2142     EXPECT_TRUE(fd2 != -1);
2143 
2144     int fd3 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2145     EXPECT_TRUE(fd3 != -1);
2146 
2147     uint8_t buf[MAXPACKET] = {};
2148     int rcode;
2149 
2150     // expect no response
2151     int res = getAsyncResponse(fd3, &rcode, buf, MAXPACKET);
2152     EXPECT_EQ(-ETIMEDOUT, res);
2153 
2154     // expect no response
2155     memset(buf, 0, MAXPACKET);
2156     res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
2157     EXPECT_EQ(-ETIMEDOUT, res);
2158 
2159     dns.setResponseProbability(1.0);
2160 
2161     int fd4 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2162     EXPECT_TRUE(fd4 != -1);
2163 
2164     memset(buf, 0, MAXPACKET);
2165     res = getAsyncResponse(fd4, &rcode, buf, MAXPACKET);
2166     EXPECT_GT(res, 0);
2167     EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2168 
2169     memset(buf, 0, MAXPACKET);
2170     res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
2171     EXPECT_GT(res, 0);
2172     EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
2173 }
2174 
TEST_F(ResolverTest,Async_MalformedQuery)2175 TEST_F(ResolverTest, Async_MalformedQuery) {
2176     constexpr char listen_addr[] = "127.0.0.4";
2177     constexpr char host_name[] = "howdy.example.com.";
2178     const std::vector<DnsRecord> records = {
2179             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2180             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2181     };
2182 
2183     test::DNSResponder dns(listen_addr);
2184     StartDns(dns, records);
2185     std::vector<std::string> servers = {listen_addr};
2186     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2187 
2188     int fd = dns_open_proxy();
2189     EXPECT_TRUE(fd > 0);
2190 
2191     const std::string badMsg = "16-52512#";
2192     static const struct {
2193         const std::string cmd;
2194         const int expectErr;
2195     } kTestData[] = {
2196             // Too few arguments
2197             {"resnsend " + badMsg + '\0', -EINVAL},
2198             // Bad netId
2199             {"resnsend badnetId 0 " + badMsg + '\0', -EINVAL},
2200             // Bad raw data
2201             {"resnsend " + std::to_string(TEST_NETID) + " 0 " + badMsg + '\0', -EILSEQ},
2202     };
2203 
2204     for (unsigned int i = 0; i < std::size(kTestData); i++) {
2205         auto& td = kTestData[i];
2206         SCOPED_TRACE(td.cmd);
2207         ssize_t rc = TEMP_FAILURE_RETRY(write(fd, td.cmd.c_str(), td.cmd.size()));
2208         EXPECT_EQ(rc, static_cast<ssize_t>(td.cmd.size()));
2209 
2210         int32_t tmp;
2211         rc = TEMP_FAILURE_RETRY(read(fd, &tmp, sizeof(tmp)));
2212         EXPECT_TRUE(rc > 0);
2213         EXPECT_EQ(static_cast<int>(ntohl(tmp)), td.expectErr);
2214     }
2215     // Normal query with answer buffer
2216     // This is raw data of query "howdy.example.com" type 1 class 1
2217     std::string query = "81sBAAABAAAAAAAABWhvd2R5B2V4YW1wbGUDY29tAAABAAE=";
2218     std::string cmd = "resnsend " + std::to_string(TEST_NETID) + " 0 " + query + '\0';
2219     ssize_t rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
2220     EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
2221 
2222     uint8_t smallBuf[1] = {};
2223     int rcode;
2224     rc = getAsyncResponse(fd, &rcode, smallBuf, 1);
2225     EXPECT_EQ(-EMSGSIZE, rc);
2226 
2227     // Do the normal test with large buffer again
2228     fd = dns_open_proxy();
2229     EXPECT_TRUE(fd > 0);
2230     rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
2231     EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
2232     uint8_t buf[MAXPACKET] = {};
2233     rc = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2234     EXPECT_EQ("1.2.3.4", toString(buf, rc, AF_INET));
2235 }
2236 
TEST_F(ResolverTest,Async_CacheFlags)2237 TEST_F(ResolverTest, Async_CacheFlags) {
2238     constexpr char listen_addr[] = "127.0.0.4";
2239     constexpr char host_name1[] = "howdy.example.com.";
2240     constexpr char host_name2[] = "howdy.example2.com.";
2241     constexpr char host_name3[] = "howdy.example3.com.";
2242     const std::vector<DnsRecord> records = {
2243             {host_name1, ns_type::ns_t_a, "1.2.3.4"}, {host_name1, ns_type::ns_t_aaaa, "::1.2.3.4"},
2244             {host_name2, ns_type::ns_t_a, "1.2.3.5"}, {host_name2, ns_type::ns_t_aaaa, "::1.2.3.5"},
2245             {host_name3, ns_type::ns_t_a, "1.2.3.6"}, {host_name3, ns_type::ns_t_aaaa, "::1.2.3.6"},
2246     };
2247 
2248     test::DNSResponder dns(listen_addr);
2249     StartDns(dns, records);
2250     std::vector<std::string> servers = {listen_addr};
2251     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2252 
2253     // ANDROID_RESOLV_NO_CACHE_STORE
2254     int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2255                               ANDROID_RESOLV_NO_CACHE_STORE);
2256     EXPECT_TRUE(fd1 != -1);
2257     int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2258                               ANDROID_RESOLV_NO_CACHE_STORE);
2259     EXPECT_TRUE(fd2 != -1);
2260     int fd3 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2261                               ANDROID_RESOLV_NO_CACHE_STORE);
2262     EXPECT_TRUE(fd3 != -1);
2263 
2264     expectAnswersValid(fd3, AF_INET, "1.2.3.4");
2265     expectAnswersValid(fd2, AF_INET, "1.2.3.4");
2266     expectAnswersValid(fd1, AF_INET, "1.2.3.4");
2267 
2268     // No cache exists, expect 3 queries
2269     EXPECT_EQ(3U, GetNumQueries(dns, host_name1));
2270 
2271     // Raise a query with no flags to ensure no cache exists. Also make an cache entry for the
2272     // query.
2273     fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2274 
2275     EXPECT_TRUE(fd1 != -1);
2276 
2277     expectAnswersValid(fd1, AF_INET, "1.2.3.4");
2278 
2279     // Expect 4 queries because there should be no cache before this query.
2280     EXPECT_EQ(4U, GetNumQueries(dns, host_name1));
2281 
2282     // Now we have the cache entry, re-query with ANDROID_RESOLV_NO_CACHE_STORE to ensure
2283     // that ANDROID_RESOLV_NO_CACHE_STORE implied ANDROID_RESOLV_NO_CACHE_LOOKUP.
2284     fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2285                           ANDROID_RESOLV_NO_CACHE_STORE);
2286     EXPECT_TRUE(fd1 != -1);
2287     expectAnswersValid(fd1, AF_INET, "1.2.3.4");
2288     // Expect 5 queries because we shouldn't do cache lookup for the query which has
2289     // ANDROID_RESOLV_NO_CACHE_STORE.
2290     EXPECT_EQ(5U, GetNumQueries(dns, host_name1));
2291 
2292     // ANDROID_RESOLV_NO_CACHE_LOOKUP
2293     fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2294                           ANDROID_RESOLV_NO_CACHE_LOOKUP);
2295     fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2296                           ANDROID_RESOLV_NO_CACHE_LOOKUP);
2297 
2298     EXPECT_TRUE(fd1 != -1);
2299     EXPECT_TRUE(fd2 != -1);
2300 
2301     expectAnswersValid(fd2, AF_INET, "1.2.3.4");
2302     expectAnswersValid(fd1, AF_INET, "1.2.3.4");
2303 
2304     // Cache was skipped, expect 2 more queries.
2305     EXPECT_EQ(7U, GetNumQueries(dns, host_name1));
2306 
2307     // Re-query verify cache works
2308     fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2309     EXPECT_TRUE(fd1 != -1);
2310     expectAnswersValid(fd1, AF_INET, "1.2.3.4");
2311 
2312     // Cache hits,  expect still 7 queries
2313     EXPECT_EQ(7U, GetNumQueries(dns, host_name1));
2314 
2315     // Start to verify if ANDROID_RESOLV_NO_CACHE_LOOKUP does write response into cache
2316     dns.clearQueries();
2317 
2318     fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa,
2319                           ANDROID_RESOLV_NO_CACHE_LOOKUP);
2320     fd2 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa,
2321                           ANDROID_RESOLV_NO_CACHE_LOOKUP);
2322 
2323     EXPECT_TRUE(fd1 != -1);
2324     EXPECT_TRUE(fd2 != -1);
2325 
2326     expectAnswersValid(fd2, AF_INET6, "::1.2.3.5");
2327     expectAnswersValid(fd1, AF_INET6, "::1.2.3.5");
2328 
2329     // Skip cache, expect 2 queries
2330     EXPECT_EQ(2U, GetNumQueries(dns, host_name2));
2331 
2332     // Re-query without flags
2333     fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa, 0);
2334     fd2 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa, 0);
2335 
2336     EXPECT_TRUE(fd1 != -1);
2337     EXPECT_TRUE(fd2 != -1);
2338 
2339     expectAnswersValid(fd2, AF_INET6, "::1.2.3.5");
2340     expectAnswersValid(fd1, AF_INET6, "::1.2.3.5");
2341 
2342     // Cache hits, expect still 2 queries
2343     EXPECT_EQ(2U, GetNumQueries(dns, host_name2));
2344 
2345     // Test both ANDROID_RESOLV_NO_CACHE_STORE and ANDROID_RESOLV_NO_CACHE_LOOKUP are set
2346     dns.clearQueries();
2347 
2348     // Make sure that the cache of "howdy.example3.com" exists.
2349     fd1 = resNetworkQuery(TEST_NETID, "howdy.example3.com", ns_c_in, ns_t_aaaa, 0);
2350     EXPECT_TRUE(fd1 != -1);
2351     expectAnswersValid(fd1, AF_INET6, "::1.2.3.6");
2352     EXPECT_EQ(1U, GetNumQueries(dns, host_name3));
2353 
2354     // Re-query with testFlags
2355     const int testFlag = ANDROID_RESOLV_NO_CACHE_STORE | ANDROID_RESOLV_NO_CACHE_LOOKUP;
2356     fd1 = resNetworkQuery(TEST_NETID, "howdy.example3.com", ns_c_in, ns_t_aaaa, testFlag);
2357     EXPECT_TRUE(fd1 != -1);
2358     expectAnswersValid(fd1, AF_INET6, "::1.2.3.6");
2359     // Expect cache lookup is skipped.
2360     EXPECT_EQ(2U, GetNumQueries(dns, host_name3));
2361 
2362     // Do another query with testFlags
2363     fd1 = resNetworkQuery(TEST_NETID, "howdy.example3.com", ns_c_in, ns_t_a, testFlag);
2364     EXPECT_TRUE(fd1 != -1);
2365     expectAnswersValid(fd1, AF_INET, "1.2.3.6");
2366     // Expect cache lookup is skipped.
2367     EXPECT_EQ(3U, GetNumQueries(dns, host_name3));
2368 
2369     // Re-query with no flags
2370     fd1 = resNetworkQuery(TEST_NETID, "howdy.example3.com", ns_c_in, ns_t_a, 0);
2371     EXPECT_TRUE(fd1 != -1);
2372     expectAnswersValid(fd1, AF_INET, "1.2.3.6");
2373     // Expect no cache hit because cache storing is also skipped in previous query.
2374     EXPECT_EQ(4U, GetNumQueries(dns, host_name3));
2375 }
2376 
TEST_F(ResolverTest,Async_NoCacheStoreFlagDoesNotRefreshStaleCacheEntry)2377 TEST_F(ResolverTest, Async_NoCacheStoreFlagDoesNotRefreshStaleCacheEntry) {
2378     constexpr char listen_addr[] = "127.0.0.4";
2379     constexpr char host_name[] = "howdy.example.com.";
2380     const std::vector<DnsRecord> records = {
2381             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2382     };
2383 
2384     test::DNSResponder dns(listen_addr);
2385     StartDns(dns, records);
2386     std::vector<std::string> servers = {listen_addr};
2387     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2388 
2389     const unsigned SHORT_TTL_SEC = 1;
2390     dns.setTtl(SHORT_TTL_SEC);
2391 
2392     // Refer to b/148842821 for the purpose of below test steps.
2393     // Basically, this test is used to ensure stale cache case is handled
2394     // correctly with ANDROID_RESOLV_NO_CACHE_STORE.
2395     int fd = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2396     EXPECT_TRUE(fd != -1);
2397     expectAnswersValid(fd, AF_INET, "1.2.3.4");
2398 
2399     EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2400     dns.clearQueries();
2401 
2402     // Wait until cache expired
2403     sleep(SHORT_TTL_SEC + 0.5);
2404 
2405     // Now request the same hostname again.
2406     // We should see a new DNS query because the entry in cache has become stale.
2407     // Due to ANDROID_RESOLV_NO_CACHE_STORE, this query must *not* refresh that stale entry.
2408     fd = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2409                          ANDROID_RESOLV_NO_CACHE_STORE);
2410     EXPECT_TRUE(fd != -1);
2411     expectAnswersValid(fd, AF_INET, "1.2.3.4");
2412     EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2413     dns.clearQueries();
2414 
2415     // If the cache is still stale, we expect to see one more DNS query
2416     // (this time the cache will be refreshed, but we're not checking for it).
2417     fd = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2418     EXPECT_TRUE(fd != -1);
2419     expectAnswersValid(fd, AF_INET, "1.2.3.4");
2420     EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2421 }
2422 
TEST_F(ResolverTest,Async_NoRetryFlag)2423 TEST_F(ResolverTest, Async_NoRetryFlag) {
2424     constexpr char listen_addr0[] = "127.0.0.4";
2425     constexpr char listen_addr1[] = "127.0.0.6";
2426     constexpr char host_name[] = "howdy.example.com.";
2427     const std::vector<DnsRecord> records = {
2428             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2429             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2430     };
2431 
2432     test::DNSResponder dns0(listen_addr0);
2433     test::DNSResponder dns1(listen_addr1);
2434     StartDns(dns0, records);
2435     StartDns(dns1, records);
2436     ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr0, listen_addr1}));
2437 
2438     dns0.clearQueries();
2439     dns1.clearQueries();
2440 
2441     dns0.setResponseProbability(0.0);
2442     dns1.setResponseProbability(0.0);
2443 
2444     int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2445                               ANDROID_RESOLV_NO_RETRY);
2446     EXPECT_TRUE(fd1 != -1);
2447 
2448     int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa,
2449                               ANDROID_RESOLV_NO_RETRY);
2450     EXPECT_TRUE(fd2 != -1);
2451 
2452     // expect no response
2453     expectAnswersNotValid(fd1, -ETIMEDOUT);
2454     expectAnswersNotValid(fd2, -ETIMEDOUT);
2455 
2456     // No retry case, expect total 2 queries. The server is selected randomly.
2457     EXPECT_EQ(2U, GetNumQueries(dns0, host_name) + GetNumQueries(dns1, host_name));
2458 
2459     dns0.clearQueries();
2460     dns1.clearQueries();
2461 
2462     fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2463     EXPECT_TRUE(fd1 != -1);
2464 
2465     fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2466     EXPECT_TRUE(fd2 != -1);
2467 
2468     // expect no response
2469     expectAnswersNotValid(fd1, -ETIMEDOUT);
2470     expectAnswersNotValid(fd2, -ETIMEDOUT);
2471 
2472     // Retry case, expect 4 queries
2473     EXPECT_EQ(4U, GetNumQueries(dns0, host_name));
2474     EXPECT_EQ(4U, GetNumQueries(dns1, host_name));
2475 }
2476 
TEST_F(ResolverTest,Async_VerifyQueryID)2477 TEST_F(ResolverTest, Async_VerifyQueryID) {
2478     constexpr char listen_addr[] = "127.0.0.4";
2479     constexpr char host_name[] = "howdy.example.com.";
2480     const std::vector<DnsRecord> records = {
2481             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2482             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2483     };
2484 
2485     test::DNSResponder dns(listen_addr);
2486     StartDns(dns, records);
2487     std::vector<std::string> servers = {listen_addr};
2488     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2489 
2490     const uint8_t queryBuf1[] = {
2491             /* Header */
2492             0x55, 0x66, /* Transaction ID */
2493             0x01, 0x00, /* Flags */
2494             0x00, 0x01, /* Questions */
2495             0x00, 0x00, /* Answer RRs */
2496             0x00, 0x00, /* Authority RRs */
2497             0x00, 0x00, /* Additional RRs */
2498             /* Queries */
2499             0x05, 0x68, 0x6f, 0x77, 0x64, 0x79, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
2500             0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */
2501             0x00, 0x01,                   /* Type */
2502             0x00, 0x01                    /* Class */
2503     };
2504 
2505     int fd = resNetworkSend(TEST_NETID, queryBuf1, sizeof(queryBuf1), 0);
2506     EXPECT_TRUE(fd != -1);
2507 
2508     uint8_t buf[MAXPACKET] = {};
2509     int rcode;
2510 
2511     int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2512     EXPECT_GT(res, 0);
2513     EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2514 
2515     auto hp = reinterpret_cast<HEADER*>(buf);
2516     EXPECT_EQ(21862U, htons(hp->id));
2517 
2518     EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2519 
2520     const uint8_t queryBuf2[] = {
2521             /* Header */
2522             0x00, 0x53, /* Transaction ID */
2523             0x01, 0x00, /* Flags */
2524             0x00, 0x01, /* Questions */
2525             0x00, 0x00, /* Answer RRs */
2526             0x00, 0x00, /* Authority RRs */
2527             0x00, 0x00, /* Additional RRs */
2528             /* Queries */
2529             0x05, 0x68, 0x6f, 0x77, 0x64, 0x79, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
2530             0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */
2531             0x00, 0x01,                   /* Type */
2532             0x00, 0x01                    /* Class */
2533     };
2534 
2535     // Re-query verify cache works and query id is correct
2536     fd = resNetworkSend(TEST_NETID, queryBuf2, sizeof(queryBuf2), 0);
2537 
2538     EXPECT_TRUE(fd != -1);
2539 
2540     res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2541     EXPECT_GT(res, 0);
2542     EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2543 
2544     EXPECT_EQ(0x0053U, htons(hp->id));
2545 
2546     EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2547 }
2548 
2549 // This test checks that the resolver should not generate the request containing OPT RR when using
2550 // cleartext DNS. If we query the DNS server not supporting EDNS0 and it reponds with
2551 // FORMERR_ON_EDNS, we will fallback to no EDNS0 and try again. If the server does no response, we
2552 // won't retry so that we get no answer.
TEST_F(ResolverTest,BrokenEdns)2553 TEST_F(ResolverTest, BrokenEdns) {
2554     typedef test::DNSResponder::Edns Edns;
2555     enum ExpectResult { EXPECT_FAILURE, EXPECT_SUCCESS };
2556 
2557     // Perform cleartext query in off mode.
2558     const char OFF[] = "off";
2559 
2560     // Perform cleartext query when there's no private DNS server validated in opportunistic mode.
2561     const char OPPORTUNISTIC_UDP[] = "opportunistic_udp";
2562 
2563     // Perform cleartext query when there is a private DNS server validated in opportunistic mode.
2564     const char OPPORTUNISTIC_FALLBACK_UDP[] = "opportunistic_fallback_udp";
2565 
2566     // Perform cyphertext query in opportunistic mode.
2567     const char OPPORTUNISTIC_TLS[] = "opportunistic_tls";
2568 
2569     // Perform cyphertext query in strict mode.
2570     const char STRICT[] = "strict";
2571 
2572     const char GETHOSTBYNAME[] = "gethostbyname";
2573     const char GETADDRINFO[] = "getaddrinfo";
2574     const char ADDR4[] = "192.0.2.1";
2575     const char CLEARTEXT_ADDR[] = "127.0.0.53";
2576     const char CLEARTEXT_PORT[] = "53";
2577     const char TLS_PORT[] = "853";
2578     const std::vector<std::string> servers = {CLEARTEXT_ADDR};
2579     ResolverParamsParcel paramsForCleanup = DnsResponderClient::GetDefaultResolverParamsParcel();
2580     paramsForCleanup.servers.clear();
2581     paramsForCleanup.tlsServers.clear();
2582 
2583     test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, ns_rcode::ns_r_servfail);
2584     ASSERT_TRUE(dns.startServer());
2585 
2586     test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2587 
2588     // clang-format off
2589     static const struct TestConfig {
2590         std::string mode;
2591         std::string method;
2592         Edns edns;
2593         ExpectResult expectResult;
2594 
2595         std::string asHostName() const {
2596             const char* ednsString;
2597             switch (edns) {
2598                 case Edns::ON:
2599                     ednsString = "ednsOn";
2600                     break;
2601                 case Edns::FORMERR_ON_EDNS:
2602                     ednsString = "ednsFormerr";
2603                     break;
2604                 case Edns::DROP:
2605                     ednsString = "ednsDrop";
2606                     break;
2607                 default:
2608                     ednsString = "";
2609                     break;
2610             }
2611             return StringPrintf("%s.%s.%s.", mode.c_str(), method.c_str(), ednsString);
2612         }
2613     } testConfigs[] = {
2614             // In OPPORTUNISTIC_TLS, if the DNS server doesn't support EDNS0 but TLS, the lookup
2615             // fails. Could such server exist? if so, we might need to fix it to fallback to
2616             // cleartext query. If the server still make no response for the queries with EDNS0, we
2617             // might also need to fix it to retry without EDNS0.
2618             // Another thing is that {OPPORTUNISTIC_TLS, Edns::DROP} and {STRICT, Edns::DROP} are
2619             // commented out since TLS timeout is not configurable.
2620             // TODO: Uncomment them after TLS timeout is configurable.
2621             {OFF,                        GETHOSTBYNAME, Edns::ON,      EXPECT_SUCCESS},
2622             {OPPORTUNISTIC_UDP,          GETHOSTBYNAME, Edns::ON,      EXPECT_SUCCESS},
2623             {OPPORTUNISTIC_FALLBACK_UDP, GETHOSTBYNAME, Edns::ON,      EXPECT_SUCCESS},
2624             {OPPORTUNISTIC_TLS,          GETHOSTBYNAME, Edns::ON,      EXPECT_SUCCESS},
2625             {STRICT,                     GETHOSTBYNAME, Edns::ON,      EXPECT_SUCCESS},
2626             {OFF,                        GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2627             {OPPORTUNISTIC_UDP,          GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2628             {OPPORTUNISTIC_FALLBACK_UDP, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2629             {OPPORTUNISTIC_TLS,          GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
2630             {STRICT,                     GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
2631             {OFF,                        GETHOSTBYNAME, Edns::DROP,    EXPECT_SUCCESS},
2632             {OPPORTUNISTIC_UDP,          GETHOSTBYNAME, Edns::DROP,    EXPECT_SUCCESS},
2633 
2634             // The failure is due to no retry on timeout. Maybe fix it?
2635             {OPPORTUNISTIC_FALLBACK_UDP, GETHOSTBYNAME, Edns::DROP,    EXPECT_FAILURE},
2636 
2637             //{OPPORTUNISTIC_TLS,        GETHOSTBYNAME, Edns::DROP,    EXPECT_FAILURE},
2638             //{STRICT,                   GETHOSTBYNAME, Edns::DROP,    EXPECT_FAILURE},
2639             {OFF,                        GETADDRINFO,   Edns::ON,      EXPECT_SUCCESS},
2640             {OPPORTUNISTIC_UDP,          GETADDRINFO,   Edns::ON,      EXPECT_SUCCESS},
2641             {OPPORTUNISTIC_FALLBACK_UDP, GETADDRINFO,   Edns::ON,      EXPECT_SUCCESS},
2642             {OPPORTUNISTIC_TLS,          GETADDRINFO,   Edns::ON,      EXPECT_SUCCESS},
2643             {STRICT,                     GETADDRINFO,   Edns::ON,      EXPECT_SUCCESS},
2644             {OFF,                        GETADDRINFO,   Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2645             {OPPORTUNISTIC_UDP,          GETADDRINFO,   Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2646             {OPPORTUNISTIC_FALLBACK_UDP, GETADDRINFO,   Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2647             {OPPORTUNISTIC_TLS,          GETADDRINFO,   Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
2648             {STRICT,                     GETADDRINFO,   Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
2649             {OFF,                        GETADDRINFO,   Edns::DROP,    EXPECT_SUCCESS},
2650             {OPPORTUNISTIC_UDP,          GETADDRINFO,   Edns::DROP,    EXPECT_SUCCESS},
2651 
2652             // The failure is due to no retry on timeout. Maybe fix it?
2653             {OPPORTUNISTIC_FALLBACK_UDP, GETADDRINFO,   Edns::DROP,    EXPECT_FAILURE},
2654 
2655             //{OPPORTUNISTIC_TLS, GETADDRINFO,   Edns::DROP,   EXPECT_FAILURE},
2656             //{STRICT,            GETADDRINFO,   Edns::DROP,   EXPECT_FAILURE},
2657     };
2658     // clang-format on
2659 
2660     for (const auto& config : testConfigs) {
2661         const std::string testHostName = config.asHostName();
2662         SCOPED_TRACE(testHostName);
2663 
2664         const char* host_name = testHostName.c_str();
2665         dns.addMapping(host_name, ns_type::ns_t_a, ADDR4);
2666         dns.setEdns(config.edns);
2667 
2668         if (config.mode == OFF) {
2669             if (tls.running()) {
2670                 ASSERT_TRUE(tls.stopServer());
2671             }
2672             ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2673         } else if (config.mode == OPPORTUNISTIC_UDP) {
2674             if (tls.running()) {
2675                 ASSERT_TRUE(tls.stopServer());
2676             }
2677             ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
2678                                                        kDefaultParams, ""));
2679             EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), false));
2680         } else if (config.mode == OPPORTUNISTIC_TLS || config.mode == OPPORTUNISTIC_FALLBACK_UDP) {
2681             if (!tls.running()) {
2682                 ASSERT_TRUE(tls.startServer());
2683             }
2684             ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
2685                                                        kDefaultParams, ""));
2686             EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
2687 
2688             if (config.mode == OPPORTUNISTIC_FALLBACK_UDP) {
2689                 // Force the resolver to fallback to cleartext queries.
2690                 ASSERT_TRUE(tls.stopServer());
2691             }
2692         } else if (config.mode == STRICT) {
2693             if (!tls.running()) {
2694                 ASSERT_TRUE(tls.startServer());
2695             }
2696             ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
2697                                                        kDefaultParams, kDefaultPrivateDnsHostName));
2698             EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
2699         }
2700 
2701         if (config.method == GETHOSTBYNAME) {
2702             const hostent* h_result = gethostbyname(host_name);
2703             if (config.expectResult == EXPECT_SUCCESS) {
2704                 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2705                 ASSERT_TRUE(h_result != nullptr);
2706                 ASSERT_EQ(4, h_result->h_length);
2707                 ASSERT_FALSE(h_result->h_addr_list[0] == nullptr);
2708                 EXPECT_EQ(ADDR4, ToString(h_result));
2709                 EXPECT_TRUE(h_result->h_addr_list[1] == nullptr);
2710             } else {
2711                 EXPECT_EQ(0U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
2712                 ASSERT_TRUE(h_result == nullptr);
2713                 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2714             }
2715         } else if (config.method == GETADDRINFO) {
2716             ScopedAddrinfo ai_result;
2717             addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2718             ai_result = safe_getaddrinfo(host_name, nullptr, &hints);
2719             if (config.expectResult == EXPECT_SUCCESS) {
2720                 EXPECT_TRUE(ai_result != nullptr);
2721                 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2722                 const std::string result_str = ToString(ai_result);
2723                 EXPECT_EQ(ADDR4, result_str);
2724             } else {
2725                 EXPECT_TRUE(ai_result == nullptr);
2726                 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
2727             }
2728         } else {
2729             FAIL() << "Unsupported query method: " << config.method;
2730         }
2731 
2732         tls.clearQueries();
2733         dns.clearQueries();
2734 
2735         // Clear the setup to force the resolver to validate private DNS servers in every test.
2736         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(paramsForCleanup));
2737     }
2738 }
2739 
2740 // DNS-over-TLS validation success, but server does not respond to TLS query after a while.
2741 // Resolver should have a reasonable number of retries instead of spinning forever. We don't have
2742 // an efficient way to know if resolver is stuck in an infinite loop. However, test case will be
2743 // failed due to timeout.
TEST_F(ResolverTest,UnstableTls)2744 TEST_F(ResolverTest, UnstableTls) {
2745     const char CLEARTEXT_ADDR[] = "127.0.0.53";
2746     const char CLEARTEXT_PORT[] = "53";
2747     const char TLS_PORT[] = "853";
2748     const char* host_name1 = "nonexistent1.example.com.";
2749     const char* host_name2 = "nonexistent2.example.com.";
2750     const std::vector<std::string> servers = {CLEARTEXT_ADDR};
2751 
2752     test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, ns_rcode::ns_r_servfail);
2753     ASSERT_TRUE(dns.startServer());
2754     dns.setEdns(test::DNSResponder::Edns::FORMERR_ON_EDNS);
2755     test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2756     ASSERT_TRUE(tls.startServer());
2757     ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
2758     EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
2759 
2760     // Shutdown TLS server to get an error. It's similar to no response case but without waiting.
2761     tls.stopServer();
2762 
2763     const hostent* h_result = gethostbyname(host_name1);
2764     EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
2765     ASSERT_TRUE(h_result == nullptr);
2766     ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2767 
2768     addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2769     ScopedAddrinfo ai_result = safe_getaddrinfo(host_name2, nullptr, &hints);
2770     EXPECT_TRUE(ai_result == nullptr);
2771     EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
2772 }
2773 
2774 // DNS-over-TLS validation success, but server does not respond to TLS query after a while.
2775 // Moreover, server responds RCODE=FORMERR even on non-EDNS query.
TEST_F(ResolverTest,BogusDnsServer)2776 TEST_F(ResolverTest, BogusDnsServer) {
2777     const char CLEARTEXT_ADDR[] = "127.0.0.53";
2778     const char CLEARTEXT_PORT[] = "53";
2779     const char TLS_PORT[] = "853";
2780     const char* host_name1 = "nonexistent1.example.com.";
2781     const char* host_name2 = "nonexistent2.example.com.";
2782     const std::vector<std::string> servers = {CLEARTEXT_ADDR};
2783 
2784     test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, ns_rcode::ns_r_servfail);
2785     ASSERT_TRUE(dns.startServer());
2786     test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2787     ASSERT_TRUE(tls.startServer());
2788     ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
2789     EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
2790 
2791     // Shutdown TLS server to get an error. It's similar to no response case but without waiting.
2792     tls.stopServer();
2793     dns.setEdns(test::DNSResponder::Edns::FORMERR_UNCOND);
2794 
2795     const hostent* h_result = gethostbyname(host_name1);
2796     EXPECT_EQ(0U, GetNumQueries(dns, host_name1));
2797     ASSERT_TRUE(h_result == nullptr);
2798     ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2799 
2800     addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2801     ScopedAddrinfo ai_result = safe_getaddrinfo(host_name2, nullptr, &hints);
2802     EXPECT_TRUE(ai_result == nullptr);
2803     EXPECT_EQ(0U, GetNumQueries(dns, host_name2));
2804 }
2805 
TEST_F(ResolverTest,GetAddrInfo_Dns64Synthesize)2806 TEST_F(ResolverTest, GetAddrInfo_Dns64Synthesize) {
2807     constexpr char listen_addr[] = "::1";
2808     constexpr char dns64_name[] = "ipv4only.arpa.";
2809     constexpr char host_name[] = "v4only.example.com.";
2810     const std::vector<DnsRecord> records = {
2811             {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2812             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2813     };
2814 
2815     test::DNSResponder dns(listen_addr);
2816     StartDns(dns, records);
2817 
2818     std::vector<std::string> servers = {listen_addr};
2819     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2820 
2821     // Start NAT64 prefix discovery and wait for it to complete.
2822     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2823     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
2824 
2825     // hints are necessary in order to let netd know which type of addresses the caller is
2826     // interested in.
2827     const addrinfo hints = {.ai_family = AF_UNSPEC};
2828     ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, &hints);
2829     EXPECT_TRUE(result != nullptr);
2830     // TODO: BUG: there should only be two queries, one AAAA (which returns no records) and one A
2831     // (which returns 1.2.3.4). But there is an extra AAAA.
2832     EXPECT_EQ(3U, GetNumQueries(dns, host_name));
2833 
2834     std::string result_str = ToString(result);
2835     EXPECT_EQ(result_str, "64:ff9b::102:304");
2836 
2837     // Stopping NAT64 prefix discovery disables synthesis.
2838     EXPECT_TRUE(mDnsClient.resolvService()->stopPrefix64Discovery(TEST_NETID).isOk());
2839     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_NOT_FOUND));
2840 
2841     dns.clearQueries();
2842 
2843     result = safe_getaddrinfo("v4only", nullptr, &hints);
2844     EXPECT_TRUE(result != nullptr);
2845     // TODO: BUG: there should only be one query, an AAAA (which returns no records), because the
2846     // A is already cached. But there is an extra AAAA.
2847     EXPECT_EQ(2U, GetNumQueries(dns, host_name));
2848 
2849     result_str = ToString(result);
2850     EXPECT_EQ(result_str, "1.2.3.4");
2851 }
2852 
TEST_F(ResolverTest,GetAddrInfo_Dns64QuerySpecified)2853 TEST_F(ResolverTest, GetAddrInfo_Dns64QuerySpecified) {
2854     constexpr char listen_addr[] = "::1";
2855     constexpr char dns64_name[] = "ipv4only.arpa.";
2856     constexpr char host_name[] = "v4only.example.com.";
2857     const std::vector<DnsRecord> records = {
2858             {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2859             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2860     };
2861 
2862     test::DNSResponder dns(listen_addr);
2863     StartDns(dns, records);
2864     const std::vector<std::string> servers = {listen_addr};
2865     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2866 
2867     // Start NAT64 prefix discovery and wait for it to complete.
2868     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2869     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
2870 
2871     // Ensure to synthesize AAAA if AF_INET6 is specified, and not to synthesize AAAA
2872     // in AF_INET case.
2873     addrinfo hints;
2874     memset(&hints, 0, sizeof(hints));
2875     hints.ai_family = AF_INET6;
2876     ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, &hints);
2877     EXPECT_TRUE(result != nullptr);
2878     std::string result_str = ToString(result);
2879     EXPECT_EQ(result_str, "64:ff9b::102:304");
2880 
2881     hints.ai_family = AF_INET;
2882     result = safe_getaddrinfo("v4only", nullptr, &hints);
2883     EXPECT_TRUE(result != nullptr);
2884     EXPECT_LE(2U, GetNumQueries(dns, host_name));
2885     result_str = ToString(result);
2886     EXPECT_EQ(result_str, "1.2.3.4");
2887 }
2888 
TEST_F(ResolverTest,GetAddrInfo_Dns64QueryUnspecifiedV6)2889 TEST_F(ResolverTest, GetAddrInfo_Dns64QueryUnspecifiedV6) {
2890     constexpr char listen_addr[] = "::1";
2891     constexpr char dns64_name[] = "ipv4only.arpa.";
2892     constexpr char host_name[] = "v4v6.example.com.";
2893     const std::vector<DnsRecord> records = {
2894             {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2895             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2896             {host_name, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
2897     };
2898 
2899     test::DNSResponder dns(listen_addr);
2900     StartDns(dns, records);
2901     const std::vector<std::string> servers = {listen_addr};
2902     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2903 
2904     // Start NAT64 prefix discovery and wait for it to complete.
2905     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2906     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
2907 
2908     const addrinfo hints = {.ai_family = AF_UNSPEC};
2909     ScopedAddrinfo result = safe_getaddrinfo("v4v6", nullptr, &hints);
2910     EXPECT_TRUE(result != nullptr);
2911     EXPECT_LE(2U, GetNumQueries(dns, host_name));
2912 
2913     // In AF_UNSPEC case, do not synthesize AAAA if there's at least one AAAA answer.
2914     const std::vector<std::string> result_strs = ToStrings(result);
2915     for (const auto& str : result_strs) {
2916         EXPECT_TRUE(str == "1.2.3.4" || str == "2001:db8::102:304")
2917                 << ", result_str='" << str << "'";
2918     }
2919 }
2920 
TEST_F(ResolverTest,GetAddrInfo_Dns64QueryUnspecifiedNoV6)2921 TEST_F(ResolverTest, GetAddrInfo_Dns64QueryUnspecifiedNoV6) {
2922     constexpr char listen_addr[] = "::1";
2923     constexpr char dns64_name[] = "ipv4only.arpa.";
2924     constexpr char host_name[] = "v4v6.example.com.";
2925     const std::vector<DnsRecord> records = {
2926             {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2927             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2928     };
2929 
2930     test::DNSResponder dns(listen_addr);
2931     StartDns(dns, records);
2932     const std::vector<std::string> servers = {listen_addr};
2933     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2934 
2935     // Start NAT64 prefix discovery and wait for it to complete.
2936     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2937     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
2938 
2939     const addrinfo hints = {.ai_family = AF_UNSPEC};
2940     ScopedAddrinfo result = safe_getaddrinfo("v4v6", nullptr, &hints);
2941     EXPECT_TRUE(result != nullptr);
2942     EXPECT_LE(2U, GetNumQueries(dns, host_name));
2943 
2944     // In AF_UNSPEC case, synthesize AAAA if there's no AAAA answer.
2945     std::string result_str = ToString(result);
2946     EXPECT_EQ(result_str, "64:ff9b::102:304");
2947 }
2948 
TEST_F(ResolverTest,GetAddrInfo_Dns64QuerySpecialUseIPv4Addresses)2949 TEST_F(ResolverTest, GetAddrInfo_Dns64QuerySpecialUseIPv4Addresses) {
2950     constexpr char THIS_NETWORK[] = "this_network";
2951     constexpr char LOOPBACK[] = "loopback";
2952     constexpr char LINK_LOCAL[] = "link_local";
2953     constexpr char MULTICAST[] = "multicast";
2954     constexpr char LIMITED_BROADCAST[] = "limited_broadcast";
2955 
2956     constexpr char ADDR_THIS_NETWORK[] = "0.0.0.1";
2957     constexpr char ADDR_LOOPBACK[] = "127.0.0.1";
2958     constexpr char ADDR_LINK_LOCAL[] = "169.254.0.1";
2959     constexpr char ADDR_MULTICAST[] = "224.0.0.1";
2960     constexpr char ADDR_LIMITED_BROADCAST[] = "255.255.255.255";
2961 
2962     constexpr char listen_addr[] = "::1";
2963     constexpr char dns64_name[] = "ipv4only.arpa.";
2964 
2965     test::DNSResponder dns(listen_addr);
2966     StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
2967     const std::vector<std::string> servers = {listen_addr};
2968     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2969 
2970     // Start NAT64 prefix discovery and wait for it to complete.
2971     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2972     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
2973 
2974     // clang-format off
2975     static const struct TestConfig {
2976         std::string name;
2977         std::string addr;
2978 
2979         std::string asHostName() const { return StringPrintf("%s.example.com.", name.c_str()); }
2980     } testConfigs[]{
2981         {THIS_NETWORK,      ADDR_THIS_NETWORK},
2982         {LOOPBACK,          ADDR_LOOPBACK},
2983         {LINK_LOCAL,        ADDR_LINK_LOCAL},
2984         {MULTICAST,         ADDR_MULTICAST},
2985         {LIMITED_BROADCAST, ADDR_LIMITED_BROADCAST}
2986     };
2987     // clang-format on
2988 
2989     for (const auto& config : testConfigs) {
2990         const std::string testHostName = config.asHostName();
2991         SCOPED_TRACE(testHostName);
2992 
2993         const char* host_name = testHostName.c_str();
2994         dns.addMapping(host_name, ns_type::ns_t_a, config.addr.c_str());
2995 
2996         addrinfo hints;
2997         memset(&hints, 0, sizeof(hints));
2998         hints.ai_family = AF_INET6;
2999         ScopedAddrinfo result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
3000         // In AF_INET6 case, don't return IPv4 answers
3001         EXPECT_TRUE(result == nullptr);
3002         EXPECT_LE(2U, GetNumQueries(dns, host_name));
3003         dns.clearQueries();
3004 
3005         memset(&hints, 0, sizeof(hints));
3006         hints.ai_family = AF_UNSPEC;
3007         result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
3008         EXPECT_TRUE(result != nullptr);
3009         // Expect IPv6 query only. IPv4 answer has been cached in previous query.
3010         EXPECT_LE(1U, GetNumQueries(dns, host_name));
3011         // In AF_UNSPEC case, don't synthesize special use IPv4 address.
3012         std::string result_str = ToString(result);
3013         EXPECT_EQ(result_str, config.addr.c_str());
3014         dns.clearQueries();
3015     }
3016 }
3017 
TEST_F(ResolverTest,GetAddrInfo_Dns64QueryWithNullArgumentHints)3018 TEST_F(ResolverTest, GetAddrInfo_Dns64QueryWithNullArgumentHints) {
3019     constexpr char listen_addr[] = "::1";
3020     constexpr char dns64_name[] = "ipv4only.arpa.";
3021     constexpr char host_name[] = "v4only.example.com.";
3022     constexpr char host_name2[] = "v4v6.example.com.";
3023     const std::vector<DnsRecord> records = {
3024             {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3025             {host_name, ns_type::ns_t_a, "1.2.3.4"},
3026             {host_name2, ns_type::ns_t_a, "1.2.3.4"},
3027             {host_name2, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
3028     };
3029 
3030     test::DNSResponder dns(listen_addr);
3031     StartDns(dns, records);
3032     const std::vector<std::string> servers = {listen_addr};
3033     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3034 
3035     // Start NAT64 prefix discovery and wait for it to complete.
3036     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3037     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
3038 
3039     // Assign argument hints of getaddrinfo() as null is equivalent to set ai_family AF_UNSPEC.
3040     // In AF_UNSPEC case, synthesize AAAA if there has A answer only.
3041     ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, nullptr);
3042     EXPECT_TRUE(result != nullptr);
3043     EXPECT_LE(2U, GetNumQueries(dns, host_name));
3044     std::string result_str = ToString(result);
3045     EXPECT_EQ(result_str, "64:ff9b::102:304");
3046     dns.clearQueries();
3047 
3048     // In AF_UNSPEC case, do not synthesize AAAA if there's at least one AAAA answer.
3049     result = safe_getaddrinfo("v4v6", nullptr, nullptr);
3050     EXPECT_TRUE(result != nullptr);
3051     EXPECT_LE(2U, GetNumQueries(dns, host_name2));
3052     std::vector<std::string> result_strs = ToStrings(result);
3053     for (const auto& str : result_strs) {
3054         EXPECT_TRUE(str == "1.2.3.4" || str == "2001:db8::102:304")
3055                 << ", result_str='" << str << "'";
3056     }
3057 }
3058 
TEST_F(ResolverTest,GetAddrInfo_Dns64QueryNullArgumentNode)3059 TEST_F(ResolverTest, GetAddrInfo_Dns64QueryNullArgumentNode) {
3060     constexpr char ADDR_ANYADDR_V4[] = "0.0.0.0";
3061     constexpr char ADDR_ANYADDR_V6[] = "::";
3062     constexpr char ADDR_LOCALHOST_V4[] = "127.0.0.1";
3063     constexpr char ADDR_LOCALHOST_V6[] = "::1";
3064 
3065     constexpr char PORT_NAME_HTTP[] = "http";
3066     constexpr char PORT_NUMBER_HTTP[] = "80";
3067 
3068     constexpr char listen_addr[] = "::1";
3069     constexpr char dns64_name[] = "ipv4only.arpa.";
3070 
3071     test::DNSResponder dns(listen_addr);
3072     StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
3073     const std::vector<std::string> servers = {listen_addr};
3074     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3075 
3076     // Start NAT64 prefix discovery and wait for it to complete.
3077     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3078     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
3079 
3080     // clang-format off
3081     // If node is null, return address is listed by libc/getaddrinfo.c as follows.
3082     // - passive socket -> anyaddr (0.0.0.0 or ::)
3083     // - non-passive socket -> localhost (127.0.0.1 or ::1)
3084     static const struct TestConfig {
3085         int flag;
3086         std::string addr_v4;
3087         std::string addr_v6;
3088 
3089         std::string asParameters() const {
3090             return StringPrintf("flag=%d, addr_v4=%s, addr_v6=%s", flag, addr_v4.c_str(),
3091                                 addr_v6.c_str());
3092         }
3093     } testConfigs[]{
3094         {0 /* non-passive */, ADDR_LOCALHOST_V4, ADDR_LOCALHOST_V6},
3095         {AI_PASSIVE,          ADDR_ANYADDR_V4,   ADDR_ANYADDR_V6}
3096     };
3097     // clang-format on
3098 
3099     for (const auto& config : testConfigs) {
3100         SCOPED_TRACE(config.asParameters());
3101 
3102         addrinfo hints = {
3103                 .ai_flags = config.flag,
3104                 .ai_family = AF_UNSPEC,  // any address family
3105                 .ai_socktype = 0,        // any type
3106                 .ai_protocol = 0,        // any protocol
3107         };
3108 
3109         // Assign hostname as null and service as port name.
3110         ScopedAddrinfo result = safe_getaddrinfo(nullptr, PORT_NAME_HTTP, &hints);
3111         ASSERT_TRUE(result != nullptr);
3112 
3113         // Can't be synthesized because it should not get into Netd.
3114         std::vector<std::string> result_strs = ToStrings(result);
3115         for (const auto& str : result_strs) {
3116             EXPECT_TRUE(str == config.addr_v4 || str == config.addr_v6)
3117                     << ", result_str='" << str << "'";
3118         }
3119 
3120         // Assign hostname as null and service as numeric port number.
3121         hints.ai_flags = config.flag | AI_NUMERICSERV;
3122         result = safe_getaddrinfo(nullptr, PORT_NUMBER_HTTP, &hints);
3123         ASSERT_TRUE(result != nullptr);
3124 
3125         // Can't be synthesized because it should not get into Netd.
3126         result_strs = ToStrings(result);
3127         for (const auto& str : result_strs) {
3128             EXPECT_TRUE(str == config.addr_v4 || str == config.addr_v6)
3129                     << ", result_str='" << str << "'";
3130         }
3131     }
3132 }
3133 
TEST_F(ResolverTest,GetHostByAddr_ReverseDnsQueryWithHavingNat64Prefix)3134 TEST_F(ResolverTest, GetHostByAddr_ReverseDnsQueryWithHavingNat64Prefix) {
3135     struct hostent* result = nullptr;
3136     struct in_addr v4addr;
3137     struct in6_addr v6addr;
3138 
3139     constexpr char listen_addr[] = "::1";
3140     constexpr char dns64_name[] = "ipv4only.arpa.";
3141     constexpr char ptr_name[] = "v4v6.example.com.";
3142     // PTR record for IPv4 address 1.2.3.4
3143     constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
3144     // PTR record for IPv6 address 2001:db8::102:304
3145     constexpr char ptr_addr_v6[] =
3146             "4.0.3.0.2.0.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa.";
3147     const std::vector<DnsRecord> records = {
3148             {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3149             {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
3150             {ptr_addr_v6, ns_type::ns_t_ptr, ptr_name},
3151     };
3152 
3153     test::DNSResponder dns(listen_addr);
3154     StartDns(dns, records);
3155     const std::vector<std::string> servers = {listen_addr};
3156     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3157 
3158     // Start NAT64 prefix discovery and wait for it to complete.
3159     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3160     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
3161 
3162     // Reverse IPv4 DNS query. Prefix should have no effect on it.
3163     inet_pton(AF_INET, "1.2.3.4", &v4addr);
3164     result = gethostbyaddr(&v4addr, sizeof(v4addr), AF_INET);
3165     ASSERT_TRUE(result != nullptr);
3166     std::string result_str = result->h_name ? result->h_name : "null";
3167     EXPECT_EQ(result_str, "v4v6.example.com");
3168 
3169     // Reverse IPv6 DNS query. Prefix should have no effect on it.
3170     inet_pton(AF_INET6, "2001:db8::102:304", &v6addr);
3171     result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
3172     ASSERT_TRUE(result != nullptr);
3173     result_str = result->h_name ? result->h_name : "null";
3174     EXPECT_EQ(result_str, "v4v6.example.com");
3175 }
3176 
TEST_F(ResolverTest,GetHostByAddr_ReverseDns64Query)3177 TEST_F(ResolverTest, GetHostByAddr_ReverseDns64Query) {
3178     constexpr char listen_addr[] = "::1";
3179     constexpr char dns64_name[] = "ipv4only.arpa.";
3180     constexpr char ptr_name[] = "v4only.example.com.";
3181     // PTR record for IPv4 address 1.2.3.4
3182     constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
3183     // PTR record for IPv6 address 64:ff9b::1.2.3.4
3184     constexpr char ptr_addr_v6_nomapping[] =
3185             "4.0.3.0.2.0.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.b.9.f.f.4.6.0.0.ip6.arpa.";
3186     constexpr char ptr_name_v6_synthesis[] = "v6synthesis.example.com.";
3187     // PTR record for IPv6 address 64:ff9b::5.6.7.8
3188     constexpr char ptr_addr_v6_synthesis[] =
3189             "8.0.7.0.6.0.5.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.b.9.f.f.4.6.0.0.ip6.arpa.";
3190     const std::vector<DnsRecord> records = {
3191             {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3192             {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
3193             {ptr_addr_v6_synthesis, ns_type::ns_t_ptr, ptr_name_v6_synthesis},
3194     };
3195 
3196     test::DNSResponder dns(listen_addr);
3197     StartDns(dns, records);
3198     // "ptr_addr_v6_nomapping" is not mapped in DNS server
3199     const std::vector<std::string> servers = {listen_addr};
3200     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3201 
3202     // Start NAT64 prefix discovery and wait for it to complete.
3203     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3204     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
3205 
3206     // Synthesized PTR record doesn't exist on DNS server
3207     // Reverse IPv6 DNS64 query while DNS server doesn't have an answer for synthesized address.
3208     // After querying synthesized address failed, expect that prefix is removed from IPv6
3209     // synthesized address and do reverse IPv4 query instead.
3210     struct in6_addr v6addr;
3211     inet_pton(AF_INET6, "64:ff9b::1.2.3.4", &v6addr);
3212     struct hostent* result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
3213     ASSERT_TRUE(result != nullptr);
3214     EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_nomapping));  // PTR record not exist
3215     EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4));            // PTR record exist
3216     std::string result_str = result->h_name ? result->h_name : "null";
3217     EXPECT_EQ(result_str, "v4only.example.com");
3218     // Check that return address has been mapped from IPv4 to IPv6 address because Netd
3219     // removes NAT64 prefix and does IPv4 DNS reverse lookup in this case. Then, Netd
3220     // fakes the return IPv4 address as original queried IPv6 address.
3221     result_str = ToString(result);
3222     EXPECT_EQ(result_str, "64:ff9b::102:304");
3223     dns.clearQueries();
3224 
3225     // Synthesized PTR record exists on DNS server
3226     // Reverse IPv6 DNS64 query while DNS server has an answer for synthesized address.
3227     // Expect to Netd pass through synthesized address for DNS queries.
3228     inet_pton(AF_INET6, "64:ff9b::5.6.7.8", &v6addr);
3229     result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
3230     ASSERT_TRUE(result != nullptr);
3231     EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_synthesis));
3232     result_str = result->h_name ? result->h_name : "null";
3233     EXPECT_EQ(result_str, "v6synthesis.example.com");
3234 }
3235 
TEST_F(ResolverTest,GetHostByAddr_ReverseDns64QueryFromHostFile)3236 TEST_F(ResolverTest, GetHostByAddr_ReverseDns64QueryFromHostFile) {
3237     constexpr char dns64_name[] = "ipv4only.arpa.";
3238     constexpr char host_name[] = "localhost";
3239     // The address is synthesized by prefix64:localhost.
3240     constexpr char host_addr[] = "64:ff9b::7f00:1";
3241     constexpr char listen_addr[] = "::1";
3242 
3243     test::DNSResponder dns(listen_addr);
3244     StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
3245     const std::vector<std::string> servers = {listen_addr};
3246     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3247 
3248     // Start NAT64 prefix discovery and wait for it to complete.
3249     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3250     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
3251 
3252     // Using synthesized "localhost" address to be a trick for resolving host name
3253     // from host file /etc/hosts and "localhost" is the only name in /etc/hosts. Note that this is
3254     // not realistic: the code never synthesizes AAAA records for addresses in 127.0.0.0/8.
3255     struct in6_addr v6addr;
3256     inet_pton(AF_INET6, host_addr, &v6addr);
3257     struct hostent* result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
3258     ASSERT_TRUE(result != nullptr);
3259     // Expect no DNS queries; localhost is resolved via /etc/hosts.
3260     EXPECT_EQ(0U, GetNumQueries(dns, host_name));
3261 
3262     ASSERT_EQ(sizeof(in6_addr), (unsigned)result->h_length);
3263     ASSERT_EQ(AF_INET6, result->h_addrtype);
3264     std::string result_str = ToString(result);
3265     EXPECT_EQ(result_str, host_addr);
3266     result_str = result->h_name ? result->h_name : "null";
3267     EXPECT_EQ(result_str, host_name);
3268 }
3269 
TEST_F(ResolverTest,GetHostByAddr_cnamesClasslessReverseDelegation)3270 TEST_F(ResolverTest, GetHostByAddr_cnamesClasslessReverseDelegation) {
3271     // IPv4 addresses in the subnet with notation '/' or '-'.
3272     constexpr char addr_slash[] = "192.0.2.1";
3273     constexpr char addr_hyphen[] = "192.0.3.1";
3274 
3275     // Used to verify DNS reverse query for classless reverse lookup zone. See detail in RFC 2317
3276     // section 4.
3277     const static std::vector<DnsRecord> records = {
3278             // The records for reverse querying "192.0.2.1" in the subnet with notation '/'.
3279             {"1.2.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0/25.2.0.192.in-addr.arpa."},
3280             {"1.0/25.2.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
3281 
3282             // The records for reverse querying "192.0.3.1" in the subnet with notation '-'.
3283             {"1.3.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0-127.3.0.192.in-addr.arpa."},
3284             {"1.0-127.3.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
3285     };
3286 
3287     test::DNSResponder dns;
3288     StartDns(dns, records);
3289     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
3290 
3291     for (const auto& address : {addr_slash, addr_hyphen}) {
3292         SCOPED_TRACE(address);
3293 
3294         in_addr v4addr;
3295         ASSERT_TRUE(inet_pton(AF_INET, address, &v4addr));
3296         hostent* result = gethostbyaddr(&v4addr, sizeof(v4addr), AF_INET);
3297         ASSERT_TRUE(result != nullptr);
3298         EXPECT_STREQ("hello.example.com", result->h_name);
3299     }
3300 }
3301 
TEST_F(ResolverTest,GetNameInfo_ReverseDnsQueryWithHavingNat64Prefix)3302 TEST_F(ResolverTest, GetNameInfo_ReverseDnsQueryWithHavingNat64Prefix) {
3303     constexpr char listen_addr[] = "::1";
3304     constexpr char dns64_name[] = "ipv4only.arpa.";
3305     constexpr char ptr_name[] = "v4v6.example.com.";
3306     // PTR record for IPv4 address 1.2.3.4
3307     constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
3308     // PTR record for IPv6 address 2001:db8::102:304
3309     constexpr char ptr_addr_v6[] =
3310             "4.0.3.0.2.0.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa.";
3311     const std::vector<DnsRecord> records = {
3312             {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3313             {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
3314             {ptr_addr_v6, ns_type::ns_t_ptr, ptr_name},
3315     };
3316 
3317     test::DNSResponder dns(listen_addr);
3318     StartDns(dns, records);
3319     const std::vector<std::string> servers = {listen_addr};
3320     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3321 
3322     // Start NAT64 prefix discovery and wait for it to complete.
3323     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3324     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
3325 
3326     // clang-format off
3327     static const struct TestConfig {
3328         int flag;
3329         int family;
3330         std::string addr;
3331         std::string host;
3332 
3333         std::string asParameters() const {
3334             return StringPrintf("flag=%d, family=%d, addr=%s, host=%s", flag, family, addr.c_str(),
3335                                 host.c_str());
3336         }
3337     } testConfigs[]{
3338         {NI_NAMEREQD,    AF_INET,  "1.2.3.4",           "v4v6.example.com"},
3339         {NI_NUMERICHOST, AF_INET,  "1.2.3.4",           "1.2.3.4"},
3340         {0,              AF_INET,  "1.2.3.4",           "v4v6.example.com"},
3341         {0,              AF_INET,  "5.6.7.8",           "5.6.7.8"},           // unmapped
3342         {NI_NAMEREQD,    AF_INET6, "2001:db8::102:304", "v4v6.example.com"},
3343         {NI_NUMERICHOST, AF_INET6, "2001:db8::102:304", "2001:db8::102:304"},
3344         {0,              AF_INET6, "2001:db8::102:304", "v4v6.example.com"},
3345         {0,              AF_INET6, "2001:db8::506:708", "2001:db8::506:708"}, // unmapped
3346     };
3347     // clang-format on
3348 
3349     // Reverse IPv4/IPv6 DNS query. Prefix should have no effect on it.
3350     for (const auto& config : testConfigs) {
3351         SCOPED_TRACE(config.asParameters());
3352 
3353         int rv;
3354         char host[NI_MAXHOST];
3355         struct sockaddr_in sin;
3356         struct sockaddr_in6 sin6;
3357         if (config.family == AF_INET) {
3358             memset(&sin, 0, sizeof(sin));
3359             sin.sin_family = AF_INET;
3360             inet_pton(AF_INET, config.addr.c_str(), &sin.sin_addr);
3361             rv = getnameinfo((const struct sockaddr*)&sin, sizeof(sin), host, sizeof(host), nullptr,
3362                              0, config.flag);
3363             if (config.flag == NI_NAMEREQD) EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4));
3364         } else if (config.family == AF_INET6) {
3365             memset(&sin6, 0, sizeof(sin6));
3366             sin6.sin6_family = AF_INET6;
3367             inet_pton(AF_INET6, config.addr.c_str(), &sin6.sin6_addr);
3368             rv = getnameinfo((const struct sockaddr*)&sin6, sizeof(sin6), host, sizeof(host),
3369                              nullptr, 0, config.flag);
3370             if (config.flag == NI_NAMEREQD) EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6));
3371         }
3372         ASSERT_EQ(0, rv);
3373         std::string result_str = host;
3374         EXPECT_EQ(result_str, config.host);
3375         dns.clearQueries();
3376     }
3377 }
3378 
TEST_F(ResolverTest,GetNameInfo_ReverseDns64Query)3379 TEST_F(ResolverTest, GetNameInfo_ReverseDns64Query) {
3380     constexpr char listen_addr[] = "::1";
3381     constexpr char dns64_name[] = "ipv4only.arpa.";
3382     constexpr char ptr_name[] = "v4only.example.com.";
3383     // PTR record for IPv4 address 1.2.3.4
3384     constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
3385     // PTR record for IPv6 address 64:ff9b::1.2.3.4
3386     constexpr char ptr_addr_v6_nomapping[] =
3387             "4.0.3.0.2.0.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.b.9.f.f.4.6.0.0.ip6.arpa.";
3388     constexpr char ptr_name_v6_synthesis[] = "v6synthesis.example.com.";
3389     // PTR record for IPv6 address 64:ff9b::5.6.7.8
3390     constexpr char ptr_addr_v6_synthesis[] =
3391             "8.0.7.0.6.0.5.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.b.9.f.f.4.6.0.0.ip6.arpa.";
3392     const std::vector<DnsRecord> records = {
3393             {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3394             {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
3395             {ptr_addr_v6_synthesis, ns_type::ns_t_ptr, ptr_name_v6_synthesis},
3396     };
3397 
3398     test::DNSResponder dns(listen_addr);
3399     StartDns(dns, records);
3400     const std::vector<std::string> servers = {listen_addr};
3401     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3402 
3403     // Start NAT64 prefix discovery and wait for it to complete.
3404     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3405     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
3406 
3407     // clang-format off
3408     static const struct TestConfig {
3409         bool hasSynthesizedPtrRecord;
3410         int flag;
3411         std::string addr;
3412         std::string host;
3413 
3414         std::string asParameters() const {
3415             return StringPrintf("hasSynthesizedPtrRecord=%d, flag=%d, addr=%s, host=%s",
3416                                 hasSynthesizedPtrRecord, flag, addr.c_str(), host.c_str());
3417         }
3418     } testConfigs[]{
3419         {false, NI_NAMEREQD,    "64:ff9b::102:304", "v4only.example.com"},
3420         {false, NI_NUMERICHOST, "64:ff9b::102:304", "64:ff9b::102:304"},
3421         {false, 0,              "64:ff9b::102:304", "v4only.example.com"},
3422         {true,  NI_NAMEREQD,    "64:ff9b::506:708", "v6synthesis.example.com"},
3423         {true,  NI_NUMERICHOST, "64:ff9b::506:708", "64:ff9b::506:708"},
3424         {true,  0,              "64:ff9b::506:708", "v6synthesis.example.com"}
3425     };
3426     // clang-format on
3427 
3428     // hasSynthesizedPtrRecord = false
3429     //   Synthesized PTR record doesn't exist on DNS server
3430     //   Reverse IPv6 DNS64 query while DNS server doesn't have an answer for synthesized address.
3431     //   After querying synthesized address failed, expect that prefix is removed from IPv6
3432     //   synthesized address and do reverse IPv4 query instead.
3433     //
3434     // hasSynthesizedPtrRecord = true
3435     //   Synthesized PTR record exists on DNS server
3436     //   Reverse IPv6 DNS64 query while DNS server has an answer for synthesized address.
3437     //   Expect to just pass through synthesized address for DNS queries.
3438     for (const auto& config : testConfigs) {
3439         SCOPED_TRACE(config.asParameters());
3440 
3441         char host[NI_MAXHOST];
3442         struct sockaddr_in6 sin6;
3443         memset(&sin6, 0, sizeof(sin6));
3444         sin6.sin6_family = AF_INET6;
3445         inet_pton(AF_INET6, config.addr.c_str(), &sin6.sin6_addr);
3446         int rv = getnameinfo((const struct sockaddr*)&sin6, sizeof(sin6), host, sizeof(host),
3447                              nullptr, 0, config.flag);
3448         ASSERT_EQ(0, rv);
3449         if (config.flag == NI_NAMEREQD) {
3450             if (config.hasSynthesizedPtrRecord) {
3451                 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_synthesis));
3452             } else {
3453                 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_nomapping));  // PTR record not exist.
3454                 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4));            // PTR record exist.
3455             }
3456         }
3457         std::string result_str = host;
3458         EXPECT_EQ(result_str, config.host);
3459         dns.clearQueries();
3460     }
3461 }
3462 
TEST_F(ResolverTest,GetNameInfo_ReverseDns64QueryFromHostFile)3463 TEST_F(ResolverTest, GetNameInfo_ReverseDns64QueryFromHostFile) {
3464     constexpr char dns64_name[] = "ipv4only.arpa.";
3465     constexpr char host_name[] = "localhost";
3466     // The address is synthesized by prefix64:localhost.
3467     constexpr char host_addr[] = "64:ff9b::7f00:1";
3468     constexpr char listen_addr[] = "::1";
3469 
3470     test::DNSResponder dns(listen_addr);
3471 
3472     StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
3473     const std::vector<std::string> servers = {listen_addr};
3474     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3475 
3476     // Start NAT64 prefix discovery and wait for it to complete.
3477     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3478     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
3479 
3480     // Using synthesized "localhost" address to be a trick for resolving host name
3481     // from host file /etc/hosts and "localhost" is the only name in /etc/hosts. Note that this is
3482     // not realistic: the code never synthesizes AAAA records for addresses in 127.0.0.0/8.
3483     char host[NI_MAXHOST];
3484     struct sockaddr_in6 sin6 = {.sin6_family = AF_INET6};
3485     inet_pton(AF_INET6, host_addr, &sin6.sin6_addr);
3486     int rv = getnameinfo((const struct sockaddr*)&sin6, sizeof(sin6), host, sizeof(host), nullptr,
3487                          0, NI_NAMEREQD);
3488     ASSERT_EQ(0, rv);
3489     // Expect no DNS queries; localhost is resolved via /etc/hosts.
3490     EXPECT_EQ(0U, GetNumQueries(dns, host_name));
3491 
3492     std::string result_str = host;
3493     EXPECT_EQ(result_str, host_name);
3494 }
3495 
TEST_F(ResolverTest,GetNameInfo_cnamesClasslessReverseDelegation)3496 TEST_F(ResolverTest, GetNameInfo_cnamesClasslessReverseDelegation) {
3497     // IPv4 addresses in the subnet with notation '/' or '-'.
3498     constexpr char addr_slash[] = "192.0.2.1";
3499     constexpr char addr_hyphen[] = "192.0.3.1";
3500 
3501     // Used to verify DNS reverse query for classless reverse lookup zone. See detail in RFC 2317
3502     // section 4.
3503     const static std::vector<DnsRecord> records = {
3504             // The records for reverse querying "192.0.2.1" in the subnet with notation '/'.
3505             {"1.2.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0/25.2.0.192.in-addr.arpa."},
3506             {"1.0/25.2.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
3507 
3508             // The records for reverse querying "192.0.3.1" in the subnet with notation '-'.
3509             {"1.3.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0-127.3.0.192.in-addr.arpa."},
3510             {"1.0-127.3.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
3511     };
3512 
3513     test::DNSResponder dns;
3514     StartDns(dns, records);
3515     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
3516 
3517     for (const auto& address : {addr_slash, addr_hyphen}) {
3518         SCOPED_TRACE(address);
3519 
3520         char host[NI_MAXHOST];
3521         sockaddr_in sin = {.sin_family = AF_INET};
3522         ASSERT_TRUE(inet_pton(AF_INET, address, &sin.sin_addr));
3523         int rv = getnameinfo((const sockaddr*)&sin, sizeof(sin), host, sizeof(host), nullptr, 0,
3524                              NI_NAMEREQD);
3525         ASSERT_EQ(0, rv);
3526         EXPECT_STREQ("hello.example.com", host);
3527     }
3528 }
3529 
TEST_F(ResolverTest,GetHostByName2_Dns64Synthesize)3530 TEST_F(ResolverTest, GetHostByName2_Dns64Synthesize) {
3531     constexpr char listen_addr[] = "::1";
3532     constexpr char dns64_name[] = "ipv4only.arpa.";
3533     constexpr char host_name[] = "ipv4only.example.com.";
3534     const std::vector<DnsRecord> records = {
3535             {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3536             {host_name, ns_type::ns_t_a, "1.2.3.4"},
3537     };
3538 
3539     test::DNSResponder dns(listen_addr);
3540     StartDns(dns, records);
3541     const std::vector<std::string> servers = {listen_addr};
3542     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3543 
3544     // Start NAT64 prefix discovery and wait for it to complete.
3545     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3546     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
3547 
3548     // Query an IPv4-only hostname. Expect that gets a synthesized address.
3549     struct hostent* result = gethostbyname2("ipv4only", AF_INET6);
3550     ASSERT_TRUE(result != nullptr);
3551     EXPECT_LE(1U, GetNumQueries(dns, host_name));
3552     std::string result_str = ToString(result);
3553     EXPECT_EQ(result_str, "64:ff9b::102:304");
3554 }
3555 
TEST_F(ResolverTest,GetHostByName2_DnsQueryWithHavingNat64Prefix)3556 TEST_F(ResolverTest, GetHostByName2_DnsQueryWithHavingNat64Prefix) {
3557     constexpr char dns64_name[] = "ipv4only.arpa.";
3558     constexpr char host_name[] = "v4v6.example.com.";
3559     constexpr char listen_addr[] = "::1";
3560     const std::vector<DnsRecord> records = {
3561             {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3562             {host_name, ns_type::ns_t_a, "1.2.3.4"},
3563             {host_name, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
3564     };
3565 
3566     test::DNSResponder dns(listen_addr);
3567     StartDns(dns, records);
3568     const std::vector<std::string> servers = {listen_addr};
3569     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3570 
3571     // Start NAT64 prefix discovery and wait for it to complete.
3572     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3573     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
3574 
3575     // IPv4 DNS query. Prefix should have no effect on it.
3576     struct hostent* result = gethostbyname2("v4v6", AF_INET);
3577     ASSERT_TRUE(result != nullptr);
3578     EXPECT_LE(1U, GetNumQueries(dns, host_name));
3579     std::string result_str = ToString(result);
3580     EXPECT_EQ(result_str, "1.2.3.4");
3581     dns.clearQueries();
3582 
3583     // IPv6 DNS query. Prefix should have no effect on it.
3584     result = gethostbyname2("v4v6", AF_INET6);
3585     ASSERT_TRUE(result != nullptr);
3586     EXPECT_LE(1U, GetNumQueries(dns, host_name));
3587     result_str = ToString(result);
3588     EXPECT_EQ(result_str, "2001:db8::102:304");
3589 }
3590 
TEST_F(ResolverTest,GetHostByName2_Dns64QuerySpecialUseIPv4Addresses)3591 TEST_F(ResolverTest, GetHostByName2_Dns64QuerySpecialUseIPv4Addresses) {
3592     constexpr char THIS_NETWORK[] = "this_network";
3593     constexpr char LOOPBACK[] = "loopback";
3594     constexpr char LINK_LOCAL[] = "link_local";
3595     constexpr char MULTICAST[] = "multicast";
3596     constexpr char LIMITED_BROADCAST[] = "limited_broadcast";
3597 
3598     constexpr char ADDR_THIS_NETWORK[] = "0.0.0.1";
3599     constexpr char ADDR_LOOPBACK[] = "127.0.0.1";
3600     constexpr char ADDR_LINK_LOCAL[] = "169.254.0.1";
3601     constexpr char ADDR_MULTICAST[] = "224.0.0.1";
3602     constexpr char ADDR_LIMITED_BROADCAST[] = "255.255.255.255";
3603 
3604     constexpr char listen_addr[] = "::1";
3605     constexpr char dns64_name[] = "ipv4only.arpa.";
3606 
3607     test::DNSResponder dns(listen_addr);
3608     StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
3609     const std::vector<std::string> servers = {listen_addr};
3610     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3611 
3612     // Start NAT64 prefix discovery and wait for it to complete.
3613     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3614     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
3615 
3616     // clang-format off
3617     static const struct TestConfig {
3618         std::string name;
3619         std::string addr;
3620 
3621         std::string asHostName() const {
3622             return StringPrintf("%s.example.com.", name.c_str());
3623         }
3624     } testConfigs[]{
3625         {THIS_NETWORK,      ADDR_THIS_NETWORK},
3626         {LOOPBACK,          ADDR_LOOPBACK},
3627         {LINK_LOCAL,        ADDR_LINK_LOCAL},
3628         {MULTICAST,         ADDR_MULTICAST},
3629         {LIMITED_BROADCAST, ADDR_LIMITED_BROADCAST}
3630     };
3631     // clang-format on
3632 
3633     for (const auto& config : testConfigs) {
3634         const std::string testHostName = config.asHostName();
3635         SCOPED_TRACE(testHostName);
3636 
3637         const char* host_name = testHostName.c_str();
3638         dns.addMapping(host_name, ns_type::ns_t_a, config.addr.c_str());
3639 
3640         struct hostent* result = gethostbyname2(config.name.c_str(), AF_INET6);
3641         EXPECT_LE(1U, GetNumQueries(dns, host_name));
3642 
3643         // In AF_INET6 case, don't synthesize special use IPv4 address.
3644         // Expect to have no answer
3645         EXPECT_EQ(nullptr, result);
3646 
3647         dns.clearQueries();
3648     }
3649 }
3650 
TEST_F(ResolverTest,PrefixDiscoveryBypassTls)3651 TEST_F(ResolverTest, PrefixDiscoveryBypassTls) {
3652     constexpr char listen_addr[] = "::1";
3653     constexpr char cleartext_port[] = "53";
3654     constexpr char tls_port[] = "853";
3655     constexpr char dns64_name[] = "ipv4only.arpa.";
3656     const std::vector<std::string> servers = {listen_addr};
3657 
3658     test::DNSResponder dns(listen_addr);
3659     StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
3660     test::DnsTlsFrontend tls(listen_addr, tls_port, listen_addr, cleartext_port);
3661     ASSERT_TRUE(tls.startServer());
3662 
3663     // Setup OPPORTUNISTIC mode and wait for the validation complete.
3664     ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
3665     EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
3666     EXPECT_TRUE(tls.waitForQueries(1));
3667     tls.clearQueries();
3668 
3669     // Start NAT64 prefix discovery and wait for it complete.
3670     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3671     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
3672 
3673     // Verify it bypassed TLS even though there's a TLS server available.
3674     EXPECT_EQ(0, tls.queries()) << dns.dumpQueries();
3675     EXPECT_EQ(1U, GetNumQueries(dns, dns64_name)) << dns.dumpQueries();
3676 
3677     // Restart the testing network to reset the cache.
3678     mDnsClient.TearDown();
3679     mDnsClient.SetUp();
3680     dns.clearQueries();
3681 
3682     // Setup STRICT mode and wait for the validation complete.
3683     ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
3684                                                kDefaultPrivateDnsHostName));
3685     EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
3686     EXPECT_TRUE(tls.waitForQueries(1));
3687     tls.clearQueries();
3688 
3689     // Start NAT64 prefix discovery and wait for it to complete.
3690     EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3691     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
3692 
3693     // Verify it bypassed TLS despite STRICT mode.
3694     EXPECT_EQ(0, tls.queries()) << dns.dumpQueries();
3695     EXPECT_EQ(1U, GetNumQueries(dns, dns64_name)) << dns.dumpQueries();
3696 }
3697 
TEST_F(ResolverTest,SetAndClearNat64Prefix)3698 TEST_F(ResolverTest, SetAndClearNat64Prefix) {
3699     constexpr char host_name[] = "v4.example.com.";
3700     constexpr char listen_addr[] = "::1";
3701     const std::vector<DnsRecord> records = {
3702             {host_name, ns_type::ns_t_a, "1.2.3.4"},
3703     };
3704     const std::string kNat64Prefix1 = "64:ff9b::/96";
3705     const std::string kNat64Prefix2 = "2001:db8:6464::/96";
3706 
3707     test::DNSResponder dns(listen_addr);
3708     StartDns(dns, records);
3709     const std::vector<std::string> servers = {listen_addr};
3710     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3711 
3712     auto resolvService = mDnsClient.resolvService();
3713     addrinfo hints = {.ai_family = AF_INET6};
3714 
3715     // No NAT64 prefix, no AAAA record.
3716     ScopedAddrinfo result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
3717     ASSERT_TRUE(result == nullptr);
3718 
3719     // Set the prefix, and expect to get a synthesized AAAA record.
3720     EXPECT_TRUE(resolvService->setPrefix64(TEST_NETID, kNat64Prefix2).isOk());
3721     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
3722     ASSERT_FALSE(result == nullptr);
3723     EXPECT_EQ("2001:db8:6464::102:304", ToString(result));
3724 
3725     // Update the prefix, expect to see AAAA records from the new prefix.
3726     EXPECT_TRUE(resolvService->setPrefix64(TEST_NETID, kNat64Prefix1).isOk());
3727     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
3728     ASSERT_FALSE(result == nullptr);
3729     EXPECT_EQ("64:ff9b::102:304", ToString(result));
3730 
3731     // Non-/96 prefixes are ignored.
3732     auto status = resolvService->setPrefix64(TEST_NETID, "64:ff9b::/64");
3733     EXPECT_FALSE(status.isOk());
3734     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
3735     EXPECT_EQ(EINVAL, status.getServiceSpecificError());
3736 
3737     // Invalid prefixes are ignored.
3738     status = resolvService->setPrefix64(TEST_NETID, "192.0.2.0/24");
3739     EXPECT_FALSE(status.isOk());
3740     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
3741     EXPECT_EQ(EINVAL, status.getServiceSpecificError());
3742 
3743     status = resolvService->setPrefix64(TEST_NETID, "192.0.2.1");
3744     EXPECT_FALSE(status.isOk());
3745     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
3746     EXPECT_EQ(EINVAL, status.getServiceSpecificError());
3747 
3748     status = resolvService->setPrefix64(TEST_NETID, "hello");
3749     EXPECT_FALSE(status.isOk());
3750     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
3751     EXPECT_EQ(EINVAL, status.getServiceSpecificError());
3752 
3753     // DNS64 synthesis is still working.
3754     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
3755     ASSERT_FALSE(result == nullptr);
3756     EXPECT_EQ("64:ff9b::102:304", ToString(result));
3757 
3758     // Clear the prefix. No AAAA records any more.
3759     EXPECT_TRUE(resolvService->setPrefix64(TEST_NETID, "").isOk());
3760     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
3761     EXPECT_TRUE(result == nullptr);
3762 
3763     // Calling startPrefix64Discovery clears the prefix.
3764     EXPECT_TRUE(resolvService->setPrefix64(TEST_NETID, kNat64Prefix1).isOk());
3765     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
3766     ASSERT_FALSE(result == nullptr);
3767     EXPECT_EQ("64:ff9b::102:304", ToString(result));
3768 
3769     EXPECT_TRUE(resolvService->startPrefix64Discovery(TEST_NETID).isOk());
3770     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
3771     ASSERT_TRUE(result == nullptr);
3772 
3773     // setPrefix64 fails if prefix discovery is started, even if no prefix is yet discovered...
3774     status = resolvService->setPrefix64(TEST_NETID, kNat64Prefix1);
3775     EXPECT_FALSE(status.isOk());
3776     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
3777     EXPECT_EQ(EEXIST, status.getServiceSpecificError());
3778 
3779     // .. and clearing the prefix also has no effect.
3780     status = resolvService->setPrefix64(TEST_NETID, "");
3781     EXPECT_FALSE(status.isOk());
3782     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
3783     EXPECT_EQ(ENOENT, status.getServiceSpecificError());
3784 
3785     // setPrefix64 succeeds again when prefix discovery is stopped.
3786     EXPECT_TRUE(resolvService->stopPrefix64Discovery(TEST_NETID).isOk());
3787     EXPECT_TRUE(resolvService->setPrefix64(TEST_NETID, kNat64Prefix1).isOk());
3788     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
3789     ASSERT_FALSE(result == nullptr);
3790     EXPECT_EQ("64:ff9b::102:304", ToString(result));
3791 
3792     // Calling stopPrefix64Discovery clears the prefix.
3793     EXPECT_TRUE(resolvService->stopPrefix64Discovery(TEST_NETID).isOk());
3794     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
3795     ASSERT_TRUE(result == nullptr);
3796 
3797     // Set up NAT64 prefix discovery.
3798     constexpr char dns64_name[] = "ipv4only.arpa.";
3799     const std::vector<DnsRecord> newRecords = {
3800             {host_name, ns_type::ns_t_a, "1.2.3.4"},
3801             {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3802     };
3803     dns.stopServer();
3804     StartDns(dns, newRecords);
3805 
3806     EXPECT_TRUE(resolvService->startPrefix64Discovery(TEST_NETID).isOk());
3807     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
3808     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
3809     ASSERT_FALSE(result == nullptr);
3810     EXPECT_EQ("64:ff9b::102:304", ToString(result));
3811 
3812     // setPrefix64 fails if NAT64 prefix discovery has succeeded, and the discovered prefix
3813     // continues to be used.
3814     status = resolvService->setPrefix64(TEST_NETID, kNat64Prefix2);
3815     EXPECT_FALSE(status.isOk());
3816     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
3817     EXPECT_EQ(EEXIST, status.getServiceSpecificError());
3818 
3819     // Clearing the prefix also has no effect if discovery is started.
3820     status = resolvService->setPrefix64(TEST_NETID, "");
3821     EXPECT_FALSE(status.isOk());
3822     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
3823     EXPECT_EQ(ENOENT, status.getServiceSpecificError());
3824 
3825     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
3826     ASSERT_FALSE(result == nullptr);
3827     EXPECT_EQ("64:ff9b::102:304", ToString(result));
3828 
3829     EXPECT_TRUE(resolvService->stopPrefix64Discovery(TEST_NETID).isOk());
3830     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_NOT_FOUND));
3831 
3832     EXPECT_EQ(0, sDnsMetricsListener->getUnexpectedNat64PrefixUpdates());
3833 }
3834 
3835 namespace {
3836 
3837 class ScopedSetNetworkForProcess {
3838   public:
ScopedSetNetworkForProcess(unsigned netId)3839     explicit ScopedSetNetworkForProcess(unsigned netId) {
3840         mStoredNetId = getNetworkForProcess();
3841         if (netId == mStoredNetId) return;
3842         EXPECT_EQ(0, setNetworkForProcess(netId));
3843     }
~ScopedSetNetworkForProcess()3844     ~ScopedSetNetworkForProcess() { EXPECT_EQ(0, setNetworkForProcess(mStoredNetId)); }
3845 
3846   private:
3847     unsigned mStoredNetId;
3848 };
3849 
3850 class ScopedSetNetworkForResolv {
3851   public:
ScopedSetNetworkForResolv(unsigned netId)3852     explicit ScopedSetNetworkForResolv(unsigned netId) { EXPECT_EQ(0, setNetworkForResolv(netId)); }
~ScopedSetNetworkForResolv()3853     ~ScopedSetNetworkForResolv() { EXPECT_EQ(0, setNetworkForResolv(NETID_UNSET)); }
3854 };
3855 
sendCommand(int fd,const std::string & cmd)3856 void sendCommand(int fd, const std::string& cmd) {
3857     ssize_t rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size() + 1));
3858     EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size() + 1));
3859 }
3860 
readBE32(int fd)3861 int32_t readBE32(int fd) {
3862     int32_t tmp;
3863     int n = TEMP_FAILURE_RETRY(read(fd, &tmp, sizeof(tmp)));
3864     EXPECT_TRUE(n > 0);
3865     return ntohl(tmp);
3866 }
3867 
readResponseCode(int fd)3868 int readResponseCode(int fd) {
3869     char buf[4];
3870     int n = TEMP_FAILURE_RETRY(read(fd, &buf, sizeof(buf)));
3871     EXPECT_TRUE(n > 0);
3872     // The format of response code is that 4 bytes for the code & null.
3873     buf[3] = '\0';
3874     int result;
3875     EXPECT_TRUE(ParseInt(buf, &result));
3876     return result;
3877 }
3878 
checkAndClearUseLocalNameserversFlag(unsigned * netid)3879 bool checkAndClearUseLocalNameserversFlag(unsigned* netid) {
3880     if (netid == nullptr || ((*netid) & NETID_USE_LOCAL_NAMESERVERS) == 0) {
3881         return false;
3882     }
3883     *netid = (*netid) & ~NETID_USE_LOCAL_NAMESERVERS;
3884     return true;
3885 }
3886 
makeUidRangeParcel(int start,int stop)3887 aidl::android::net::UidRangeParcel makeUidRangeParcel(int start, int stop) {
3888     aidl::android::net::UidRangeParcel res;
3889     res.start = start;
3890     res.stop = stop;
3891 
3892     return res;
3893 }
3894 
expectNetIdWithLocalNameserversFlag(unsigned netId)3895 void expectNetIdWithLocalNameserversFlag(unsigned netId) {
3896     unsigned dnsNetId = 0;
3897     EXPECT_EQ(0, getNetworkForDns(&dnsNetId));
3898     EXPECT_TRUE(checkAndClearUseLocalNameserversFlag(&dnsNetId));
3899     EXPECT_EQ(netId, static_cast<unsigned>(dnsNetId));
3900 }
3901 
expectDnsNetIdEquals(unsigned netId)3902 void expectDnsNetIdEquals(unsigned netId) {
3903     unsigned dnsNetId = 0;
3904     EXPECT_EQ(0, getNetworkForDns(&dnsNetId));
3905     EXPECT_EQ(netId, static_cast<unsigned>(dnsNetId));
3906 }
3907 
expectDnsNetIdIsDefaultNetwork(INetd * netdService)3908 void expectDnsNetIdIsDefaultNetwork(INetd* netdService) {
3909     int currentNetid;
3910     EXPECT_TRUE(netdService->networkGetDefault(&currentNetid).isOk());
3911     expectDnsNetIdEquals(currentNetid);
3912 }
3913 
expectDnsNetIdWithVpn(INetd * netdService,unsigned vpnNetId,unsigned expectedNetId)3914 void expectDnsNetIdWithVpn(INetd* netdService, unsigned vpnNetId, unsigned expectedNetId) {
3915     EXPECT_TRUE(netdService->networkCreateVpn(vpnNetId, false /* secure */).isOk());
3916     uid_t uid = getuid();
3917     // Add uid to VPN
3918     EXPECT_TRUE(netdService->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3919     expectDnsNetIdEquals(expectedNetId);
3920     EXPECT_TRUE(netdService->networkDestroy(vpnNetId).isOk());
3921 }
3922 
3923 }  // namespace
3924 
TEST_F(ResolverTest,getDnsNetId)3925 TEST_F(ResolverTest, getDnsNetId) {
3926     // We've called setNetworkForProcess in SetupOemNetwork, so reset to default first.
3927     setNetworkForProcess(NETID_UNSET);
3928 
3929     expectDnsNetIdIsDefaultNetwork(mDnsClient.netdService());
3930     expectDnsNetIdWithVpn(mDnsClient.netdService(), TEST_VPN_NETID, TEST_VPN_NETID);
3931 
3932     // Test with setNetworkForProcess
3933     {
3934         ScopedSetNetworkForProcess scopedSetNetworkForProcess(TEST_NETID);
3935         expectDnsNetIdEquals(TEST_NETID);
3936     }
3937 
3938     // Test with setNetworkForProcess with NETID_USE_LOCAL_NAMESERVERS
3939     {
3940         ScopedSetNetworkForProcess scopedSetNetworkForProcess(TEST_NETID |
3941                                                               NETID_USE_LOCAL_NAMESERVERS);
3942         expectNetIdWithLocalNameserversFlag(TEST_NETID);
3943     }
3944 
3945     // Test with setNetworkForResolv
3946     {
3947         ScopedSetNetworkForResolv scopedSetNetworkForResolv(TEST_NETID);
3948         expectDnsNetIdEquals(TEST_NETID);
3949     }
3950 
3951     // Test with setNetworkForResolv with NETID_USE_LOCAL_NAMESERVERS
3952     {
3953         ScopedSetNetworkForResolv scopedSetNetworkForResolv(TEST_NETID |
3954                                                             NETID_USE_LOCAL_NAMESERVERS);
3955         expectNetIdWithLocalNameserversFlag(TEST_NETID);
3956     }
3957 
3958     // Test with setNetworkForResolv under bypassable vpn
3959     {
3960         ScopedSetNetworkForResolv scopedSetNetworkForResolv(TEST_NETID);
3961         expectDnsNetIdWithVpn(mDnsClient.netdService(), TEST_VPN_NETID, TEST_NETID);
3962     }
3963 
3964     // Create socket connected to DnsProxyListener
3965     int fd = dns_open_proxy();
3966     EXPECT_TRUE(fd > 0);
3967     unique_fd ufd(fd);
3968 
3969     // Test command with wrong netId
3970     sendCommand(fd, "getdnsnetid abc");
3971     EXPECT_EQ(ResponseCode::DnsProxyQueryResult, readResponseCode(fd));
3972     EXPECT_EQ(-EINVAL, readBE32(fd));
3973 
3974     // Test unsupported command
3975     sendCommand(fd, "getdnsnetidNotSupported");
3976     // Keep in sync with FrameworkListener.cpp (500, "Command not recognized")
3977     EXPECT_EQ(500, readResponseCode(fd));
3978 }
3979 
TEST_F(ResolverTest,BlockDnsQueryWithUidRule)3980 TEST_F(ResolverTest, BlockDnsQueryWithUidRule) {
3981     // This test relies on blocking traffic on loopback, which xt_qtaguid does not do.
3982     // See aosp/358413 and b/34444781 for why.
3983     SKIP_IF_BPF_NOT_SUPPORTED;
3984 
3985     constexpr char listen_addr1[] = "127.0.0.4";
3986     constexpr char listen_addr2[] = "::1";
3987     constexpr char host_name[] = "howdy.example.com.";
3988     const std::vector<DnsRecord> records = {
3989             {host_name, ns_type::ns_t_a, "1.2.3.4"},
3990             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
3991     };
3992     INetd* netdService = mDnsClient.netdService();
3993 
3994     test::DNSResponder dns1(listen_addr1);
3995     test::DNSResponder dns2(listen_addr2);
3996     StartDns(dns1, records);
3997     StartDns(dns2, records);
3998 
3999     std::vector<std::string> servers = {listen_addr1, listen_addr2};
4000     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
4001     dns1.clearQueries();
4002     dns2.clearQueries();
4003 
4004     ScopeBlockedUIDRule scopeBlockUidRule(netdService, TEST_UID);
4005     // Dns Query
4006     int fd1 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_a, 0);
4007     int fd2 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_aaaa, 0);
4008     EXPECT_TRUE(fd1 != -1);
4009     EXPECT_TRUE(fd2 != -1);
4010 
4011     uint8_t buf[MAXPACKET] = {};
4012     int rcode;
4013     int res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
4014     EXPECT_EQ(-ECONNREFUSED, res);
4015 
4016     memset(buf, 0, MAXPACKET);
4017     res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
4018     EXPECT_EQ(-ECONNREFUSED, res);
4019 }
4020 
TEST_F(ResolverTest,EnforceDnsUid)4021 TEST_F(ResolverTest, EnforceDnsUid) {
4022     SKIP_IF_BPF_NOT_SUPPORTED;
4023 
4024     constexpr char listen_addr1[] = "127.0.0.4";
4025     constexpr char listen_addr2[] = "::1";
4026     constexpr char host_name[] = "howdy.example.com.";
4027     const std::vector<DnsRecord> records = {
4028             {host_name, ns_type::ns_t_a, "1.2.3.4"},
4029             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
4030     };
4031     INetd* netdService = mDnsClient.netdService();
4032 
4033     test::DNSResponder dns1(listen_addr1);
4034     test::DNSResponder dns2(listen_addr2);
4035     StartDns(dns1, records);
4036     StartDns(dns2, records);
4037 
4038     // switch uid of DNS queries from applications to AID_DNS
4039     ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
4040     parcel.servers = {listen_addr1, listen_addr2};
4041     ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(parcel).isOk());
4042 
4043     uint8_t buf[MAXPACKET] = {};
4044     int rcode;
4045     {
4046         ScopeBlockedUIDRule scopeBlockUidRule(netdService, TEST_UID);
4047         // Dns Queries should be blocked
4048         int fd1 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_a, 0);
4049         int fd2 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_aaaa, 0);
4050         EXPECT_TRUE(fd1 != -1);
4051         EXPECT_TRUE(fd2 != -1);
4052 
4053         int res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
4054         EXPECT_EQ(-ECONNREFUSED, res);
4055 
4056         memset(buf, 0, MAXPACKET);
4057         res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
4058         EXPECT_EQ(-ECONNREFUSED, res);
4059     }
4060 
4061     parcel.resolverOptions.enforceDnsUid = true;
4062     ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(parcel).isOk());
4063     {
4064         ScopeBlockedUIDRule scopeBlockUidRule(netdService, TEST_UID);
4065         // Dns Queries should NOT be blocked
4066         int fd1 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_a, 0);
4067         int fd2 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_aaaa, 0);
4068         EXPECT_TRUE(fd1 != -1);
4069         EXPECT_TRUE(fd2 != -1);
4070 
4071         int res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
4072         EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
4073 
4074         memset(buf, 0, MAXPACKET);
4075         res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
4076         EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
4077 
4078         // @TODO: So far we know that uid of DNS queries are no more set to DNS requester. But we
4079         // don't check if they are actually being set to AID_DNS, because system uids are always
4080         // allowed in bpf_owner_match(). Audit by firewallSetUidRule(AID_DNS) + sending queries is
4081         // infeasible. Fix it if the behavior of bpf_owner_match() is changed in the future, or if
4082         // we have better idea to deal with this.
4083     }
4084 }
4085 
4086 namespace {
4087 
4088 const std::string kDotConnectTimeoutMsFlag(
4089         "persist.device_config.netd_native.dot_connect_timeout_ms");
4090 
4091 class ScopedSystemProperties {
4092   public:
ScopedSystemProperties(const std::string & key,const std::string & value)4093     explicit ScopedSystemProperties(const std::string& key, const std::string& value)
4094         : mStoredKey(key) {
4095         mStoredValue = android::base::GetProperty(key, "");
4096         android::base::SetProperty(key, value);
4097     }
~ScopedSystemProperties()4098     ~ScopedSystemProperties() { android::base::SetProperty(mStoredKey, mStoredValue); }
4099 
4100   private:
4101     std::string mStoredKey;
4102     std::string mStoredValue;
4103 };
4104 
4105 }  // namespace
4106 
TEST_F(ResolverTest,ConnectTlsServerTimeout)4107 TEST_F(ResolverTest, ConnectTlsServerTimeout) {
4108     constexpr int expectedTimeout = 1000;
4109     constexpr char hostname1[] = "query1.example.com.";
4110     constexpr char hostname2[] = "query2.example.com.";
4111     const std::vector<DnsRecord> records = {
4112             {hostname1, ns_type::ns_t_a, "1.2.3.4"},
4113             {hostname2, ns_type::ns_t_a, "1.2.3.5"},
4114     };
4115 
4116     test::DNSResponder dns;
4117     StartDns(dns, records);
4118     test::DnsTlsFrontend tls;
4119     ASSERT_TRUE(tls.startServer());
4120 
4121     // The resolver will adjust the timeout value to 1000ms since the value is too small.
4122     ScopedSystemProperties scopedSystemProperties(kDotConnectTimeoutMsFlag, "100");
4123 
4124     // Re-setup test network to make experiment flag take effect.
4125     resetNetwork();
4126 
4127     // Set up resolver to opportunistic mode with the default configuration.
4128     const ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
4129     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
4130     EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
4131     EXPECT_TRUE(tls.waitForQueries(1));
4132     tls.clearQueries();
4133     dns.clearQueries();
4134 
4135     // The server becomes unresponsive to the handshake request.
4136     tls.setHangOnHandshakeForTesting(true);
4137 
4138     // Expect the things happening in getaddrinfo():
4139     //   1. Connect to the private DNS server.
4140     //   2. SSL handshake times out.
4141     //   3. Fallback to UDP transport, and then get the answer.
4142     const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
4143     auto [result, timeTakenMs] = safe_getaddrinfo_time_taken(hostname1, nullptr, hints);
4144 
4145     EXPECT_NE(nullptr, result);
4146     EXPECT_EQ(0, tls.queries());
4147     EXPECT_EQ(1U, GetNumQueries(dns, hostname1));
4148     EXPECT_EQ(records.at(0).addr, ToString(result));
4149 
4150     // A loose upper bound is set by adding 2000ms buffer time. Theoretically, getaddrinfo()
4151     // should just take a bit more than expetTimeout milliseconds.
4152     EXPECT_GE(timeTakenMs, expectedTimeout);
4153     EXPECT_LE(timeTakenMs, expectedTimeout + 2000);
4154 
4155     // Set the server to be responsive. Verify that the resolver will attempt to reconnect
4156     // to the server and then get the result within the timeout.
4157     tls.setHangOnHandshakeForTesting(false);
4158     std::tie(result, timeTakenMs) = safe_getaddrinfo_time_taken(hostname2, nullptr, hints);
4159 
4160     EXPECT_NE(nullptr, result);
4161     EXPECT_TRUE(tls.waitForQueries(1));
4162     EXPECT_EQ(1U, GetNumQueries(dns, hostname2));
4163     EXPECT_EQ(records.at(1).addr, ToString(result));
4164 
4165     EXPECT_LE(timeTakenMs, expectedTimeout);
4166 }
4167 
TEST_F(ResolverTest,FlushNetworkCache)4168 TEST_F(ResolverTest, FlushNetworkCache) {
4169     SKIP_IF_REMOTE_VERSION_LESS_THAN(mDnsClient.resolvService(), 4);
4170     test::DNSResponder dns;
4171     StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, kHelloExampleComAddrV4}});
4172     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
4173 
4174     const hostent* result = gethostbyname("hello");
4175     EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, kHelloExampleCom));
4176 
4177     // get result from cache
4178     result = gethostbyname("hello");
4179     EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, kHelloExampleCom));
4180 
4181     EXPECT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
4182 
4183     result = gethostbyname("hello");
4184     EXPECT_EQ(2U, GetNumQueriesForType(dns, ns_type::ns_t_a, kHelloExampleCom));
4185 }
4186 
TEST_F(ResolverTest,FlushNetworkCache_random)4187 TEST_F(ResolverTest, FlushNetworkCache_random) {
4188     SKIP_IF_REMOTE_VERSION_LESS_THAN(mDnsClient.resolvService(), 4);
4189     constexpr int num_flush = 10;
4190     constexpr int num_queries = 20;
4191     test::DNSResponder dns;
4192     StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, kHelloExampleComAddrV4}});
4193     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
4194     const addrinfo hints = {.ai_family = AF_INET};
4195 
4196     std::thread t([this]() {
4197         for (int i = 0; i < num_flush; ++i) {
4198             unsigned delay = arc4random_uniform(10 * 1000);  // 10ms
4199             usleep(delay);
4200             EXPECT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
4201         }
4202     });
4203 
4204     for (int i = 0; i < num_queries; ++i) {
4205         ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
4206         EXPECT_TRUE(result != nullptr);
4207         EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
4208     }
4209     t.join();
4210 }
4211 
4212 // flush cache while one query is wait-for-response, another is pending.
TEST_F(ResolverTest,FlushNetworkCache_concurrent)4213 TEST_F(ResolverTest, FlushNetworkCache_concurrent) {
4214     SKIP_IF_REMOTE_VERSION_LESS_THAN(mDnsClient.resolvService(), 4);
4215     const char* listen_addr1 = "127.0.0.9";
4216     const char* listen_addr2 = "127.0.0.10";
4217     test::DNSResponder dns1(listen_addr1);
4218     test::DNSResponder dns2(listen_addr2);
4219     StartDns(dns1, {{kHelloExampleCom, ns_type::ns_t_a, kHelloExampleComAddrV4}});
4220     StartDns(dns2, {{kHelloExampleCom, ns_type::ns_t_a, kHelloExampleComAddrV4}});
4221     addrinfo hints = {.ai_family = AF_INET};
4222 
4223     // step 1: set server#1 into deferred responding mode
4224     dns1.setDeferredResp(true);
4225     std::thread t1([&listen_addr1, &hints, this]() {
4226         ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr1}));
4227         // step 3: query
4228         ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
4229         // step 9: check result
4230         EXPECT_TRUE(result != nullptr);
4231         EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
4232     });
4233 
4234     // step 2: wait for the query to reach the server
4235     while (GetNumQueries(dns1, kHelloExampleCom) == 0) {
4236         usleep(1000);  // 1ms
4237     }
4238 
4239     std::thread t2([&listen_addr2, &hints, &dns2, this]() {
4240         ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr2}));
4241         // step 5: query (should be blocked in resolver)
4242         ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
4243         // step 7: check result
4244         EXPECT_TRUE(result != nullptr);
4245         EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
4246         EXPECT_EQ(1U, GetNumQueriesForType(dns2, ns_type::ns_t_a, kHelloExampleCom));
4247     });
4248 
4249     // step 4: wait a bit for the 2nd query to enter pending state
4250     usleep(100 * 1000);  // 100ms
4251     // step 6: flush cache (will unblock pending queries)
4252     EXPECT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
4253     t2.join();
4254 
4255     // step 8: resume server#1
4256     dns1.setDeferredResp(false);
4257     t1.join();
4258 
4259     // step 10: verify if result is correctly cached
4260     dns2.clearQueries();
4261     ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
4262     EXPECT_EQ(0U, GetNumQueries(dns2, kHelloExampleCom));
4263     EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
4264 }
4265 
4266 // TODO: Perhaps to have a boundary conditions test for TCP and UDP.
TEST_F(ResolverTest,TcpQueryWithOversizePayload)4267 TEST_F(ResolverTest, TcpQueryWithOversizePayload) {
4268     test::DNSResponder dns;
4269     StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, kHelloExampleComAddrV4}});
4270     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
4271 
4272     int fd = dns_open_proxy();
4273     ASSERT_TRUE(fd > 0);
4274 
4275     // Sending DNS query over TCP once the packet sizes exceed 512 bytes.
4276     // The raw data is combined with Question section and Additional section
4277     // Question section : query "hello.example.com", type A, class IN
4278     // Additional section : type OPT (41), Option PADDING, Option Length 546
4279     // Padding option which allows DNS clients and servers to artificially
4280     // increase the size of a DNS message by a variable number of bytes.
4281     // See also RFC7830, section 3
4282     const std::string query =
4283             "+c0BAAABAAAAAAABBWhlbGxvB2V4YW1wbGUDY29tAAABAAEAACkgAAAAgAACJgAMAiIAAAAAAAAAAAAAAAAAA"
4284             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
4285             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
4286             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
4287             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
4288             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
4289             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
4290             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
4291             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
4292             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
4293     const std::string cmd =
4294             "resnsend " + std::to_string(TEST_NETID) + " 0 " /* ResNsendFlags */ + query + '\0';
4295     ssize_t rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
4296     EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
4297     expectAnswersValid(fd, AF_INET, kHelloExampleComAddrV4);
4298     EXPECT_EQ(1U, GetNumQueriesForProtocol(dns, IPPROTO_TCP, kHelloExampleCom));
4299     EXPECT_EQ(0U, GetNumQueriesForProtocol(dns, IPPROTO_UDP, kHelloExampleCom));
4300 }
4301 
TEST_F(ResolverTest,TruncatedRspMode)4302 TEST_F(ResolverTest, TruncatedRspMode) {
4303     constexpr char listen_addr[] = "127.0.0.4";
4304     constexpr char listen_addr2[] = "127.0.0.5";
4305     constexpr char listen_srv[] = "53";
4306 
4307     test::DNSResponder dns(listen_addr, listen_srv, static_cast<ns_rcode>(-1));
4308     test::DNSResponder dns2(listen_addr2, listen_srv, static_cast<ns_rcode>(-1));
4309     // dns supports UDP only, dns2 support UDP and TCP
4310     dns.setResponseProbability(0.0, IPPROTO_TCP);
4311     StartDns(dns, kLargeCnameChainRecords);
4312     StartDns(dns2, kLargeCnameChainRecords);
4313 
4314     const struct TestConfig {
4315         const std::optional<int32_t> tcMode;
4316         const bool ret;
4317         const unsigned numQueries;
4318         std::string asParameters() const {
4319             return StringPrintf("tcMode: %d, ret: %s, numQueries: %u", tcMode.value_or(-1),
4320                                 ret ? "true" : "false", numQueries);
4321         }
4322     } testConfigs[]{
4323             // clang-format off
4324             {std::nullopt,                                      true,  0}, /* mode unset */
4325             {aidl::android::net::IDnsResolver::TC_MODE_DEFAULT, true,  0}, /* default mode */
4326             {aidl::android::net::IDnsResolver::TC_MODE_UDP_TCP, true,  1}, /* alternative mode */
4327             {-666,                                              false, 1}, /* invalid input */
4328             // clang-format on
4329     };
4330 
4331     for (const auto& config : testConfigs) {
4332         SCOPED_TRACE(config.asParameters());
4333 
4334         ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
4335         parcel.servers = {listen_addr, listen_addr2};
4336         if (config.tcMode) {
4337             parcel.resolverOptions.tcMode = config.tcMode.value();
4338         }
4339         ASSERT_EQ(mDnsClient.resolvService()->setResolverConfiguration(parcel).isOk(), config.ret);
4340 
4341         const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
4342         ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
4343         ASSERT_TRUE(result != nullptr);
4344         EXPECT_EQ(ToString(result), kHelloExampleComAddrV4);
4345         // TC_MODE_DEFAULT: resolver retries on TCP-only on each name server.
4346         // TC_MODE_UDP_TCP: resolver retries on TCP on the same server, falls back to UDP from next.
4347         ASSERT_EQ(GetNumQueriesForProtocol(dns, IPPROTO_UDP, kHelloExampleCom), 1U);
4348         ASSERT_EQ(GetNumQueriesForProtocol(dns, IPPROTO_TCP, kHelloExampleCom), 1U);
4349         ASSERT_EQ(GetNumQueriesForProtocol(dns2, IPPROTO_UDP, kHelloExampleCom), config.numQueries);
4350         ASSERT_EQ(GetNumQueriesForProtocol(dns2, IPPROTO_TCP, kHelloExampleCom), 1U);
4351 
4352         dns.clearQueries();
4353         dns2.clearQueries();
4354         ASSERT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
4355     }
4356 }
4357 
TEST_F(ResolverTest,RepeatedSetup_ResolverStatusRemains)4358 TEST_F(ResolverTest, RepeatedSetup_ResolverStatusRemains) {
4359     constexpr char unusable_listen_addr[] = "127.0.0.3";
4360     constexpr char listen_addr[] = "127.0.0.4";
4361     constexpr char hostname[] = "a.hello.query.";
4362     const auto repeatedSetResolversFromParcel = [&](const ResolverParamsParcel& parcel) {
4363         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
4364         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
4365         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
4366     };
4367 
4368     test::DNSResponder dns(listen_addr);
4369     StartDns(dns, {{hostname, ns_type::ns_t_a, "1.2.3.3"}});
4370     test::DnsTlsFrontend tls1(listen_addr, "853", listen_addr, "53");
4371     ASSERT_TRUE(tls1.startServer());
4372 
4373     // Private DNS off mode.
4374     ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
4375     parcel.servers = {unusable_listen_addr, listen_addr};
4376     parcel.tlsServers.clear();
4377     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
4378 
4379     // Send a query.
4380     const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
4381     EXPECT_NE(safe_getaddrinfo(hostname, nullptr, &hints), nullptr);
4382 
4383     // Check the stats as expected.
4384     const std::vector<NameserverStats> expectedCleartextDnsStats = {
4385             NameserverStats(unusable_listen_addr).setInternalErrors(1),
4386             NameserverStats(listen_addr).setSuccesses(1),
4387     };
4388     EXPECT_TRUE(expectStatsFromGetResolverInfo(expectedCleartextDnsStats));
4389     EXPECT_EQ(GetNumQueries(dns, hostname), 1U);
4390 
4391     // The stats is supposed to remain as long as the list of cleartext DNS servers is unchanged.
4392     static const struct TestConfig {
4393         std::vector<std::string> servers;
4394         std::vector<std::string> tlsServers;
4395         std::string tlsName;
4396     } testConfigs[] = {
4397             // Private DNS opportunistic mode.
4398             {{listen_addr, unusable_listen_addr}, {listen_addr, unusable_listen_addr}, ""},
4399             {{unusable_listen_addr, listen_addr}, {unusable_listen_addr, listen_addr}, ""},
4400 
4401             // Private DNS strict mode.
4402             {{listen_addr, unusable_listen_addr}, {"127.0.0.100"}, kDefaultPrivateDnsHostName},
4403             {{unusable_listen_addr, listen_addr}, {"127.0.0.100"}, kDefaultPrivateDnsHostName},
4404 
4405             // Private DNS off mode.
4406             {{unusable_listen_addr, listen_addr}, {}, ""},
4407             {{listen_addr, unusable_listen_addr}, {}, ""},
4408     };
4409 
4410     for (const auto& config : testConfigs) {
4411         SCOPED_TRACE(fmt::format("testConfig: [{}] [{}] [{}]", fmt::join(config.servers, ","),
4412                                  fmt::join(config.tlsServers, ","), config.tlsName));
4413         parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
4414         parcel.servers = config.servers;
4415         parcel.tlsServers = config.tlsServers;
4416         parcel.tlsName = config.tlsName;
4417         repeatedSetResolversFromParcel(parcel);
4418         EXPECT_TRUE(expectStatsFromGetResolverInfo(expectedCleartextDnsStats));
4419 
4420         // The stats remains when the list of search domains changes.
4421         parcel.domains.push_back("tmp.domains");
4422         repeatedSetResolversFromParcel(parcel);
4423         EXPECT_TRUE(expectStatsFromGetResolverInfo(expectedCleartextDnsStats));
4424 
4425         // The stats remains when the parameters change (except maxSamples).
4426         parcel.sampleValiditySeconds++;
4427         parcel.successThreshold++;
4428         parcel.minSamples++;
4429         parcel.baseTimeoutMsec++;
4430         parcel.retryCount++;
4431         repeatedSetResolversFromParcel(parcel);
4432         EXPECT_TRUE(expectStatsFromGetResolverInfo(expectedCleartextDnsStats));
4433     }
4434 
4435     // The cache remains.
4436     EXPECT_NE(safe_getaddrinfo(hostname, nullptr, &hints), nullptr);
4437     EXPECT_EQ(GetNumQueries(dns, hostname), 1U);
4438 }
4439 
TEST_F(ResolverTest,RepeatedSetup_NoRedundantPrivateDnsValidation)4440 TEST_F(ResolverTest, RepeatedSetup_NoRedundantPrivateDnsValidation) {
4441     const std::string addr1 = getUniqueIPv4Address();  // For a workable DNS server.
4442     const std::string addr2 = getUniqueIPv4Address();  // For an unresponsive DNS server.
4443     const std::string unusable_addr = getUniqueIPv4Address();
4444     const auto waitForPrivateDnsStateUpdated = []() {
4445         // A buffer time for the PrivateDnsConfiguration instance to update its map,
4446         // mPrivateDnsValidateThreads, which is used for tracking validation threads.
4447         // Since there is a time gap between when PrivateDnsConfiguration reports
4448         // onPrivateDnsValidationEvent and when PrivateDnsConfiguration updates the map, this is a
4449         // workaround to avoid the test starts a subsequent resolver setup during the time gap.
4450         // TODO: Report onPrivateDnsValidationEvent after all the relevant updates are complete.
4451         // Reference to b/152009023.
4452         std::this_thread::sleep_for(20ms);
4453     };
4454 
4455     test::DNSResponder dns1(addr1);
4456     test::DNSResponder dns2(addr2);
4457     StartDns(dns1, {});
4458     StartDns(dns2, {});
4459     test::DnsTlsFrontend workableTls(addr1, "853", addr1, "53");
4460     test::DnsTlsFrontend unresponsiveTls(addr2, "853", addr2, "53");
4461     unresponsiveTls.setHangOnHandshakeForTesting(true);
4462     ASSERT_TRUE(workableTls.startServer());
4463     ASSERT_TRUE(unresponsiveTls.startServer());
4464 
4465     // First setup.
4466     ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
4467     parcel.servers = {addr1, addr2, unusable_addr};
4468     parcel.tlsServers = {addr1, addr2, unusable_addr};
4469     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
4470 
4471     // Check the validation results.
4472     EXPECT_TRUE(WaitForPrivateDnsValidation(workableTls.listen_address(), true));
4473     EXPECT_TRUE(WaitForPrivateDnsValidation(unusable_addr, false));
4474     EXPECT_EQ(unresponsiveTls.acceptConnectionsCount(), 1);  // The validation is still in progress.
4475 
4476     static const struct TestConfig {
4477         std::vector<std::string> tlsServers;
4478         std::string tlsName;
4479     } testConfigs[] = {
4480             {{addr1, addr2, unusable_addr}, ""},
4481             {{unusable_addr, addr1, addr2}, ""},
4482             {{unusable_addr, addr1, addr2}, kDefaultPrivateDnsHostName},
4483             {{addr1, addr2, unusable_addr}, kDefaultPrivateDnsHostName},
4484     };
4485 
4486     std::string TlsNameLastTime;
4487     for (const auto& config : testConfigs) {
4488         SCOPED_TRACE(fmt::format("testConfig: [{}] [{}]", fmt::join(config.tlsServers, ","),
4489                                  config.tlsName));
4490         parcel.servers = config.tlsServers;
4491         parcel.tlsServers = config.tlsServers;
4492         parcel.tlsName = config.tlsName;
4493         parcel.caCertificate = config.tlsName.empty() ? "" : kCaCert;
4494 
4495         const bool dnsModeChanged = (TlsNameLastTime != config.tlsName);
4496 
4497         waitForPrivateDnsStateUpdated();
4498         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
4499 
4500         for (const auto& serverAddr : parcel.tlsServers) {
4501             SCOPED_TRACE(serverAddr);
4502             if (serverAddr == workableTls.listen_address()) {
4503                 if (dnsModeChanged) {
4504                     // In despite of the identical IP address, the server is regarded as a different
4505                     // server when DnsTlsServer.name is different. The resolver treats it as a
4506                     // different object and begins the validation process.
4507                     EXPECT_TRUE(WaitForPrivateDnsValidation(serverAddr, true));
4508                 }
4509             } else if (serverAddr == unresponsiveTls.listen_address()) {
4510                 // No revalidation needed for the server which have been marked as in_progesss.
4511             } else {
4512                 // Must be unusable_addr.
4513                 // In opportunistic mode, when a validation for a private DNS server fails, the
4514                 // resolver just marks the server as failed and doesn't re-evaluate it, but the
4515                 // server can be re-evaluated when setResolverConfiguration() is called.
4516                 // However, in strict mode, the resolver automatically re-evaluates the server and
4517                 // marks the server as in_progress until the validation succeeds, so repeated setup
4518                 // makes no effect.
4519                 if (dnsModeChanged || config.tlsName.empty() /* not in strict mode */) {
4520                     EXPECT_TRUE(WaitForPrivateDnsValidation(serverAddr, false));
4521                 }
4522             }
4523         }
4524 
4525         // Repeated setups make no effect in strict mode.
4526         waitForPrivateDnsStateUpdated();
4527         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
4528         if (config.tlsName.empty()) {
4529             EXPECT_TRUE(WaitForPrivateDnsValidation(unusable_addr, false));
4530         }
4531         waitForPrivateDnsStateUpdated();
4532         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
4533         if (config.tlsName.empty()) {
4534             EXPECT_TRUE(WaitForPrivateDnsValidation(unusable_addr, false));
4535         }
4536 
4537         EXPECT_EQ(unresponsiveTls.acceptConnectionsCount(), 1);
4538 
4539         TlsNameLastTime = config.tlsName;
4540     }
4541 
4542     // Check that all the validation results are caught.
4543     // Note: it doesn't mean no validation being in progress.
4544     EXPECT_FALSE(hasUncaughtPrivateDnsValidation(addr1));
4545     EXPECT_FALSE(hasUncaughtPrivateDnsValidation(addr2));
4546     EXPECT_FALSE(hasUncaughtPrivateDnsValidation(unusable_addr));
4547 }
4548 
TEST_F(ResolverTest,RepeatedSetup_KeepChangingPrivateDnsServers)4549 TEST_F(ResolverTest, RepeatedSetup_KeepChangingPrivateDnsServers) {
4550     enum TlsServerState { WORKING, UNSUPPORTED, UNRESPONSIVE };
4551     const std::string addr1 = getUniqueIPv4Address();
4552     const std::string addr2 = getUniqueIPv4Address();
4553     const auto waitForPrivateDnsStateUpdated = []() {
4554         // A buffer time for PrivateDnsConfiguration to update its state. It prevents this test
4555         // being flaky. See b/152009023 for the reason.
4556         std::this_thread::sleep_for(20ms);
4557     };
4558 
4559     test::DNSResponder dns1(addr1);
4560     test::DNSResponder dns2(addr2);
4561     StartDns(dns1, {});
4562     StartDns(dns2, {});
4563     test::DnsTlsFrontend tls1(addr1, "853", addr1, "53");
4564     test::DnsTlsFrontend tls2(addr2, "853", addr2, "53");
4565     ASSERT_TRUE(tls1.startServer());
4566     ASSERT_TRUE(tls2.startServer());
4567 
4568     static const struct TestConfig {
4569         std::string tlsServer;
4570         std::string tlsName;
4571         bool expectNothingHappenWhenServerUnsupported;
4572         bool expectNothingHappenWhenServerUnresponsive;
4573         std::string asTestName() const {
4574             return fmt::format("{}, {}, {}, {}", tlsServer, tlsName,
4575                                expectNothingHappenWhenServerUnsupported,
4576                                expectNothingHappenWhenServerUnresponsive);
4577         }
4578     } testConfigs[] = {
4579             {{addr1}, "", false, false},
4580             {{addr2}, "", false, false},
4581             {{addr1}, "", false, true},
4582             {{addr2}, "", false, true},
4583             {{addr1}, kDefaultPrivateDnsHostName, false, true},
4584             {{addr2}, kDefaultPrivateDnsHostName, false, true},
4585             {{addr1}, kDefaultPrivateDnsHostName, true, true},
4586             {{addr2}, kDefaultPrivateDnsHostName, true, true},
4587 
4588             // There's no new validation to start because there are already two validation threads
4589             // running (one is for addr1, the other is for addr2). This is because the comparator
4590             // doesn't compare DnsTlsServer.name. Keep the design as-is until it's known to be
4591             // harmful.
4592             {{addr1}, "", true, true},
4593             {{addr2}, "", true, true},
4594             {{addr1}, "", true, true},
4595             {{addr2}, "", true, true},
4596     };
4597 
4598     for (const auto& serverState : {WORKING, UNSUPPORTED, UNRESPONSIVE}) {
4599         int testIndex = 0;
4600         for (const auto& config : testConfigs) {
4601             SCOPED_TRACE(fmt::format("serverState:{} testIndex:{} testConfig:[{}]", serverState,
4602                                      testIndex++, config.asTestName()));
4603             auto& tls = (config.tlsServer == addr1) ? tls1 : tls2;
4604 
4605             if (serverState == UNSUPPORTED && tls.running()) ASSERT_TRUE(tls.stopServer());
4606             if (serverState != UNSUPPORTED && !tls.running()) ASSERT_TRUE(tls.startServer());
4607 
4608             tls.setHangOnHandshakeForTesting(serverState == UNRESPONSIVE);
4609             const int connectCountsBefore = tls.acceptConnectionsCount();
4610 
4611             waitForPrivateDnsStateUpdated();
4612             ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
4613             parcel.servers = {config.tlsServer};
4614             parcel.tlsServers = {config.tlsServer};
4615             parcel.tlsName = config.tlsName;
4616             parcel.caCertificate = config.tlsName.empty() ? "" : kCaCert;
4617             ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
4618 
4619             if (serverState == WORKING) {
4620                 EXPECT_TRUE(WaitForPrivateDnsValidation(config.tlsServer, true));
4621             } else if (serverState == UNSUPPORTED) {
4622                 if (config.expectNothingHappenWhenServerUnsupported) {
4623                     // It's possible that the resolver hasn't yet started to
4624                     // connect. Wait a while.
4625                     // TODO: See if we can get rid of the hard waiting time, such as comparing
4626                     // the CountDiff across two tests.
4627                     std::this_thread::sleep_for(100ms);
4628                     EXPECT_EQ(tls.acceptConnectionsCount(), connectCountsBefore);
4629                 } else {
4630                     EXPECT_TRUE(WaitForPrivateDnsValidation(config.tlsServer, false));
4631                 }
4632             } else {
4633                 // Must be UNRESPONSIVE.
4634                 // DnsTlsFrontend is the only signal for checking whether or not the resolver starts
4635                 // another validation when the server is unresponsive.
4636                 const int expectCountDiff =
4637                         config.expectNothingHappenWhenServerUnresponsive ? 0 : 1;
4638                 if (expectCountDiff == 0) {
4639                     // It's possible that the resolver hasn't yet started to
4640                     // connect. Wait a while.
4641                     std::this_thread::sleep_for(100ms);
4642                 }
4643                 const auto condition = [&]() {
4644                     return tls.acceptConnectionsCount() == connectCountsBefore + expectCountDiff;
4645                 };
4646                 EXPECT_TRUE(PollForCondition(condition));
4647             }
4648         }
4649 
4650         // Set to off mode to reset the PrivateDnsConfiguration state.
4651         ResolverParamsParcel setupOffmode = DnsResponderClient::GetDefaultResolverParamsParcel();
4652         setupOffmode.tlsServers.clear();
4653         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(setupOffmode));
4654     }
4655 
4656     // Check that all the validation results are caught.
4657     // Note: it doesn't mean no validation being in progress.
4658     EXPECT_FALSE(hasUncaughtPrivateDnsValidation(addr1));
4659     EXPECT_FALSE(hasUncaughtPrivateDnsValidation(addr2));
4660 }
4661 
TEST_F(ResolverTest,PermissionCheckOnCertificateInjection)4662 TEST_F(ResolverTest, PermissionCheckOnCertificateInjection) {
4663     ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
4664     parcel.caCertificate = kCaCert;
4665     ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(parcel).isOk());
4666 
4667     for (const uid_t uid : {AID_SYSTEM, TEST_UID}) {
4668         ScopedChangeUID scopedChangeUID(uid);
4669         auto status = mDnsClient.resolvService()->setResolverConfiguration(parcel);
4670         EXPECT_EQ(status.getExceptionCode(), EX_SECURITY);
4671     }
4672 }
4673 
4674 // Parameterized tests.
4675 // TODO: Merge the existing tests as parameterized test if possible.
4676 // TODO: Perhaps move parameterized tests to an independent file.
4677 enum class CallType { GETADDRINFO, GETHOSTBYNAME };
4678 class ResolverParameterizedTest : public ResolverTest,
4679                                   public testing::WithParamInterface<CallType> {
4680   protected:
VerifyQueryHelloExampleComV4(const test::DNSResponder & dns,const CallType calltype,const bool verifyNumQueries=true)4681     void VerifyQueryHelloExampleComV4(const test::DNSResponder& dns, const CallType calltype,
4682                                       const bool verifyNumQueries = true) {
4683         if (calltype == CallType::GETADDRINFO) {
4684             const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
4685             ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
4686             ASSERT_TRUE(result != nullptr);
4687             EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
4688         } else if (calltype == CallType::GETHOSTBYNAME) {
4689             const hostent* result = gethostbyname("hello");
4690             ASSERT_TRUE(result != nullptr);
4691             ASSERT_EQ(4, result->h_length);
4692             ASSERT_FALSE(result->h_addr_list[0] == nullptr);
4693             EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
4694             EXPECT_TRUE(result->h_addr_list[1] == nullptr);
4695         } else {
4696             FAIL() << "Unsupported call type: " << static_cast<uint32_t>(calltype);
4697         }
4698         if (verifyNumQueries) EXPECT_EQ(1U, GetNumQueries(dns, kHelloExampleCom));
4699     }
4700 };
4701 
4702 INSTANTIATE_TEST_SUITE_P(QueryCallTest, ResolverParameterizedTest,
4703                          testing::Values(CallType::GETADDRINFO, CallType::GETHOSTBYNAME),
__anonaf7621961602(const testing::TestParamInfo<CallType>& info) 4704                          [](const testing::TestParamInfo<CallType>& info) {
4705                              switch (info.param) {
4706                                  case CallType::GETADDRINFO:
4707                                      return "GetAddrInfo";
4708                                  case CallType::GETHOSTBYNAME:
4709                                      return "GetHostByName";
4710                                  default:
4711                                      return "InvalidParameter";  // Should not happen.
4712                              }
4713                          });
4714 
TEST_P(ResolverParameterizedTest,AuthoritySectionAndAdditionalSection)4715 TEST_P(ResolverParameterizedTest, AuthoritySectionAndAdditionalSection) {
4716     // DNS response may have more information in authority section and additional section.
4717     // Currently, getanswer() of packages/modules/DnsResolver/getaddrinfo.cpp doesn't parse the
4718     // content of authority section and additional section. Test these sections if they crash
4719     // the resolver, just in case. See also RFC 1035 section 4.1.
4720     const auto& calltype = GetParam();
4721     test::DNSHeader header(kDefaultDnsHeader);
4722 
4723     // Create a DNS response which has a authoritative nameserver record in authority
4724     // section and its relevant address record in additional section.
4725     //
4726     // Question
4727     //   hello.example.com.     IN      A
4728     // Answer
4729     //   hello.example.com.     IN      A   1.2.3.4
4730     // Authority:
4731     //   hello.example.com.     IN      NS  ns1.example.com.
4732     // Additional:
4733     //   ns1.example.com.       IN      A   5.6.7.8
4734     //
4735     // A response may have only question, answer, and authority section. Current testing response
4736     // should be able to cover this condition.
4737 
4738     // Question section.
4739     test::DNSQuestion question{
4740             .qname = {.name = kHelloExampleCom},
4741             .qtype = ns_type::ns_t_a,
4742             .qclass = ns_c_in,
4743     };
4744     header.questions.push_back(std::move(question));
4745 
4746     // Answer section.
4747     test::DNSRecord recordAnswer{
4748             .name = {.name = kHelloExampleCom},
4749             .rtype = ns_type::ns_t_a,
4750             .rclass = ns_c_in,
4751             .ttl = 0,  // no cache
4752     };
4753     EXPECT_TRUE(test::DNSResponder::fillRdata(kHelloExampleComAddrV4, recordAnswer));
4754     header.answers.push_back(std::move(recordAnswer));
4755 
4756     // Authority section.
4757     test::DNSRecord recordAuthority{
4758             .name = {.name = kHelloExampleCom},
4759             .rtype = ns_type::ns_t_ns,
4760             .rclass = ns_c_in,
4761             .ttl = 0,  // no cache
4762     };
4763     EXPECT_TRUE(test::DNSResponder::fillRdata("ns1.example.com.", recordAuthority));
4764     header.authorities.push_back(std::move(recordAuthority));
4765 
4766     // Additional section.
4767     test::DNSRecord recordAdditional{
4768             .name = {.name = "ns1.example.com."},
4769             .rtype = ns_type::ns_t_a,
4770             .rclass = ns_c_in,
4771             .ttl = 0,  // no cache
4772     };
4773     EXPECT_TRUE(test::DNSResponder::fillRdata("5.6.7.8", recordAdditional));
4774     header.additionals.push_back(std::move(recordAdditional));
4775 
4776     // Start DNS server.
4777     test::DNSResponder dns(test::DNSResponder::MappingType::DNS_HEADER);
4778     dns.addMappingDnsHeader(kHelloExampleCom, ns_type::ns_t_a, header);
4779     ASSERT_TRUE(dns.startServer());
4780     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
4781     dns.clearQueries();
4782 
4783     // Expect that get the address and the resolver doesn't crash.
4784     VerifyQueryHelloExampleComV4(dns, calltype);
4785 }
4786 
TEST_P(ResolverParameterizedTest,MessageCompression)4787 TEST_P(ResolverParameterizedTest, MessageCompression) {
4788     const auto& calltype = GetParam();
4789 
4790     // The response with compressed domain name by a pointer. See RFC 1035 section 4.1.4.
4791     //
4792     // Ignoring the other fields of the message, the domain name of question section and answer
4793     // section are presented as:
4794     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4795     // 12 |           5           |           h           |
4796     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4797     // 14 |           e           |           l           |
4798     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4799     // 16 |           l           |           o           |
4800     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4801     // 18 |           7           |           e           |
4802     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4803     // 20 |           x           |           a           |
4804     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4805     // 22 |           m           |           p           |
4806     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4807     // 24 |           l           |           e           |
4808     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4809     // 26 |           3           |           c           |
4810     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4811     // 28 |           o           |           m           |
4812     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4813     // 30 |           0           |          ...          |
4814     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4815     //
4816     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4817     // 35 | 1  1|                12                       |
4818     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4819     const std::vector<uint8_t> kResponseAPointer = {
4820             /* Header */
4821             0x00, 0x00, /* Transaction ID: 0x0000 */
4822             0x81, 0x80, /* Flags: qr rd ra */
4823             0x00, 0x01, /* Questions: 1 */
4824             0x00, 0x01, /* Answer RRs: 1 */
4825             0x00, 0x00, /* Authority RRs: 0 */
4826             0x00, 0x00, /* Additional RRs: 0 */
4827             /* Queries */
4828             0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
4829             0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name: hello.example.com */
4830             0x00, 0x01,                   /* Type: A */
4831             0x00, 0x01,                   /* Class: IN */
4832             /* Answers */
4833             0xc0, 0x0c,             /* Name: hello.example.com (a pointer) */
4834             0x00, 0x01,             /* Type: A */
4835             0x00, 0x01,             /* Class: IN */
4836             0x00, 0x00, 0x00, 0x00, /* Time to live: 0 */
4837             0x00, 0x04,             /* Data length: 4 */
4838             0x01, 0x02, 0x03, 0x04  /* Address: 1.2.3.4 */
4839     };
4840 
4841     // The response with compressed domain name by a sequence of labels ending with a pointer. See
4842     // RFC 1035 section 4.1.4.
4843     //
4844     // Ignoring the other fields of the message, the domain name of question section and answer
4845     // section are presented as:
4846     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4847     // 12 |           5           |           h           |
4848     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4849     // 14 |           e           |           l           |
4850     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4851     // 16 |           l           |           o           |
4852     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4853     // 18 |           7           |           e           |
4854     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4855     // 20 |           x           |           a           |
4856     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4857     // 22 |           m           |           p           |
4858     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4859     // 24 |           l           |           e           |
4860     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4861     // 26 |           3           |           c           |
4862     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4863     // 28 |           o           |           m           |
4864     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4865     // 30 |           0           |          ...          |
4866     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4867     //
4868     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4869     // 35 |           5           |           h           |
4870     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4871     // 37 |           e           |           l           |
4872     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4873     // 39 |           l           |           o           |
4874     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4875     // 41 | 1  1|                18                       |
4876     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
4877     const std::vector<uint8_t> kResponseLabelEndingWithAPointer = {
4878             /* Header */
4879             0x00, 0x00, /* Transaction ID: 0x0000 */
4880             0x81, 0x80, /* Flags: qr rd ra */
4881             0x00, 0x01, /* Questions: 1 */
4882             0x00, 0x01, /* Answer RRs: 1 */
4883             0x00, 0x00, /* Authority RRs: 0 */
4884             0x00, 0x00, /* Additional RRs: 0 */
4885             /* Queries */
4886             0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
4887             0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name: hello.example.com */
4888             0x00, 0x01,                   /* Type: A */
4889             0x00, 0x01,                   /* Class: IN */
4890             /* Answers */
4891             0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0xc0,
4892             0x12,                   /* Name: hello.example.com (a label ending with a pointer) */
4893             0x00, 0x01,             /* Type: A */
4894             0x00, 0x01,             /* Class: IN */
4895             0x00, 0x00, 0x00, 0x00, /* Time to live: 0 */
4896             0x00, 0x04,             /* Data length: 4 */
4897             0x01, 0x02, 0x03, 0x04  /* Address: 1.2.3.4 */
4898     };
4899 
4900     for (const auto& response : {kResponseAPointer, kResponseLabelEndingWithAPointer}) {
4901         SCOPED_TRACE(StringPrintf("Hex dump: %s", toHex(makeSlice(response)).c_str()));
4902 
4903         test::DNSResponder dns(test::DNSResponder::MappingType::BINARY_PACKET);
4904         dns.addMappingBinaryPacket(kHelloExampleComQueryV4, response);
4905         StartDns(dns, {});
4906         ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
4907 
4908         // Expect no cache because the TTL of testing responses are 0.
4909         VerifyQueryHelloExampleComV4(dns, calltype);
4910     }
4911 }
4912 
TEST_P(ResolverParameterizedTest,TruncatedResponse)4913 TEST_P(ResolverParameterizedTest, TruncatedResponse) {
4914     const auto& calltype = GetParam();
4915 
4916     test::DNSResponder dns;
4917     StartDns(dns, kLargeCnameChainRecords);
4918     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
4919 
4920     // Expect UDP response is truncated. The resolver retries over TCP. See RFC 1035 section 4.2.1.
4921     VerifyQueryHelloExampleComV4(dns, calltype, false);
4922     EXPECT_EQ(1U, GetNumQueriesForProtocol(dns, IPPROTO_UDP, kHelloExampleCom));
4923     EXPECT_EQ(1U, GetNumQueriesForProtocol(dns, IPPROTO_TCP, kHelloExampleCom));
4924 }
4925 
TEST_F(ResolverTest,KeepListeningUDP)4926 TEST_F(ResolverTest, KeepListeningUDP) {
4927     constexpr char listen_addr1[] = "127.0.0.4";
4928     constexpr char listen_addr2[] = "127.0.0.5";
4929     constexpr char host_name[] = "howdy.example.com.";
4930     const std::vector<DnsRecord> records = {
4931             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
4932     };
4933     const std::vector<int> params = {300, 25, 8, 8, 1000 /* BASE_TIMEOUT_MSEC */,
4934                                      1 /* retry count */};
4935     const int delayTimeMs = 1500;
4936 
4937     test::DNSResponder neverRespondDns(listen_addr2, "53", static_cast<ns_rcode>(-1));
4938     neverRespondDns.setResponseProbability(0.0);
4939     StartDns(neverRespondDns, records);
4940     ScopedSystemProperties scopedSystemProperties(
4941             "persist.device_config.netd_native.keep_listening_udp", "1");
4942     // Re-setup test network to make experiment flag take effect.
4943     resetNetwork();
4944 
4945     ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr1, listen_addr2},
4946                                                   kDefaultSearchDomains, params));
4947     // There are 2 DNS servers for this test.
4948     // |delayedDns| will be blocked for |delayTimeMs|, then start to respond to requests.
4949     // |neverRespondDns| will never respond.
4950     // In the first try, resolver will send query to |delayedDns| but get timeout error
4951     // because |delayTimeMs| > DNS timeout.
4952     // Then it's the second try, resolver will send query to |neverRespondDns| and
4953     // listen on both servers. Resolver will receive the answer coming from |delayedDns|.
4954 
4955     test::DNSResponder delayedDns(listen_addr1);
4956     delayedDns.setResponseDelayMs(delayTimeMs);
4957     StartDns(delayedDns, records);
4958 
4959     // Specify hints to ensure resolver doing query only 1 round.
4960     const addrinfo hints = {.ai_family = AF_INET6, .ai_socktype = SOCK_DGRAM};
4961     ScopedAddrinfo result = safe_getaddrinfo(host_name, nullptr, &hints);
4962     EXPECT_TRUE(result != nullptr);
4963 
4964     std::string result_str = ToString(result);
4965     EXPECT_TRUE(result_str == "::1.2.3.4") << ", result_str='" << result_str << "'";
4966 }
4967 
TEST_F(ResolverTest,GetAddrInfoParallelLookupTimeout)4968 TEST_F(ResolverTest, GetAddrInfoParallelLookupTimeout) {
4969     constexpr char listen_addr[] = "127.0.0.4";
4970     constexpr char host_name[] = "howdy.example.com.";
4971     constexpr int TIMING_TOLERANCE_MS = 200;
4972     constexpr int DNS_TIMEOUT_MS = 1000;
4973     const std::vector<DnsRecord> records = {
4974             {host_name, ns_type::ns_t_a, "1.2.3.4"},
4975             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
4976     };
4977     const std::vector<int> params = {300, 25, 8, 8, DNS_TIMEOUT_MS /* BASE_TIMEOUT_MSEC */,
4978                                      1 /* retry count */};
4979     test::DNSResponder neverRespondDns(listen_addr, "53", static_cast<ns_rcode>(-1));
4980     neverRespondDns.setResponseProbability(0.0);
4981     StartDns(neverRespondDns, records);
4982     ScopedSystemProperties scopedSystemProperties(
4983             "persist.device_config.netd_native.parallel_lookup", "1");
4984     // The default value of parallel_lookup_sleep_time should be very small
4985     // that we can ignore in this test case.
4986     // Re-setup test network to make experiment flag take effect.
4987     resetNetwork();
4988 
4989     ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr}, kDefaultSearchDomains, params));
4990     neverRespondDns.clearQueries();
4991 
4992     // Use a never respond DNS server to verify if the A/AAAA queries are sent in parallel.
4993     // The resolver parameters are set to timeout 1s and retry 1 times.
4994     // So we expect the safe_getaddrinfo_time_taken() might take ~1s to
4995     // return when parallel lookup is enabled. And the DNS server should receive 2 queries.
4996     const addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM};
4997     auto [result, timeTakenMs] = safe_getaddrinfo_time_taken(host_name, nullptr, hints);
4998 
4999     EXPECT_TRUE(result == nullptr);
5000     EXPECT_NEAR(DNS_TIMEOUT_MS, timeTakenMs, TIMING_TOLERANCE_MS)
5001             << "took time should approximate equal timeout";
5002     EXPECT_EQ(2U, GetNumQueries(neverRespondDns, host_name));
5003 }
5004 
TEST_F(ResolverTest,GetAddrInfoParallelLookupSleepTime)5005 TEST_F(ResolverTest, GetAddrInfoParallelLookupSleepTime) {
5006     constexpr char listen_addr[] = "127.0.0.4";
5007     constexpr int TIMING_TOLERANCE_MS = 200;
5008     const std::vector<DnsRecord> records = {
5009             {kHelloExampleCom, ns_type::ns_t_a, kHelloExampleComAddrV4},
5010             {kHelloExampleCom, ns_type::ns_t_aaaa, kHelloExampleComAddrV6},
5011     };
5012     const std::vector<int> params = {300, 25, 8, 8, 1000 /* BASE_TIMEOUT_MSEC */,
5013                                      1 /* retry count */};
5014     test::DNSResponder dns(listen_addr);
5015     StartDns(dns, records);
5016     ScopedSystemProperties scopedSystemProperties1(
5017             "persist.device_config.netd_native.parallel_lookup", "1");
5018     constexpr int PARALLEL_LOOKUP_SLEEP_TIME_MS = 500;
5019     ScopedSystemProperties scopedSystemProperties2(
5020             "persist.device_config.netd_native.parallel_lookup_sleep_time",
5021             std::to_string(PARALLEL_LOOKUP_SLEEP_TIME_MS));
5022     // Re-setup test network to make experiment flag take effect.
5023     resetNetwork();
5024 
5025     ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr}, kDefaultSearchDomains, params));
5026     dns.clearQueries();
5027 
5028     // Expect the safe_getaddrinfo_time_taken() might take ~500ms to return because we set
5029     // parallel_lookup_sleep_time to 500ms.
5030     const addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM};
5031     auto [result, timeTakenMs] = safe_getaddrinfo_time_taken(kHelloExampleCom, nullptr, hints);
5032 
5033     EXPECT_NE(nullptr, result);
5034     EXPECT_THAT(ToStrings(result), testing::UnorderedElementsAreArray(
5035                                            {kHelloExampleComAddrV4, kHelloExampleComAddrV6}));
5036     EXPECT_NEAR(PARALLEL_LOOKUP_SLEEP_TIME_MS, timeTakenMs, TIMING_TOLERANCE_MS)
5037             << "took time should approximate equal timeout";
5038     EXPECT_EQ(2U, GetNumQueries(dns, kHelloExampleCom));
5039 
5040     // Expect the PARALLEL_LOOKUP_SLEEP_TIME_MS won't affect the query under cache hit case.
5041     dns.clearQueries();
5042     std::tie(result, timeTakenMs) = safe_getaddrinfo_time_taken(kHelloExampleCom, nullptr, hints);
5043     EXPECT_NE(nullptr, result);
5044     EXPECT_THAT(ToStrings(result), testing::UnorderedElementsAreArray(
5045                                            {kHelloExampleComAddrV4, kHelloExampleComAddrV6}));
5046     EXPECT_GT(PARALLEL_LOOKUP_SLEEP_TIME_MS, timeTakenMs);
5047     EXPECT_EQ(0U, GetNumQueries(dns, kHelloExampleCom));
5048 }
5049 
TEST_F(ResolverTest,BlockDnsQueryUidDoesNotLeadToBadServer)5050 TEST_F(ResolverTest, BlockDnsQueryUidDoesNotLeadToBadServer) {
5051     // This test relies on blocking traffic on loopback, which xt_qtaguid does not do.
5052     // See aosp/358413 and b/34444781 for why.
5053     SKIP_IF_BPF_NOT_SUPPORTED;
5054 
5055     constexpr char listen_addr1[] = "127.0.0.4";
5056     constexpr char listen_addr2[] = "::1";
5057     test::DNSResponder dns1(listen_addr1);
5058     test::DNSResponder dns2(listen_addr2);
5059     StartDns(dns1, {});
5060     StartDns(dns2, {});
5061 
5062     std::vector<std::string> servers = {listen_addr1, listen_addr2};
5063     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
5064     dns1.clearQueries();
5065     dns2.clearQueries();
5066     {
5067         ScopeBlockedUIDRule scopeBlockUidRule(mDnsClient.netdService(), TEST_UID);
5068         // Start querying ten times.
5069         for (int i = 0; i < 10; i++) {
5070             std::string hostName = fmt::format("blocked{}.com", i);
5071             const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
5072             EXPECT_EQ(safe_getaddrinfo(hostName.c_str(), nullptr, &hints), nullptr);
5073         }
5074     }
5075     // Since all query packets are blocked, we should not see any stats of them.
5076     const std::vector<NameserverStats> expectedEmptyDnsStats = {
5077             NameserverStats(listen_addr1),
5078             NameserverStats(listen_addr2),
5079     };
5080     expectStatsFromGetResolverInfo(expectedEmptyDnsStats);
5081     EXPECT_EQ(dns1.queries().size(), 0U);
5082     EXPECT_EQ(dns2.queries().size(), 0U);
5083 }
5084