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