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 requied 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 <arpa/inet.h>
21 #include <arpa/nameser.h>
22 #include <netdb.h>
23 #include <netinet/in.h>
24 #include <poll.h> /* poll */
25 #include <resolv.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <sys/socket.h>
30 #include <sys/un.h>
31 #include <unistd.h>
32
33 #include <algorithm>
34 #include <chrono>
35 #include <iterator>
36 #include <numeric>
37 #include <thread>
38
39 #include <android-base/parseint.h>
40 #include <android-base/stringprintf.h>
41 #include <android-base/unique_fd.h>
42 #include <android/multinetwork.h> // ResNsendFlags
43 #include <cutils/sockets.h>
44 #include <gmock/gmock-matchers.h>
45 #include <gtest/gtest.h>
46 #include <openssl/base64.h>
47 #include <private/android_filesystem_config.h>
48 #include <utils/Log.h>
49
50 #include "NetdClient.h"
51 #include "netid_client.h" // NETID_UNSET
52 #include "netd_resolv/params.h" // MAX_NS
53
54 #include "dns_responder/dns_responder.h"
55 #include "dns_responder/dns_responder_client.h"
56 #include "dns_responder/dns_tls_frontend.h"
57
58 #include "NetdConstants.h"
59 #include "ResolverStats.h"
60
61 #include "android/net/IDnsResolver.h"
62 #include "binder/IServiceManager.h"
63 #include "netdutils/ResponseCode.h"
64 #include "netdutils/SocketOption.h"
65
66 // TODO: make this dynamic and stop depending on implementation details.
67 constexpr int TEST_NETID = 30;
68 // Valid VPN netId range is 100 ~ 65535
69 constexpr int TEST_VPN_NETID = 65502;
70 constexpr int MAXPACKET = (8 * 1024);
71
72 // Semi-public Bionic hook used by the NDK (frameworks/base/native/android/net.c)
73 // Tested here for convenience.
74 extern "C" int android_getaddrinfofornet(const char* hostname, const char* servname,
75 const addrinfo* hints, unsigned netid, unsigned mark,
76 struct addrinfo** result);
77
78 using android::base::ParseInt;
79 using android::base::StringPrintf;
80 using android::base::unique_fd;
81 using android::net::ResolverStats;
82 using android::netdutils::enableSockopt;
83 using android::netdutils::ResponseCode;
84
85 // TODO: move into libnetdutils?
86 namespace {
safe_getaddrinfo(const char * node,const char * service,const struct addrinfo * hints)87 ScopedAddrinfo safe_getaddrinfo(const char* node, const char* service,
88 const struct addrinfo* hints) {
89 addrinfo* result = nullptr;
90 if (getaddrinfo(node, service, hints, &result) != 0) {
91 result = nullptr; // Should already be the case, but...
92 }
93 return ScopedAddrinfo(result);
94 }
95 } // namespace
96
97 class ResolverTest : public ::testing::Test {
98 protected:
99 struct DnsRecord {
100 std::string host_name; // host name
101 ns_type type; // record type
102 std::string addr; // ipv4/v6 address
103 };
104
SetUp()105 void SetUp() { mDnsClient.SetUp(); }
TearDown()106 void TearDown() {
107 mDnsClient.TearDown();
108 }
109
GetResolverInfo(std::vector<std::string> * servers,std::vector<std::string> * domains,std::vector<std::string> * tlsServers,res_params * params,std::vector<ResolverStats> * stats,int * wait_for_pending_req_timeout_count)110 bool GetResolverInfo(std::vector<std::string>* servers, std::vector<std::string>* domains,
111 std::vector<std::string>* tlsServers, res_params* params,
112 std::vector<ResolverStats>* stats,
113 int* wait_for_pending_req_timeout_count) {
114 using android::net::IDnsResolver;
115 std::vector<int32_t> params32;
116 std::vector<int32_t> stats32;
117 std::vector<int32_t> wait_for_pending_req_timeout_count32{0};
118 auto rv = mDnsClient.resolvService()->getResolverInfo(
119 TEST_NETID, servers, domains, tlsServers, ¶ms32, &stats32,
120 &wait_for_pending_req_timeout_count32);
121
122 if (!rv.isOk() ||
123 params32.size() != static_cast<size_t>(IDnsResolver::RESOLVER_PARAMS_COUNT)) {
124 return false;
125 }
126 *params = res_params{
127 .sample_validity = static_cast<uint16_t>(
128 params32[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY]),
129 .success_threshold = static_cast<uint8_t>(
130 params32[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD]),
131 .min_samples =
132 static_cast<uint8_t>(params32[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES]),
133 .max_samples =
134 static_cast<uint8_t>(params32[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES]),
135 .base_timeout_msec = params32[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
136 .retry_count = params32[IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT],
137 };
138 *wait_for_pending_req_timeout_count = wait_for_pending_req_timeout_count32[0];
139 return ResolverStats::decodeAll(stats32, stats);
140 }
141
ToString(const hostent * he)142 static std::string ToString(const hostent* he) {
143 if (he == nullptr) return "<null>";
144 char buffer[INET6_ADDRSTRLEN];
145 if (!inet_ntop(he->h_addrtype, he->h_addr_list[0], buffer, sizeof(buffer))) {
146 return "<invalid>";
147 }
148 return buffer;
149 }
150
ToString(const addrinfo * ai)151 static std::string ToString(const addrinfo* ai) {
152 if (!ai)
153 return "<null>";
154 for (const auto* aip = ai ; aip != nullptr ; aip = aip->ai_next) {
155 char host[NI_MAXHOST];
156 int rv = getnameinfo(aip->ai_addr, aip->ai_addrlen, host, sizeof(host), nullptr, 0,
157 NI_NUMERICHOST);
158 if (rv != 0)
159 return gai_strerror(rv);
160 return host;
161 }
162 return "<invalid>";
163 }
164
ToString(const ScopedAddrinfo & ai)165 static std::string ToString(const ScopedAddrinfo& ai) { return ToString(ai.get()); }
166
ToStrings(const addrinfo * ai)167 static std::vector<std::string> ToStrings(const addrinfo* ai) {
168 std::vector<std::string> hosts;
169 if (!ai) {
170 hosts.push_back("<null>");
171 return hosts;
172 }
173 for (const auto* aip = ai; aip != nullptr; aip = aip->ai_next) {
174 char host[NI_MAXHOST];
175 int rv = getnameinfo(aip->ai_addr, aip->ai_addrlen, host, sizeof(host), nullptr, 0,
176 NI_NUMERICHOST);
177 if (rv != 0) {
178 hosts.clear();
179 hosts.push_back(gai_strerror(rv));
180 return hosts;
181 } else {
182 hosts.push_back(host);
183 }
184 }
185 if (hosts.empty()) hosts.push_back("<invalid>");
186 return hosts;
187 }
188
ToStrings(const ScopedAddrinfo & ai)189 static std::vector<std::string> ToStrings(const ScopedAddrinfo& ai) {
190 return ToStrings(ai.get());
191 }
192
GetNumQueries(const test::DNSResponder & dns,const char * name) const193 size_t GetNumQueries(const test::DNSResponder& dns, const char* name) const {
194 auto queries = dns.queries();
195 size_t found = 0;
196 for (const auto& p : queries) {
197 if (p.first == name) {
198 ++found;
199 }
200 }
201 return found;
202 }
203
GetNumQueriesForType(const test::DNSResponder & dns,ns_type type,const char * name) const204 size_t GetNumQueriesForType(const test::DNSResponder& dns, ns_type type,
205 const char* name) const {
206 auto queries = dns.queries();
207 size_t found = 0;
208 for (const auto& p : queries) {
209 if (p.second == type && p.first == name) {
210 ++found;
211 }
212 }
213 return found;
214 }
215
WaitForPrefix64Detected(int netId,int timeoutMs)216 bool WaitForPrefix64Detected(int netId, int timeoutMs) {
217 constexpr int intervalMs = 2;
218 const int limit = timeoutMs / intervalMs;
219 for (int count = 0; count <= limit; ++count) {
220 std::string prefix;
221 auto rv = mDnsClient.resolvService()->getPrefix64(netId, &prefix);
222 if (rv.isOk()) {
223 return true;
224 }
225 usleep(intervalMs * 1000);
226 }
227 return false;
228 }
229
RunGetAddrInfoStressTest_Binder(unsigned num_hosts,unsigned num_threads,unsigned num_queries)230 void RunGetAddrInfoStressTest_Binder(unsigned num_hosts, unsigned num_threads,
231 unsigned num_queries) {
232 std::vector<std::string> domains = { "example.com" };
233 std::vector<std::unique_ptr<test::DNSResponder>> dns;
234 std::vector<std::string> servers;
235 std::vector<DnsResponderClient::DnsResponderClient::Mapping> mappings;
236 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(num_hosts, domains, &mappings));
237 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(MAXNS, mappings, &dns, &servers));
238
239 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains, kDefaultParams));
240
241 auto t0 = std::chrono::steady_clock::now();
242 std::vector<std::thread> threads(num_threads);
243 for (std::thread& thread : threads) {
244 thread = std::thread([&mappings, num_queries]() {
245 for (unsigned i = 0 ; i < num_queries ; ++i) {
246 uint32_t ofs = arc4random_uniform(mappings.size());
247 auto& mapping = mappings[ofs];
248 addrinfo* result = nullptr;
249 int rv = getaddrinfo(mapping.host.c_str(), nullptr, nullptr, &result);
250 EXPECT_EQ(0, rv) << "error [" << rv << "] " << gai_strerror(rv);
251 if (rv == 0) {
252 std::string result_str = ToString(result);
253 EXPECT_TRUE(result_str == mapping.ip4 || result_str == mapping.ip6)
254 << "result='" << result_str << "', ip4='" << mapping.ip4
255 << "', ip6='" << mapping.ip6;
256 }
257 if (result) {
258 freeaddrinfo(result);
259 result = nullptr;
260 }
261 }
262 });
263 }
264
265 for (std::thread& thread : threads) {
266 thread.join();
267 }
268 auto t1 = std::chrono::steady_clock::now();
269 ALOGI("%u hosts, %u threads, %u queries, %Es", num_hosts, num_threads, num_queries,
270 std::chrono::duration<double>(t1 - t0).count());
271
272 std::vector<std::string> res_servers;
273 std::vector<std::string> res_domains;
274 std::vector<std::string> res_tls_servers;
275 res_params res_params;
276 std::vector<ResolverStats> res_stats;
277 int wait_for_pending_req_timeout_count;
278 ASSERT_TRUE(GetResolverInfo(&res_servers, &res_domains, &res_tls_servers, &res_params,
279 &res_stats, &wait_for_pending_req_timeout_count));
280 EXPECT_EQ(0, wait_for_pending_req_timeout_count);
281 }
282
StartDns(test::DNSResponder & dns,const std::vector<DnsRecord> & records)283 void StartDns(test::DNSResponder& dns, const std::vector<DnsRecord>& records) {
284 for (const auto& r : records) {
285 dns.addMapping(r.host_name, r.type, r.addr);
286 }
287
288 ASSERT_TRUE(dns.startServer());
289 dns.clearQueries();
290 }
291
292 DnsResponderClient mDnsClient;
293
294 static constexpr char kLocalHost[] = "localhost";
295 static constexpr char kLocalHostAddr[] = "127.0.0.1";
296 static constexpr char kIp6LocalHost[] = "ip6-localhost";
297 static constexpr char kIp6LocalHostAddr[] = "::1";
298 static constexpr char kHelloExampleCom[] = "hello.example.com.";
299 };
300
TEST_F(ResolverTest,GetHostByName)301 TEST_F(ResolverTest, GetHostByName) {
302 constexpr char nonexistent_host_name[] = "nonexistent.example.com.";
303
304 test::DNSResponder dns;
305 StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.3"}});
306 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
307
308 const hostent* result;
309 result = gethostbyname("nonexistent");
310 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, nonexistent_host_name));
311 ASSERT_TRUE(result == nullptr);
312 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
313
314 dns.clearQueries();
315 result = gethostbyname("hello");
316 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, kHelloExampleCom));
317 ASSERT_FALSE(result == nullptr);
318 ASSERT_EQ(4, result->h_length);
319 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
320 EXPECT_EQ("1.2.3.3", ToString(result));
321 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
322 }
323
TEST_F(ResolverTest,GetHostByName_cnames)324 TEST_F(ResolverTest, GetHostByName_cnames) {
325 constexpr char host_name[] = "host.example.com.";
326 size_t cnamecount = 0;
327 test::DNSResponder dns;
328
329 const std::vector<DnsRecord> records = {
330 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
331 {"a.example.com.", ns_type::ns_t_cname, "b.example.com."},
332 {"b.example.com.", ns_type::ns_t_cname, "c.example.com."},
333 {"c.example.com.", ns_type::ns_t_cname, "d.example.com."},
334 {"d.example.com.", ns_type::ns_t_cname, "e.example.com."},
335 {"e.example.com.", ns_type::ns_t_cname, host_name},
336 {host_name, ns_type::ns_t_a, "1.2.3.3"},
337 {host_name, ns_type::ns_t_aaaa, "2001:db8::42"},
338 };
339 StartDns(dns, records);
340 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
341
342 // using gethostbyname2() to resolve ipv4 hello.example.com. to 1.2.3.3
343 // Ensure the v4 address and cnames are correct
344 const hostent* result;
345 result = gethostbyname2("hello", AF_INET);
346 ASSERT_FALSE(result == nullptr);
347
348 for (int i = 0; result != nullptr && result->h_aliases[i] != nullptr; i++) {
349 std::string domain_name = records[i].host_name.substr(0, records[i].host_name.size() - 1);
350 EXPECT_EQ(result->h_aliases[i], domain_name);
351 cnamecount++;
352 }
353 // The size of "Non-cname type" record in DNS records is 2
354 ASSERT_EQ(cnamecount, records.size() - 2);
355 ASSERT_EQ(4, result->h_length);
356 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
357 EXPECT_EQ("1.2.3.3", ToString(result));
358 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
359 EXPECT_EQ(1U, dns.queries().size()) << dns.dumpQueries();
360
361 // using gethostbyname2() to resolve ipv6 hello.example.com. to 2001:db8::42
362 // Ensure the v6 address and cnames are correct
363 cnamecount = 0;
364 dns.clearQueries();
365 result = gethostbyname2("hello", AF_INET6);
366 for (unsigned i = 0; result != nullptr && result->h_aliases[i] != nullptr; i++) {
367 std::string domain_name = records[i].host_name.substr(0, records[i].host_name.size() - 1);
368 EXPECT_EQ(result->h_aliases[i], domain_name);
369 cnamecount++;
370 }
371 // The size of "Non-cname type" DNS record in records is 2
372 ASSERT_EQ(cnamecount, records.size() - 2);
373 ASSERT_FALSE(result == nullptr);
374 ASSERT_EQ(16, result->h_length);
375 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
376 EXPECT_EQ("2001:db8::42", ToString(result));
377 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
378 }
379
TEST_F(ResolverTest,GetHostByName_cnamesInfiniteLoop)380 TEST_F(ResolverTest, GetHostByName_cnamesInfiniteLoop) {
381 test::DNSResponder dns;
382 const std::vector<DnsRecord> records = {
383 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
384 {"a.example.com.", ns_type::ns_t_cname, kHelloExampleCom},
385 };
386 StartDns(dns, records);
387 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
388
389 const hostent* result;
390 result = gethostbyname2("hello", AF_INET);
391 ASSERT_TRUE(result == nullptr);
392
393 dns.clearQueries();
394 result = gethostbyname2("hello", AF_INET6);
395 ASSERT_TRUE(result == nullptr);
396 }
397
TEST_F(ResolverTest,GetHostByName_localhost)398 TEST_F(ResolverTest, GetHostByName_localhost) {
399 constexpr char name_camelcase[] = "LocalHost";
400 constexpr char name_ip6_dot[] = "ip6-localhost.";
401 constexpr char name_ip6_fqdn[] = "ip6-localhost.example.com.";
402
403 // Add a dummy nameserver which shouldn't receive any queries
404 test::DNSResponder dns;
405 StartDns(dns, {});
406 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
407
408 // Expect no DNS queries; localhost is resolved via /etc/hosts
409 const hostent* result = gethostbyname(kLocalHost);
410 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
411 ASSERT_FALSE(result == nullptr);
412 ASSERT_EQ(4, result->h_length);
413 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
414 EXPECT_EQ(kLocalHostAddr, ToString(result));
415 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
416
417 // Ensure the hosts file resolver ignores case of hostnames
418 result = gethostbyname(name_camelcase);
419 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
420 ASSERT_FALSE(result == nullptr);
421 ASSERT_EQ(4, result->h_length);
422 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
423 EXPECT_EQ(kLocalHostAddr, ToString(result));
424 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
425
426 // The hosts file also contains ip6-localhost, but gethostbyname() won't
427 // return it unless the RES_USE_INET6 option is set. This would be easy to
428 // change, but there's no point in changing the legacy behavior; new code
429 // should be calling getaddrinfo() anyway.
430 // So we check the legacy behavior, which results in amusing A-record
431 // lookups for ip6-localhost, with and without search domains appended.
432 dns.clearQueries();
433 result = gethostbyname(kIp6LocalHost);
434 EXPECT_EQ(2U, dns.queries().size()) << dns.dumpQueries();
435 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, name_ip6_dot)) << dns.dumpQueries();
436 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, name_ip6_fqdn)) << dns.dumpQueries();
437 ASSERT_TRUE(result == nullptr);
438
439 // Finally, use gethostbyname2() to resolve ip6-localhost to ::1 from
440 // the hosts file.
441 dns.clearQueries();
442 result = gethostbyname2(kIp6LocalHost, AF_INET6);
443 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
444 ASSERT_FALSE(result == nullptr);
445 ASSERT_EQ(16, result->h_length);
446 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
447 EXPECT_EQ(kIp6LocalHostAddr, ToString(result));
448 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
449 }
450
TEST_F(ResolverTest,GetHostByName_numeric)451 TEST_F(ResolverTest, GetHostByName_numeric) {
452 // Add a dummy nameserver which shouldn't receive any queries
453 test::DNSResponder dns;
454 StartDns(dns, {});
455 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
456
457 // Numeric v4 address: expect no DNS queries
458 constexpr char numeric_v4[] = "192.168.0.1";
459 const hostent* result = gethostbyname(numeric_v4);
460 EXPECT_EQ(0U, dns.queries().size());
461 ASSERT_FALSE(result == nullptr);
462 ASSERT_EQ(4, result->h_length); // v4
463 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
464 EXPECT_EQ(numeric_v4, ToString(result));
465 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
466
467 // gethostbyname() recognizes a v6 address, and fails with no DNS queries
468 constexpr char numeric_v6[] = "2001:db8::42";
469 dns.clearQueries();
470 result = gethostbyname(numeric_v6);
471 EXPECT_EQ(0U, dns.queries().size());
472 EXPECT_TRUE(result == nullptr);
473
474 // Numeric v6 address with gethostbyname2(): succeeds with no DNS queries
475 dns.clearQueries();
476 result = gethostbyname2(numeric_v6, AF_INET6);
477 EXPECT_EQ(0U, dns.queries().size());
478 ASSERT_FALSE(result == nullptr);
479 ASSERT_EQ(16, result->h_length); // v6
480 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
481 EXPECT_EQ(numeric_v6, ToString(result));
482 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
483
484 // Numeric v6 address with scope work with getaddrinfo(),
485 // but gethostbyname2() does not understand them; it issues two dns
486 // queries, then fails. This hardly ever happens, there's no point
487 // in fixing this. This test simply verifies the current (bogus)
488 // behavior to avoid further regressions (like crashes, or leaks).
489 constexpr char numeric_v6_scope[] = "fe80::1%lo";
490 dns.clearQueries();
491 result = gethostbyname2(numeric_v6_scope, AF_INET6);
492 EXPECT_EQ(2U, dns.queries().size()); // OUCH!
493 ASSERT_TRUE(result == nullptr);
494 }
495
TEST_F(ResolverTest,BinderSerialization)496 TEST_F(ResolverTest, BinderSerialization) {
497 using android::net::IDnsResolver;
498 std::vector<int> params_offsets = {
499 IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY,
500 IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD,
501 IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES,
502 IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES,
503 IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC,
504 IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT,
505 };
506 const int size = static_cast<int>(params_offsets.size());
507 EXPECT_EQ(size, IDnsResolver::RESOLVER_PARAMS_COUNT);
508 std::sort(params_offsets.begin(), params_offsets.end());
509 for (int i = 0; i < size; ++i) {
510 EXPECT_EQ(params_offsets[i], i);
511 }
512 }
513
TEST_F(ResolverTest,GetHostByName_Binder)514 TEST_F(ResolverTest, GetHostByName_Binder) {
515 using android::net::IDnsResolver;
516
517 std::vector<std::string> domains = { "example.com" };
518 std::vector<std::unique_ptr<test::DNSResponder>> dns;
519 std::vector<std::string> servers;
520 std::vector<DnsResponderClient::Mapping> mappings;
521 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(1, domains, &mappings));
522 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(4, mappings, &dns, &servers));
523 ASSERT_EQ(1U, mappings.size());
524 const DnsResponderClient::Mapping& mapping = mappings[0];
525
526 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains, kDefaultParams));
527
528 const hostent* result = gethostbyname(mapping.host.c_str());
529 const size_t total_queries =
530 std::accumulate(dns.begin(), dns.end(), 0, [this, &mapping](size_t total, auto& d) {
531 return total + GetNumQueriesForType(*d, ns_type::ns_t_a, mapping.entry.c_str());
532 });
533
534 EXPECT_LE(1U, total_queries);
535 ASSERT_FALSE(result == nullptr);
536 ASSERT_EQ(4, result->h_length);
537 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
538 EXPECT_EQ(mapping.ip4, ToString(result));
539 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
540
541 std::vector<std::string> res_servers;
542 std::vector<std::string> res_domains;
543 std::vector<std::string> res_tls_servers;
544 res_params res_params;
545 std::vector<ResolverStats> res_stats;
546 int wait_for_pending_req_timeout_count;
547 ASSERT_TRUE(GetResolverInfo(&res_servers, &res_domains, &res_tls_servers, &res_params,
548 &res_stats, &wait_for_pending_req_timeout_count));
549 EXPECT_EQ(servers.size(), res_servers.size());
550 EXPECT_EQ(domains.size(), res_domains.size());
551 EXPECT_EQ(0U, res_tls_servers.size());
552 ASSERT_EQ(static_cast<size_t>(IDnsResolver::RESOLVER_PARAMS_COUNT), kDefaultParams.size());
553 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY],
554 res_params.sample_validity);
555 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD],
556 res_params.success_threshold);
557 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES], res_params.min_samples);
558 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES], res_params.max_samples);
559 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
560 res_params.base_timeout_msec);
561 EXPECT_EQ(servers.size(), res_stats.size());
562
563 EXPECT_THAT(res_servers, testing::UnorderedElementsAreArray(servers));
564 EXPECT_THAT(res_domains, testing::UnorderedElementsAreArray(domains));
565 }
566
TEST_F(ResolverTest,GetAddrInfo)567 TEST_F(ResolverTest, GetAddrInfo) {
568 constexpr char listen_addr[] = "127.0.0.4";
569 constexpr char listen_addr2[] = "127.0.0.5";
570 constexpr char host_name[] = "howdy.example.com.";
571
572 const std::vector<DnsRecord> records = {
573 {host_name, ns_type::ns_t_a, "1.2.3.4"},
574 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
575 };
576 test::DNSResponder dns(listen_addr);
577 test::DNSResponder dns2(listen_addr2);
578 StartDns(dns, records);
579 StartDns(dns2, records);
580
581 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr}));
582 dns.clearQueries();
583 dns2.clearQueries();
584
585 ScopedAddrinfo result = safe_getaddrinfo("howdy", nullptr, nullptr);
586 EXPECT_TRUE(result != nullptr);
587 size_t found = GetNumQueries(dns, host_name);
588 EXPECT_LE(1U, found);
589 // Could be A or AAAA
590 std::string result_str = ToString(result);
591 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
592 << ", result_str='" << result_str << "'";
593
594 // Verify that the name is cached.
595 size_t old_found = found;
596 result = safe_getaddrinfo("howdy", nullptr, nullptr);
597 EXPECT_TRUE(result != nullptr);
598 found = GetNumQueries(dns, host_name);
599 EXPECT_LE(1U, found);
600 EXPECT_EQ(old_found, found);
601 result_str = ToString(result);
602 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
603 << result_str;
604
605 // Change the DNS resolver, ensure that queries are still cached.
606 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr2}));
607 dns.clearQueries();
608 dns2.clearQueries();
609
610 result = safe_getaddrinfo("howdy", nullptr, nullptr);
611 EXPECT_TRUE(result != nullptr);
612 found = GetNumQueries(dns, host_name);
613 size_t found2 = GetNumQueries(dns2, host_name);
614 EXPECT_EQ(0U, found);
615 EXPECT_LE(0U, found2);
616
617 // Could be A or AAAA
618 result_str = ToString(result);
619 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
620 << ", result_str='" << result_str << "'";
621 }
622
TEST_F(ResolverTest,GetAddrInfoV4)623 TEST_F(ResolverTest, GetAddrInfoV4) {
624 test::DNSResponder dns;
625 StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.5"}});
626 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
627
628 const addrinfo hints = {.ai_family = AF_INET};
629 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
630 EXPECT_TRUE(result != nullptr);
631 EXPECT_EQ(1U, GetNumQueries(dns, kHelloExampleCom));
632 EXPECT_EQ("1.2.3.5", ToString(result));
633 }
634
TEST_F(ResolverTest,GetAddrInfo_localhost)635 TEST_F(ResolverTest, GetAddrInfo_localhost) {
636 // Add a dummy nameserver which shouldn't receive any queries
637 test::DNSResponder dns;
638 StartDns(dns, {});
639 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
640
641 ScopedAddrinfo result = safe_getaddrinfo(kLocalHost, nullptr, nullptr);
642 EXPECT_TRUE(result != nullptr);
643 // Expect no DNS queries; localhost is resolved via /etc/hosts
644 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
645 EXPECT_EQ(kLocalHostAddr, ToString(result));
646
647 result = safe_getaddrinfo(kIp6LocalHost, nullptr, nullptr);
648 EXPECT_TRUE(result != nullptr);
649 // Expect no DNS queries; ip6-localhost is resolved via /etc/hosts
650 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
651 EXPECT_EQ(kIp6LocalHostAddr, ToString(result));
652 }
653
654 // Verify if the resolver correctly handle multiple queries simultaneously
655 // step 1: set dns server#1 into deferred responding mode.
656 // step 2: thread#1 query "hello.example.com." --> resolver send query to server#1.
657 // step 3: thread#2 query "hello.example.com." --> resolver hold the request and wait for
658 // response of previous pending query sent by thread#1.
659 // step 4: thread#3 query "konbanha.example.com." --> resolver send query to server#3. Server
660 // respond to resolver immediately.
661 // step 5: check if server#1 get 1 query by thread#1, server#2 get 0 query, server#3 get 1 query.
662 // step 6: resume dns server#1 to respond dns query in step#2.
663 // step 7: thread#1 and #2 should get returned from DNS query after step#6. Also, check the
664 // number of queries in server#2 is 0 to ensure thread#2 does not wake up unexpectedly
665 // before signaled by thread#1.
TEST_F(ResolverTest,GetAddrInfoV4_deferred_resp)666 TEST_F(ResolverTest, GetAddrInfoV4_deferred_resp) {
667 const char* listen_addr1 = "127.0.0.9";
668 const char* listen_addr2 = "127.0.0.10";
669 const char* listen_addr3 = "127.0.0.11";
670 const char* listen_srv = "53";
671 const char* host_name_deferred = "hello.example.com.";
672 const char* host_name_normal = "konbanha.example.com.";
673 test::DNSResponder dns1(listen_addr1, listen_srv, 250, ns_rcode::ns_r_servfail);
674 test::DNSResponder dns2(listen_addr2, listen_srv, 250, ns_rcode::ns_r_servfail);
675 test::DNSResponder dns3(listen_addr3, listen_srv, 250, ns_rcode::ns_r_servfail);
676 dns1.addMapping(host_name_deferred, ns_type::ns_t_a, "1.2.3.4");
677 dns2.addMapping(host_name_deferred, ns_type::ns_t_a, "1.2.3.4");
678 dns3.addMapping(host_name_normal, ns_type::ns_t_a, "1.2.3.5");
679 ASSERT_TRUE(dns1.startServer());
680 ASSERT_TRUE(dns2.startServer());
681 ASSERT_TRUE(dns3.startServer());
682 const std::vector<std::string> servers_for_t1 = {listen_addr1};
683 const std::vector<std::string> servers_for_t2 = {listen_addr2};
684 const std::vector<std::string> servers_for_t3 = {listen_addr3};
685 addrinfo hints = {.ai_family = AF_INET};
686 const std::vector<int> params = {300, 25, 8, 8, 5000};
687 bool t3_task_done = false;
688
689 dns1.setDeferredResp(true);
690 std::thread t1([&, this]() {
691 ASSERT_TRUE(
692 mDnsClient.SetResolversForNetwork(servers_for_t1, kDefaultSearchDomains, params));
693 ScopedAddrinfo result = safe_getaddrinfo(host_name_deferred, nullptr, &hints);
694 // t3's dns query should got returned first
695 EXPECT_TRUE(t3_task_done);
696 EXPECT_EQ(1U, GetNumQueries(dns1, host_name_deferred));
697 EXPECT_TRUE(result != nullptr);
698 EXPECT_EQ("1.2.3.4", ToString(result));
699 });
700
701 // ensuring t1 and t2 handler functions are processed in order
702 usleep(100 * 1000);
703 std::thread t2([&, this]() {
704 ASSERT_TRUE(
705 mDnsClient.SetResolversForNetwork(servers_for_t2, kDefaultSearchDomains, params));
706 ScopedAddrinfo result = safe_getaddrinfo(host_name_deferred, nullptr, &hints);
707 EXPECT_TRUE(t3_task_done);
708 EXPECT_EQ(0U, GetNumQueries(dns2, host_name_deferred));
709 EXPECT_TRUE(result != nullptr);
710 EXPECT_EQ("1.2.3.4", ToString(result));
711
712 std::vector<std::string> res_servers;
713 std::vector<std::string> res_domains;
714 std::vector<std::string> res_tls_servers;
715 res_params res_params;
716 std::vector<ResolverStats> res_stats;
717 int wait_for_pending_req_timeout_count;
718 ASSERT_TRUE(GetResolverInfo(&res_servers, &res_domains, &res_tls_servers, &res_params,
719 &res_stats, &wait_for_pending_req_timeout_count));
720 EXPECT_EQ(0, wait_for_pending_req_timeout_count);
721 });
722
723 // ensuring t2 and t3 handler functions are processed in order
724 usleep(100 * 1000);
725 std::thread t3([&, this]() {
726 ASSERT_TRUE(
727 mDnsClient.SetResolversForNetwork(servers_for_t3, kDefaultSearchDomains, params));
728 ScopedAddrinfo result = safe_getaddrinfo(host_name_normal, nullptr, &hints);
729 EXPECT_EQ(1U, GetNumQueries(dns1, host_name_deferred));
730 EXPECT_EQ(0U, GetNumQueries(dns2, host_name_deferred));
731 EXPECT_EQ(1U, GetNumQueries(dns3, host_name_normal));
732 EXPECT_TRUE(result != nullptr);
733 EXPECT_EQ("1.2.3.5", ToString(result));
734
735 t3_task_done = true;
736 dns1.setDeferredResp(false);
737 });
738 t3.join();
739 t1.join();
740 t2.join();
741 }
742
TEST_F(ResolverTest,GetAddrInfo_cnames)743 TEST_F(ResolverTest, GetAddrInfo_cnames) {
744 constexpr char host_name[] = "host.example.com.";
745 test::DNSResponder dns;
746 const std::vector<DnsRecord> records = {
747 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
748 {"a.example.com.", ns_type::ns_t_cname, "b.example.com."},
749 {"b.example.com.", ns_type::ns_t_cname, "c.example.com."},
750 {"c.example.com.", ns_type::ns_t_cname, "d.example.com."},
751 {"d.example.com.", ns_type::ns_t_cname, "e.example.com."},
752 {"e.example.com.", ns_type::ns_t_cname, host_name},
753 {host_name, ns_type::ns_t_a, "1.2.3.3"},
754 {host_name, ns_type::ns_t_aaaa, "2001:db8::42"},
755 };
756 StartDns(dns, records);
757 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
758
759 addrinfo hints = {.ai_family = AF_INET};
760 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
761 EXPECT_TRUE(result != nullptr);
762 EXPECT_EQ("1.2.3.3", ToString(result));
763
764 dns.clearQueries();
765 hints = {.ai_family = AF_INET6};
766 result = safe_getaddrinfo("hello", nullptr, &hints);
767 EXPECT_TRUE(result != nullptr);
768 EXPECT_EQ("2001:db8::42", ToString(result));
769 }
770
TEST_F(ResolverTest,GetAddrInfo_cnamesNoIpAddress)771 TEST_F(ResolverTest, GetAddrInfo_cnamesNoIpAddress) {
772 test::DNSResponder dns;
773 const std::vector<DnsRecord> records = {
774 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
775 };
776 StartDns(dns, records);
777 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
778
779 addrinfo hints = {.ai_family = AF_INET};
780 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
781 EXPECT_TRUE(result == nullptr);
782
783 dns.clearQueries();
784 hints = {.ai_family = AF_INET6};
785 result = safe_getaddrinfo("hello", nullptr, &hints);
786 EXPECT_TRUE(result == nullptr);
787 }
788
TEST_F(ResolverTest,GetAddrInfo_cnamesIllegalRdata)789 TEST_F(ResolverTest, GetAddrInfo_cnamesIllegalRdata) {
790 test::DNSResponder dns;
791 const std::vector<DnsRecord> records = {
792 {kHelloExampleCom, ns_type::ns_t_cname, ".!#?"},
793 };
794 StartDns(dns, records);
795 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
796
797 addrinfo hints = {.ai_family = AF_INET};
798 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
799 EXPECT_TRUE(result == nullptr);
800
801 dns.clearQueries();
802 hints = {.ai_family = AF_INET6};
803 result = safe_getaddrinfo("hello", nullptr, &hints);
804 EXPECT_TRUE(result == nullptr);
805 }
806
TEST_F(ResolverTest,MultidomainResolution)807 TEST_F(ResolverTest, MultidomainResolution) {
808 constexpr char host_name[] = "nihao.example2.com.";
809 std::vector<std::string> searchDomains = { "example1.com", "example2.com", "example3.com" };
810
811 test::DNSResponder dns("127.0.0.6");
812 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.3"}});
813 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({"127.0.0.6"}, searchDomains));
814
815 const hostent* result = gethostbyname("nihao");
816
817 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
818 ASSERT_FALSE(result == nullptr);
819 ASSERT_EQ(4, result->h_length);
820 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
821 EXPECT_EQ("1.2.3.3", ToString(result));
822 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
823 }
824
TEST_F(ResolverTest,GetAddrInfoV6_numeric)825 TEST_F(ResolverTest, GetAddrInfoV6_numeric) {
826 constexpr char host_name[] = "ohayou.example.com.";
827 constexpr char numeric_addr[] = "fe80::1%lo";
828
829 test::DNSResponder dns;
830 dns.setResponseProbability(0.0);
831 StartDns(dns, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
832 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
833
834 addrinfo hints = {.ai_family = AF_INET6};
835 ScopedAddrinfo result = safe_getaddrinfo(numeric_addr, nullptr, &hints);
836 EXPECT_TRUE(result != nullptr);
837 EXPECT_EQ(numeric_addr, ToString(result));
838 EXPECT_TRUE(dns.queries().empty()); // Ensure no DNS queries were sent out
839
840 // Now try a non-numeric hostname query with the AI_NUMERICHOST flag set.
841 // We should fail without sending out a DNS query.
842 hints.ai_flags |= AI_NUMERICHOST;
843 result = safe_getaddrinfo(host_name, nullptr, &hints);
844 EXPECT_TRUE(result == nullptr);
845 EXPECT_TRUE(dns.queries().empty()); // Ensure no DNS queries were sent out
846 }
847
TEST_F(ResolverTest,GetAddrInfoV6_failing)848 TEST_F(ResolverTest, GetAddrInfoV6_failing) {
849 constexpr char listen_addr0[] = "127.0.0.7";
850 constexpr char listen_addr1[] = "127.0.0.8";
851 const char* host_name = "ohayou.example.com.";
852
853 test::DNSResponder dns0(listen_addr0);
854 test::DNSResponder dns1(listen_addr1);
855 dns0.setResponseProbability(0.0);
856 StartDns(dns0, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
857 StartDns(dns1, {{host_name, ns_type::ns_t_aaaa, "2001:db8::6"}});
858
859 std::vector<std::string> servers = { listen_addr0, listen_addr1 };
860 // <sample validity in s> <success threshold in percent> <min samples> <max samples>
861 int sample_count = 8;
862 const std::vector<int> params = { 300, 25, sample_count, sample_count };
863 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, kDefaultSearchDomains, params));
864
865 // Repeatedly perform resolutions for non-existing domains until MAXNSSAMPLES resolutions have
866 // reached the dns0, which is set to fail. No more requests should then arrive at that server
867 // for the next sample_lifetime seconds.
868 // TODO: This approach is implementation-dependent, change once metrics reporting is available.
869 const addrinfo hints = {.ai_family = AF_INET6};
870 for (int i = 0; i < sample_count; ++i) {
871 std::string domain = StringPrintf("nonexistent%d", i);
872 ScopedAddrinfo result = safe_getaddrinfo(domain.c_str(), nullptr, &hints);
873 }
874 // Due to 100% errors for all possible samples, the server should be ignored from now on and
875 // only the second one used for all following queries, until NSSAMPLE_VALIDITY is reached.
876 dns0.clearQueries();
877 dns1.clearQueries();
878 ScopedAddrinfo result = safe_getaddrinfo("ohayou", nullptr, &hints);
879 EXPECT_TRUE(result != nullptr);
880 EXPECT_EQ(0U, GetNumQueries(dns0, host_name));
881 EXPECT_EQ(1U, GetNumQueries(dns1, host_name));
882 }
883
TEST_F(ResolverTest,GetAddrInfoV6_nonresponsive)884 TEST_F(ResolverTest, GetAddrInfoV6_nonresponsive) {
885 constexpr char listen_addr0[] = "127.0.0.7";
886 constexpr char listen_addr1[] = "127.0.0.8";
887 constexpr char listen_srv[] = "53";
888 constexpr char host_name1[] = "ohayou.example.com.";
889 constexpr char host_name2[] = "ciao.example.com.";
890 const std::vector<DnsRecord> records0 = {
891 {host_name1, ns_type::ns_t_aaaa, "2001:db8::5"},
892 {host_name2, ns_type::ns_t_aaaa, "2001:db8::5"},
893 };
894 const std::vector<DnsRecord> records1 = {
895 {host_name1, ns_type::ns_t_aaaa, "2001:db8::6"},
896 {host_name2, ns_type::ns_t_aaaa, "2001:db8::6"},
897 };
898
899 // dns0 does not respond with 100% probability, while
900 // dns1 responds normally, at least initially.
901 test::DNSResponder dns0(listen_addr0, listen_srv, 250, static_cast<ns_rcode>(-1));
902 test::DNSResponder dns1(listen_addr1, listen_srv, 250, static_cast<ns_rcode>(-1));
903 dns0.setResponseProbability(0.0);
904 StartDns(dns0, records0);
905 StartDns(dns1, records1);
906 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr0, listen_addr1}));
907
908 const addrinfo hints = {.ai_family = AF_INET6};
909
910 // dns0 will ignore the request, and we'll fallback to dns1 after the first
911 // retry.
912 ScopedAddrinfo result = safe_getaddrinfo(host_name1, nullptr, &hints);
913 EXPECT_TRUE(result != nullptr);
914 EXPECT_EQ(1U, GetNumQueries(dns0, host_name1));
915 EXPECT_EQ(1U, GetNumQueries(dns1, host_name1));
916
917 // Now make dns1 also ignore 100% requests... The resolve should alternate
918 // retries between the nameservers and fail after 4 attempts.
919 dns1.setResponseProbability(0.0);
920 addrinfo* result2 = nullptr;
921 EXPECT_EQ(EAI_NODATA, getaddrinfo(host_name2, nullptr, &hints, &result2));
922 EXPECT_EQ(nullptr, result2);
923 EXPECT_EQ(4U, GetNumQueries(dns0, host_name2));
924 EXPECT_EQ(4U, GetNumQueries(dns1, host_name2));
925 }
926
TEST_F(ResolverTest,GetAddrInfoV6_concurrent)927 TEST_F(ResolverTest, GetAddrInfoV6_concurrent) {
928 constexpr char listen_addr0[] = "127.0.0.9";
929 constexpr char listen_addr1[] = "127.0.0.10";
930 constexpr char listen_addr2[] = "127.0.0.11";
931 constexpr char host_name[] = "konbanha.example.com.";
932
933 test::DNSResponder dns0(listen_addr0);
934 test::DNSResponder dns1(listen_addr1);
935 test::DNSResponder dns2(listen_addr2);
936 StartDns(dns0, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
937 StartDns(dns1, {{host_name, ns_type::ns_t_aaaa, "2001:db8::6"}});
938 StartDns(dns2, {{host_name, ns_type::ns_t_aaaa, "2001:db8::7"}});
939
940 const std::vector<std::string> servers = { listen_addr0, listen_addr1, listen_addr2 };
941 std::vector<std::thread> threads(10);
942 for (std::thread& thread : threads) {
943 thread = std::thread([this, &servers]() {
944 unsigned delay = arc4random_uniform(1*1000*1000); // <= 1s
945 usleep(delay);
946 std::vector<std::string> serverSubset;
947 for (const auto& server : servers) {
948 if (arc4random_uniform(2)) {
949 serverSubset.push_back(server);
950 }
951 }
952 if (serverSubset.empty()) serverSubset = servers;
953 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(serverSubset));
954 const addrinfo hints = {.ai_family = AF_INET6};
955 addrinfo* result = nullptr;
956 int rv = getaddrinfo("konbanha", nullptr, &hints, &result);
957 EXPECT_EQ(0, rv) << "error [" << rv << "] " << gai_strerror(rv);
958 if (result) {
959 freeaddrinfo(result);
960 result = nullptr;
961 }
962 });
963 }
964 for (std::thread& thread : threads) {
965 thread.join();
966 }
967
968 std::vector<std::string> res_servers;
969 std::vector<std::string> res_domains;
970 std::vector<std::string> res_tls_servers;
971 res_params res_params;
972 std::vector<ResolverStats> res_stats;
973 int wait_for_pending_req_timeout_count;
974 ASSERT_TRUE(GetResolverInfo(&res_servers, &res_domains, &res_tls_servers, &res_params,
975 &res_stats, &wait_for_pending_req_timeout_count));
976 EXPECT_EQ(0, wait_for_pending_req_timeout_count);
977 }
978
TEST_F(ResolverTest,GetAddrInfoStressTest_Binder_100)979 TEST_F(ResolverTest, GetAddrInfoStressTest_Binder_100) {
980 const unsigned num_hosts = 100;
981 const unsigned num_threads = 100;
982 const unsigned num_queries = 100;
983 ASSERT_NO_FATAL_FAILURE(RunGetAddrInfoStressTest_Binder(num_hosts, num_threads, num_queries));
984 }
985
TEST_F(ResolverTest,GetAddrInfoStressTest_Binder_100000)986 TEST_F(ResolverTest, GetAddrInfoStressTest_Binder_100000) {
987 const unsigned num_hosts = 100000;
988 const unsigned num_threads = 100;
989 const unsigned num_queries = 100;
990 ASSERT_NO_FATAL_FAILURE(RunGetAddrInfoStressTest_Binder(num_hosts, num_threads, num_queries));
991 }
992
TEST_F(ResolverTest,EmptySetup)993 TEST_F(ResolverTest, EmptySetup) {
994 using android::net::IDnsResolver;
995 std::vector<std::string> servers;
996 std::vector<std::string> domains;
997 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
998 std::vector<std::string> res_servers;
999 std::vector<std::string> res_domains;
1000 std::vector<std::string> res_tls_servers;
1001 res_params res_params;
1002 std::vector<ResolverStats> res_stats;
1003 int wait_for_pending_req_timeout_count;
1004 ASSERT_TRUE(GetResolverInfo(&res_servers, &res_domains, &res_tls_servers, &res_params,
1005 &res_stats, &wait_for_pending_req_timeout_count));
1006 EXPECT_EQ(0U, res_servers.size());
1007 EXPECT_EQ(0U, res_domains.size());
1008 EXPECT_EQ(0U, res_tls_servers.size());
1009 ASSERT_EQ(static_cast<size_t>(IDnsResolver::RESOLVER_PARAMS_COUNT), kDefaultParams.size());
1010 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY],
1011 res_params.sample_validity);
1012 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD],
1013 res_params.success_threshold);
1014 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES], res_params.min_samples);
1015 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES], res_params.max_samples);
1016 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
1017 res_params.base_timeout_msec);
1018 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT], res_params.retry_count);
1019 }
1020
TEST_F(ResolverTest,SearchPathChange)1021 TEST_F(ResolverTest, SearchPathChange) {
1022 constexpr char listen_addr[] = "127.0.0.13";
1023 constexpr char host_name1[] = "test13.domain1.org.";
1024 constexpr char host_name2[] = "test13.domain2.org.";
1025 std::vector<std::string> servers = { listen_addr };
1026 std::vector<std::string> domains = { "domain1.org" };
1027
1028 const std::vector<DnsRecord> records = {
1029 {host_name1, ns_type::ns_t_aaaa, "2001:db8::13"},
1030 {host_name2, ns_type::ns_t_aaaa, "2001:db8::1:13"},
1031 };
1032 test::DNSResponder dns(listen_addr);
1033 StartDns(dns, records);
1034 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
1035
1036 const addrinfo hints = {.ai_family = AF_INET6};
1037 ScopedAddrinfo result = safe_getaddrinfo("test13", nullptr, &hints);
1038 EXPECT_TRUE(result != nullptr);
1039 EXPECT_EQ(1U, dns.queries().size());
1040 EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
1041 EXPECT_EQ("2001:db8::13", ToString(result));
1042
1043 // Test that changing the domain search path on its own works.
1044 domains = { "domain2.org" };
1045 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
1046 dns.clearQueries();
1047
1048 result = safe_getaddrinfo("test13", nullptr, &hints);
1049 EXPECT_TRUE(result != nullptr);
1050 EXPECT_EQ(1U, dns.queries().size());
1051 EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
1052 EXPECT_EQ("2001:db8::1:13", ToString(result));
1053 }
1054
base64Encode(const std::vector<uint8_t> & input)1055 static std::string base64Encode(const std::vector<uint8_t>& input) {
1056 size_t out_len;
1057 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
1058 // out_len includes the trailing NULL.
1059 uint8_t output_bytes[out_len];
1060 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
1061 return std::string(reinterpret_cast<char*>(output_bytes));
1062 }
1063
1064 // If we move this function to dns_responder_client, it will complicate the dependency need of
1065 // dns_tls_frontend.h.
setupTlsServers(const std::vector<std::string> & servers,std::vector<std::unique_ptr<test::DnsTlsFrontend>> * tls,std::vector<std::string> * fingerprints)1066 static void setupTlsServers(const std::vector<std::string>& servers,
1067 std::vector<std::unique_ptr<test::DnsTlsFrontend>>* tls,
1068 std::vector<std::string>* fingerprints) {
1069 constexpr char listen_udp[] = "53";
1070 constexpr char listen_tls[] = "853";
1071
1072 for (const auto& server : servers) {
1073 auto t = std::make_unique<test::DnsTlsFrontend>(server, listen_tls, server, listen_udp);
1074 t = std::make_unique<test::DnsTlsFrontend>(server, listen_tls, server, listen_udp);
1075 t->startServer();
1076 fingerprints->push_back(base64Encode(t->fingerprint()));
1077 tls->push_back(std::move(t));
1078 }
1079 }
1080
TEST_F(ResolverTest,MaxServerPrune_Binder)1081 TEST_F(ResolverTest, MaxServerPrune_Binder) {
1082 std::vector<std::string> domains;
1083 std::vector<std::unique_ptr<test::DNSResponder>> dns;
1084 std::vector<std::unique_ptr<test::DnsTlsFrontend>> tls;
1085 std::vector<std::string> servers;
1086 std::vector<std::string> fingerprints;
1087 std::vector<DnsResponderClient::Mapping> mappings;
1088
1089 for (unsigned i = 0; i < MAXDNSRCH + 1; i++) {
1090 domains.push_back(StringPrintf("example%u.com", i));
1091 }
1092 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(1, domains, &mappings));
1093 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(MAXNS + 1, mappings, &dns, &servers));
1094 ASSERT_NO_FATAL_FAILURE(setupTlsServers(servers, &tls, &fingerprints));
1095
1096 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, domains, kDefaultParams, "", fingerprints));
1097
1098 // If the private DNS validation hasn't completed yet before backend DNS servers stop,
1099 // TLS servers will get stuck in handleOneRequest(), which causes this test stuck in
1100 // ~DnsTlsFrontend() because the TLS server loop threads can't be terminated.
1101 // So, wait for private DNS validation done before stopping backend DNS servers.
1102 for (int i = 0; i < MAXNS; i++) {
1103 ALOGI("Waiting for private DNS validation on %s.", tls[i]->listen_address().c_str());
1104 EXPECT_TRUE(tls[i]->waitForQueries(1, 5000));
1105 ALOGI("private DNS validation on %s done.", tls[i]->listen_address().c_str());
1106 }
1107
1108 std::vector<std::string> res_servers;
1109 std::vector<std::string> res_domains;
1110 std::vector<std::string> res_tls_servers;
1111 res_params res_params;
1112 std::vector<ResolverStats> res_stats;
1113 int wait_for_pending_req_timeout_count;
1114 ASSERT_TRUE(GetResolverInfo(&res_servers, &res_domains, &res_tls_servers, &res_params,
1115 &res_stats, &wait_for_pending_req_timeout_count));
1116
1117 // Check the size of the stats and its contents.
1118 EXPECT_EQ(static_cast<size_t>(MAXNS), res_servers.size());
1119 EXPECT_EQ(static_cast<size_t>(MAXNS), res_tls_servers.size());
1120 EXPECT_EQ(static_cast<size_t>(MAXDNSRCH), res_domains.size());
1121 EXPECT_TRUE(std::equal(servers.begin(), servers.begin() + MAXNS, res_servers.begin()));
1122 EXPECT_TRUE(std::equal(servers.begin(), servers.begin() + MAXNS, res_tls_servers.begin()));
1123 EXPECT_TRUE(std::equal(domains.begin(), domains.begin() + MAXDNSRCH, res_domains.begin()));
1124 }
1125
TEST_F(ResolverTest,ResolverStats)1126 TEST_F(ResolverTest, ResolverStats) {
1127 constexpr char listen_addr1[] = "127.0.0.4";
1128 constexpr char listen_addr2[] = "127.0.0.5";
1129 constexpr char listen_addr3[] = "127.0.0.6";
1130
1131 // Set server 1 timeout.
1132 test::DNSResponder dns1(listen_addr1, "53", 250, static_cast<ns_rcode>(-1));
1133 dns1.setResponseProbability(0.0);
1134 ASSERT_TRUE(dns1.startServer());
1135
1136 // Set server 2 responding server failure.
1137 test::DNSResponder dns2(listen_addr2);
1138 dns2.setResponseProbability(0.0);
1139 ASSERT_TRUE(dns2.startServer());
1140
1141 // Set server 3 workable.
1142 test::DNSResponder dns3(listen_addr3);
1143 dns3.addMapping(kHelloExampleCom, ns_type::ns_t_a, "1.2.3.4");
1144 ASSERT_TRUE(dns3.startServer());
1145
1146 std::vector<std::string> servers = {listen_addr1, listen_addr2, listen_addr3};
1147 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
1148
1149 dns3.clearQueries();
1150 const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
1151 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
1152 size_t found = GetNumQueries(dns3, kHelloExampleCom);
1153 EXPECT_LE(1U, found);
1154 std::string result_str = ToString(result);
1155 EXPECT_TRUE(result_str == "1.2.3.4") << ", result_str='" << result_str << "'";
1156
1157 std::vector<std::string> res_servers;
1158 std::vector<std::string> res_domains;
1159 std::vector<std::string> res_tls_servers;
1160 res_params res_params;
1161 std::vector<ResolverStats> res_stats;
1162 int wait_for_pending_req_timeout_count;
1163 ASSERT_TRUE(GetResolverInfo(&res_servers, &res_domains, &res_tls_servers, &res_params,
1164 &res_stats, &wait_for_pending_req_timeout_count));
1165
1166 EXPECT_EQ(1, res_stats[0].timeouts);
1167 EXPECT_EQ(1, res_stats[1].errors);
1168 EXPECT_EQ(1, res_stats[2].successes);
1169 }
1170
1171 // Test what happens if the specified TLS server is nonexistent.
TEST_F(ResolverTest,GetHostByName_TlsMissing)1172 TEST_F(ResolverTest, GetHostByName_TlsMissing) {
1173 constexpr char listen_addr[] = "127.0.0.3";
1174 constexpr char host_name[] = "tlsmissing.example.com.";
1175
1176 test::DNSResponder dns;
1177 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.3"}});
1178 std::vector<std::string> servers = { listen_addr };
1179
1180 // There's nothing listening on this address, so validation will either fail or
1181 /// hang. Either way, queries will continue to flow to the DNSResponder.
1182 ASSERT_TRUE(
1183 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
1184
1185 const hostent* result;
1186
1187 result = gethostbyname("tlsmissing");
1188 ASSERT_FALSE(result == nullptr);
1189 EXPECT_EQ("1.2.3.3", ToString(result));
1190
1191 // Clear TLS bit.
1192 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1193 }
1194
1195 // Test what happens if the specified TLS server replies with garbage.
TEST_F(ResolverTest,GetHostByName_TlsBroken)1196 TEST_F(ResolverTest, GetHostByName_TlsBroken) {
1197 constexpr char listen_addr[] = "127.0.0.3";
1198 constexpr char host_name1[] = "tlsbroken1.example.com.";
1199 constexpr char host_name2[] = "tlsbroken2.example.com.";
1200 const std::vector<DnsRecord> records = {
1201 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1202 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1203 };
1204
1205 test::DNSResponder dns;
1206 StartDns(dns, records);
1207 std::vector<std::string> servers = { listen_addr };
1208
1209 // Bind the specified private DNS socket but don't respond to any client sockets yet.
1210 int s = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP);
1211 ASSERT_TRUE(s >= 0);
1212 struct sockaddr_in tlsServer = {
1213 .sin_family = AF_INET,
1214 .sin_port = htons(853),
1215 };
1216 ASSERT_TRUE(inet_pton(AF_INET, listen_addr, &tlsServer.sin_addr));
1217 ASSERT_TRUE(enableSockopt(s, SOL_SOCKET, SO_REUSEPORT).ok());
1218 ASSERT_TRUE(enableSockopt(s, SOL_SOCKET, SO_REUSEADDR).ok());
1219 ASSERT_FALSE(bind(s, reinterpret_cast<struct sockaddr*>(&tlsServer), sizeof(tlsServer)));
1220 ASSERT_FALSE(listen(s, 1));
1221
1222 // Trigger TLS validation.
1223 ASSERT_TRUE(
1224 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
1225
1226 struct sockaddr_storage cliaddr;
1227 socklen_t sin_size = sizeof(cliaddr);
1228 int new_fd = accept4(s, reinterpret_cast<struct sockaddr *>(&cliaddr), &sin_size, SOCK_CLOEXEC);
1229 ASSERT_TRUE(new_fd > 0);
1230
1231 // We've received the new file descriptor but not written to it or closed, so the
1232 // validation is still pending. Queries should still flow correctly because the
1233 // server is not used until validation succeeds.
1234 const hostent* result;
1235 result = gethostbyname("tlsbroken1");
1236 ASSERT_FALSE(result == nullptr);
1237 EXPECT_EQ("1.2.3.1", ToString(result));
1238
1239 // Now we cause the validation to fail.
1240 std::string garbage = "definitely not a valid TLS ServerHello";
1241 write(new_fd, garbage.data(), garbage.size());
1242 close(new_fd);
1243
1244 // Validation failure shouldn't interfere with lookups, because lookups won't be sent
1245 // to the TLS server unless validation succeeds.
1246 result = gethostbyname("tlsbroken2");
1247 ASSERT_FALSE(result == nullptr);
1248 EXPECT_EQ("1.2.3.2", ToString(result));
1249
1250 // Clear TLS bit.
1251 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1252 close(s);
1253 }
1254
TEST_F(ResolverTest,GetHostByName_Tls)1255 TEST_F(ResolverTest, GetHostByName_Tls) {
1256 constexpr char listen_addr[] = "127.0.0.3";
1257 constexpr char listen_udp[] = "53";
1258 constexpr char listen_tls[] = "853";
1259 constexpr char host_name1[] = "tls1.example.com.";
1260 constexpr char host_name2[] = "tls2.example.com.";
1261 constexpr char host_name3[] = "tls3.example.com.";
1262 const std::vector<DnsRecord> records = {
1263 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1264 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1265 {host_name3, ns_type::ns_t_a, "1.2.3.3"},
1266 };
1267
1268 test::DNSResponder dns;
1269 StartDns(dns, records);
1270 std::vector<std::string> servers = { listen_addr };
1271
1272 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1273 ASSERT_TRUE(tls.startServer());
1274 ASSERT_TRUE(
1275 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
1276
1277 const hostent* result;
1278
1279 // Wait for validation to complete.
1280 EXPECT_TRUE(tls.waitForQueries(1, 5000));
1281
1282 result = gethostbyname("tls1");
1283 ASSERT_FALSE(result == nullptr);
1284 EXPECT_EQ("1.2.3.1", ToString(result));
1285
1286 // Wait for query to get counted.
1287 EXPECT_TRUE(tls.waitForQueries(2, 5000));
1288
1289 // Stop the TLS server. Since we're in opportunistic mode, queries will
1290 // fall back to the locally-assigned (clear text) nameservers.
1291 tls.stopServer();
1292
1293 dns.clearQueries();
1294 result = gethostbyname("tls2");
1295 EXPECT_FALSE(result == nullptr);
1296 EXPECT_EQ("1.2.3.2", ToString(result));
1297 const auto queries = dns.queries();
1298 EXPECT_EQ(1U, queries.size());
1299 EXPECT_EQ("tls2.example.com.", queries[0].first);
1300 EXPECT_EQ(ns_t_a, queries[0].second);
1301
1302 // Reset the resolvers without enabling TLS. Queries should still be routed
1303 // to the UDP endpoint.
1304 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1305
1306 result = gethostbyname("tls3");
1307 ASSERT_FALSE(result == nullptr);
1308 EXPECT_EQ("1.2.3.3", ToString(result));
1309 }
1310
TEST_F(ResolverTest,GetHostByName_TlsFingerprint)1311 TEST_F(ResolverTest, GetHostByName_TlsFingerprint) {
1312 constexpr char listen_addr[] = "127.0.0.3";
1313 constexpr char listen_udp[] = "53";
1314 constexpr char listen_tls[] = "853";
1315 test::DNSResponder dns;
1316 ASSERT_TRUE(dns.startServer());
1317 for (int chain_length = 1; chain_length <= 3; ++chain_length) {
1318 std::string host_name = StringPrintf("tlsfingerprint%d.example.com.", chain_length);
1319 dns.addMapping(host_name, ns_type::ns_t_a, "1.2.3.1");
1320 std::vector<std::string> servers = { listen_addr };
1321
1322 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1323 tls.set_chain_length(chain_length);
1324 ASSERT_TRUE(tls.startServer());
1325 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
1326 "", {base64Encode(tls.fingerprint())}));
1327
1328 const hostent* result;
1329
1330 // Wait for validation to complete.
1331 EXPECT_TRUE(tls.waitForQueries(1, 5000));
1332
1333 result = gethostbyname(StringPrintf("tlsfingerprint%d", chain_length).c_str());
1334 EXPECT_FALSE(result == nullptr);
1335 if (result) {
1336 EXPECT_EQ("1.2.3.1", ToString(result));
1337
1338 // Wait for query to get counted.
1339 EXPECT_TRUE(tls.waitForQueries(2, 5000));
1340 }
1341
1342 // Clear TLS bit to ensure revalidation.
1343 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1344 tls.stopServer();
1345 }
1346 }
1347
TEST_F(ResolverTest,GetHostByName_BadTlsFingerprint)1348 TEST_F(ResolverTest, GetHostByName_BadTlsFingerprint) {
1349 constexpr char listen_addr[] = "127.0.0.3";
1350 constexpr char listen_udp[] = "53";
1351 constexpr char listen_tls[] = "853";
1352 constexpr char host_name[] = "badtlsfingerprint.example.com.";
1353
1354 test::DNSResponder dns;
1355 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.1"}});
1356 std::vector<std::string> servers = { listen_addr };
1357
1358 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1359 ASSERT_TRUE(tls.startServer());
1360 std::vector<uint8_t> bad_fingerprint = tls.fingerprint();
1361 bad_fingerprint[5] += 1; // Corrupt the fingerprint.
1362 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "",
1363 {base64Encode(bad_fingerprint)}));
1364
1365 // The initial validation should fail at the fingerprint check before
1366 // issuing a query.
1367 EXPECT_FALSE(tls.waitForQueries(1, 500));
1368
1369 // A fingerprint was provided and failed to match, so the query should fail.
1370 EXPECT_EQ(nullptr, gethostbyname("badtlsfingerprint"));
1371
1372 // Clear TLS bit.
1373 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1374 }
1375
1376 // Test that we can pass two different fingerprints, and connection succeeds as long as
1377 // at least one of them matches the server.
TEST_F(ResolverTest,GetHostByName_TwoTlsFingerprints)1378 TEST_F(ResolverTest, GetHostByName_TwoTlsFingerprints) {
1379 constexpr char listen_addr[] = "127.0.0.3";
1380 constexpr char listen_udp[] = "53";
1381 constexpr char listen_tls[] = "853";
1382 constexpr char host_name[] = "twotlsfingerprints.example.com.";
1383
1384 test::DNSResponder dns;
1385 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.1"}});
1386 std::vector<std::string> servers = { listen_addr };
1387
1388 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1389 ASSERT_TRUE(tls.startServer());
1390 std::vector<uint8_t> bad_fingerprint = tls.fingerprint();
1391 bad_fingerprint[5] += 1; // Corrupt the fingerprint.
1392 ASSERT_TRUE(mDnsClient.SetResolversWithTls(
1393 servers, kDefaultSearchDomains, kDefaultParams, "",
1394 {base64Encode(bad_fingerprint), base64Encode(tls.fingerprint())}));
1395
1396 const hostent* result;
1397
1398 // Wait for validation to complete.
1399 EXPECT_TRUE(tls.waitForQueries(1, 5000));
1400
1401 result = gethostbyname("twotlsfingerprints");
1402 ASSERT_FALSE(result == nullptr);
1403 EXPECT_EQ("1.2.3.1", ToString(result));
1404
1405 // Wait for query to get counted.
1406 EXPECT_TRUE(tls.waitForQueries(2, 5000));
1407
1408 // Clear TLS bit.
1409 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1410 }
1411
TEST_F(ResolverTest,GetHostByName_TlsFingerprintGoesBad)1412 TEST_F(ResolverTest, GetHostByName_TlsFingerprintGoesBad) {
1413 constexpr char listen_addr[] = "127.0.0.3";
1414 constexpr char listen_udp[] = "53";
1415 constexpr char listen_tls[] = "853";
1416 constexpr char host_name1[] = "tlsfingerprintgoesbad1.example.com.";
1417 constexpr char host_name2[] = "tlsfingerprintgoesbad2.example.com.";
1418 const std::vector<DnsRecord> records = {
1419 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1420 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1421 };
1422
1423 test::DNSResponder dns;
1424 StartDns(dns, records);
1425 std::vector<std::string> servers = { listen_addr };
1426
1427 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1428 ASSERT_TRUE(tls.startServer());
1429 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "",
1430 {base64Encode(tls.fingerprint())}));
1431
1432 const hostent* result;
1433
1434 // Wait for validation to complete.
1435 EXPECT_TRUE(tls.waitForQueries(1, 5000));
1436
1437 result = gethostbyname("tlsfingerprintgoesbad1");
1438 ASSERT_FALSE(result == nullptr);
1439 EXPECT_EQ("1.2.3.1", ToString(result));
1440
1441 // Wait for query to get counted.
1442 EXPECT_TRUE(tls.waitForQueries(2, 5000));
1443
1444 // Restart the TLS server. This will generate a new certificate whose fingerprint
1445 // no longer matches the stored fingerprint.
1446 tls.stopServer();
1447 tls.startServer();
1448
1449 result = gethostbyname("tlsfingerprintgoesbad2");
1450 ASSERT_TRUE(result == nullptr);
1451 EXPECT_EQ(HOST_NOT_FOUND, h_errno);
1452
1453 // Clear TLS bit.
1454 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1455 }
1456
TEST_F(ResolverTest,GetHostByName_TlsFailover)1457 TEST_F(ResolverTest, GetHostByName_TlsFailover) {
1458 constexpr char listen_addr1[] = "127.0.0.3";
1459 constexpr char listen_addr2[] = "127.0.0.4";
1460 constexpr char listen_udp[] = "53";
1461 constexpr char listen_tls[] = "853";
1462 constexpr char host_name1[] = "tlsfailover1.example.com.";
1463 constexpr char host_name2[] = "tlsfailover2.example.com.";
1464 const std::vector<DnsRecord> records1 = {
1465 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1466 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1467 };
1468 const std::vector<DnsRecord> records2 = {
1469 {host_name1, ns_type::ns_t_a, "1.2.3.3"},
1470 {host_name2, ns_type::ns_t_a, "1.2.3.4"},
1471 };
1472
1473 test::DNSResponder dns1(listen_addr1);
1474 test::DNSResponder dns2(listen_addr2);
1475 StartDns(dns1, records1);
1476 StartDns(dns2, records2);
1477
1478 std::vector<std::string> servers = { listen_addr1, listen_addr2 };
1479
1480 test::DnsTlsFrontend tls1(listen_addr1, listen_tls, listen_addr1, listen_udp);
1481 test::DnsTlsFrontend tls2(listen_addr2, listen_tls, listen_addr2, listen_udp);
1482 ASSERT_TRUE(tls1.startServer());
1483 ASSERT_TRUE(tls2.startServer());
1484 ASSERT_TRUE(mDnsClient.SetResolversWithTls(
1485 servers, kDefaultSearchDomains, kDefaultParams, "",
1486 {base64Encode(tls1.fingerprint()), base64Encode(tls2.fingerprint())}));
1487
1488 const hostent* result;
1489
1490 // Wait for validation to complete.
1491 EXPECT_TRUE(tls1.waitForQueries(1, 5000));
1492 EXPECT_TRUE(tls2.waitForQueries(1, 5000));
1493
1494 result = gethostbyname("tlsfailover1");
1495 ASSERT_FALSE(result == nullptr);
1496 EXPECT_EQ("1.2.3.1", ToString(result));
1497
1498 // Wait for query to get counted.
1499 EXPECT_TRUE(tls1.waitForQueries(2, 5000));
1500 // No new queries should have reached tls2.
1501 EXPECT_EQ(1, tls2.queries());
1502
1503 // Stop tls1. Subsequent queries should attempt to reach tls1, fail, and retry to tls2.
1504 tls1.stopServer();
1505
1506 result = gethostbyname("tlsfailover2");
1507 EXPECT_EQ("1.2.3.4", ToString(result));
1508
1509 // Wait for query to get counted.
1510 EXPECT_TRUE(tls2.waitForQueries(2, 5000));
1511
1512 // No additional queries should have reached the insecure servers.
1513 EXPECT_EQ(2U, dns1.queries().size());
1514 EXPECT_EQ(2U, dns2.queries().size());
1515
1516 // Clear TLS bit.
1517 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
1518 }
1519
TEST_F(ResolverTest,GetHostByName_BadTlsName)1520 TEST_F(ResolverTest, GetHostByName_BadTlsName) {
1521 constexpr char listen_addr[] = "127.0.0.3";
1522 constexpr char listen_udp[] = "53";
1523 constexpr char listen_tls[] = "853";
1524 constexpr char host_name[] = "badtlsname.example.com.";
1525
1526 test::DNSResponder dns;
1527 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.1"}});
1528 std::vector<std::string> servers = { listen_addr };
1529
1530 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1531 ASSERT_TRUE(tls.startServer());
1532 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
1533 "www.example.com", {}));
1534
1535 // The TLS server's certificate doesn't chain to a known CA, and a nonempty name was specified,
1536 // so the client should fail the TLS handshake before ever issuing a query.
1537 EXPECT_FALSE(tls.waitForQueries(1, 500));
1538
1539 // The query should fail hard, because a name was specified.
1540 EXPECT_EQ(nullptr, gethostbyname("badtlsname"));
1541
1542 // Clear TLS bit.
1543 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1544 }
1545
TEST_F(ResolverTest,GetAddrInfo_Tls)1546 TEST_F(ResolverTest, GetAddrInfo_Tls) {
1547 constexpr char listen_addr[] = "127.0.0.3";
1548 constexpr char listen_udp[] = "53";
1549 constexpr char listen_tls[] = "853";
1550 constexpr char host_name[] = "addrinfotls.example.com.";
1551 const std::vector<DnsRecord> records = {
1552 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1553 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1554 };
1555
1556 test::DNSResponder dns;
1557 StartDns(dns, records);
1558 std::vector<std::string> servers = { listen_addr };
1559
1560 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1561 ASSERT_TRUE(tls.startServer());
1562 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "",
1563 {base64Encode(tls.fingerprint())}));
1564
1565 // Wait for validation to complete.
1566 EXPECT_TRUE(tls.waitForQueries(1, 5000));
1567
1568 dns.clearQueries();
1569 ScopedAddrinfo result = safe_getaddrinfo("addrinfotls", nullptr, nullptr);
1570 EXPECT_TRUE(result != nullptr);
1571 size_t found = GetNumQueries(dns, host_name);
1572 EXPECT_LE(1U, found);
1573 // Could be A or AAAA
1574 std::string result_str = ToString(result);
1575 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
1576 << ", result_str='" << result_str << "'";
1577 // Wait for both A and AAAA queries to get counted.
1578 EXPECT_TRUE(tls.waitForQueries(3, 5000));
1579
1580 // Clear TLS bit.
1581 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1582 }
1583
TEST_F(ResolverTest,TlsBypass)1584 TEST_F(ResolverTest, TlsBypass) {
1585 const char OFF[] = "off";
1586 const char OPPORTUNISTIC[] = "opportunistic";
1587 const char STRICT[] = "strict";
1588
1589 const char GETHOSTBYNAME[] = "gethostbyname";
1590 const char GETADDRINFO[] = "getaddrinfo";
1591 const char GETADDRINFOFORNET[] = "getaddrinfofornet";
1592
1593 const unsigned BYPASS_NETID = NETID_USE_LOCAL_NAMESERVERS | TEST_NETID;
1594
1595 const std::vector<uint8_t> NOOP_FINGERPRINT(SHA256_SIZE, 0U);
1596
1597 const char ADDR4[] = "192.0.2.1";
1598 const char ADDR6[] = "2001:db8::1";
1599
1600 const char cleartext_addr[] = "127.0.0.53";
1601 const char cleartext_port[] = "53";
1602 const char tls_port[] = "853";
1603 const std::vector<std::string> servers = { cleartext_addr };
1604
1605 test::DNSResponder dns(cleartext_addr);
1606 ASSERT_TRUE(dns.startServer());
1607
1608 test::DnsTlsFrontend tls(cleartext_addr, tls_port, cleartext_addr, cleartext_port);
1609
1610 struct TestConfig {
1611 const std::string mode;
1612 const bool withWorkingTLS;
1613 const std::string method;
1614
1615 std::string asHostName() const {
1616 return StringPrintf("%s.%s.%s.",
1617 mode.c_str(),
1618 withWorkingTLS ? "tlsOn" : "tlsOff",
1619 method.c_str());
1620 }
1621 } testConfigs[]{
1622 {OFF, false, GETHOSTBYNAME},
1623 {OPPORTUNISTIC, false, GETHOSTBYNAME},
1624 {STRICT, false, GETHOSTBYNAME},
1625 {OFF, true, GETHOSTBYNAME},
1626 {OPPORTUNISTIC, true, GETHOSTBYNAME},
1627 {STRICT, true, GETHOSTBYNAME},
1628 {OFF, false, GETADDRINFO},
1629 {OPPORTUNISTIC, false, GETADDRINFO},
1630 {STRICT, false, GETADDRINFO},
1631 {OFF, true, GETADDRINFO},
1632 {OPPORTUNISTIC, true, GETADDRINFO},
1633 {STRICT, true, GETADDRINFO},
1634 {OFF, false, GETADDRINFOFORNET},
1635 {OPPORTUNISTIC, false, GETADDRINFOFORNET},
1636 {STRICT, false, GETADDRINFOFORNET},
1637 {OFF, true, GETADDRINFOFORNET},
1638 {OPPORTUNISTIC, true, GETADDRINFOFORNET},
1639 {STRICT, true, GETADDRINFOFORNET},
1640 };
1641
1642 for (const auto& config : testConfigs) {
1643 const std::string testHostName = config.asHostName();
1644 SCOPED_TRACE(testHostName);
1645
1646 // Don't tempt test bugs due to caching.
1647 const char* host_name = testHostName.c_str();
1648 dns.addMapping(host_name, ns_type::ns_t_a, ADDR4);
1649 dns.addMapping(host_name, ns_type::ns_t_aaaa, ADDR6);
1650
1651 if (config.withWorkingTLS) ASSERT_TRUE(tls.startServer());
1652
1653 if (config.mode == OFF) {
1654 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, kDefaultSearchDomains,
1655 kDefaultParams));
1656 } else if (config.mode == OPPORTUNISTIC) {
1657 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
1658 kDefaultParams, "", {}));
1659 // Wait for validation to complete.
1660 if (config.withWorkingTLS) EXPECT_TRUE(tls.waitForQueries(1, 5000));
1661 } else if (config.mode == STRICT) {
1662 // We use the existence of fingerprints to trigger strict mode,
1663 // rather than hostname validation.
1664 const auto& fingerprint =
1665 (config.withWorkingTLS) ? tls.fingerprint() : NOOP_FINGERPRINT;
1666 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
1667 kDefaultParams, "",
1668 {base64Encode(fingerprint)}));
1669 // Wait for validation to complete.
1670 if (config.withWorkingTLS) EXPECT_TRUE(tls.waitForQueries(1, 5000));
1671 } else {
1672 FAIL() << "Unsupported Private DNS mode: " << config.mode;
1673 }
1674
1675 const int tlsQueriesBefore = tls.queries();
1676
1677 const hostent* h_result = nullptr;
1678 ScopedAddrinfo ai_result;
1679
1680 if (config.method == GETHOSTBYNAME) {
1681 ASSERT_EQ(0, setNetworkForResolv(BYPASS_NETID));
1682 h_result = gethostbyname(host_name);
1683
1684 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
1685 ASSERT_FALSE(h_result == nullptr);
1686 ASSERT_EQ(4, h_result->h_length);
1687 ASSERT_FALSE(h_result->h_addr_list[0] == nullptr);
1688 EXPECT_EQ(ADDR4, ToString(h_result));
1689 EXPECT_TRUE(h_result->h_addr_list[1] == nullptr);
1690 } else if (config.method == GETADDRINFO) {
1691 ASSERT_EQ(0, setNetworkForResolv(BYPASS_NETID));
1692 ai_result = safe_getaddrinfo(host_name, nullptr, nullptr);
1693 EXPECT_TRUE(ai_result != nullptr);
1694
1695 EXPECT_LE(1U, GetNumQueries(dns, host_name));
1696 // Could be A or AAAA
1697 const std::string result_str = ToString(ai_result);
1698 EXPECT_TRUE(result_str == ADDR4 || result_str == ADDR6)
1699 << ", result_str='" << result_str << "'";
1700 } else if (config.method == GETADDRINFOFORNET) {
1701 addrinfo* raw_ai_result = nullptr;
1702 EXPECT_EQ(0, android_getaddrinfofornet(host_name, /*servname=*/nullptr,
1703 /*hints=*/nullptr, BYPASS_NETID, MARK_UNSET,
1704 &raw_ai_result));
1705 ai_result.reset(raw_ai_result);
1706
1707 EXPECT_LE(1U, GetNumQueries(dns, host_name));
1708 // Could be A or AAAA
1709 const std::string result_str = ToString(ai_result);
1710 EXPECT_TRUE(result_str == ADDR4 || result_str == ADDR6)
1711 << ", result_str='" << result_str << "'";
1712 } else {
1713 FAIL() << "Unsupported query method: " << config.method;
1714 }
1715
1716 const int tlsQueriesAfter = tls.queries();
1717 EXPECT_EQ(0, tlsQueriesAfter - tlsQueriesBefore);
1718
1719 // Clear per-process resolv netid.
1720 ASSERT_EQ(0, setNetworkForResolv(NETID_UNSET));
1721 tls.stopServer();
1722 dns.clearQueries();
1723 }
1724 }
1725
TEST_F(ResolverTest,StrictMode_NoTlsServers)1726 TEST_F(ResolverTest, StrictMode_NoTlsServers) {
1727 const std::vector<uint8_t> NOOP_FINGERPRINT(SHA256_SIZE, 0U);
1728 constexpr char cleartext_addr[] = "127.0.0.53";
1729 const std::vector<std::string> servers = { cleartext_addr };
1730 constexpr char host_name[] = "strictmode.notlsips.example.com.";
1731 const std::vector<DnsRecord> records = {
1732 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1733 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1734 };
1735
1736 test::DNSResponder dns(cleartext_addr);
1737 StartDns(dns, records);
1738
1739 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, {},
1740 "", {base64Encode(NOOP_FINGERPRINT)}));
1741
1742 addrinfo* ai_result = nullptr;
1743 EXPECT_NE(0, getaddrinfo(host_name, nullptr, nullptr, &ai_result));
1744 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
1745 }
1746
1747 namespace {
1748
getAsyncResponse(int fd,int * rcode,uint8_t * buf,int bufLen)1749 int getAsyncResponse(int fd, int* rcode, uint8_t* buf, int bufLen) {
1750 struct pollfd wait_fd[1];
1751 wait_fd[0].fd = fd;
1752 wait_fd[0].events = POLLIN;
1753 short revents;
1754 int ret;
1755
1756 ret = poll(wait_fd, 1, -1);
1757 revents = wait_fd[0].revents;
1758 if (revents & POLLIN) {
1759 int n = resNetworkResult(fd, rcode, buf, bufLen);
1760 // Verify that resNetworkResult() closed the fd
1761 char dummy;
1762 EXPECT_EQ(-1, read(fd, &dummy, sizeof dummy));
1763 EXPECT_EQ(EBADF, errno);
1764 return n;
1765 }
1766 return -1;
1767 }
1768
toString(uint8_t * buf,int bufLen,int ipType)1769 std::string toString(uint8_t* buf, int bufLen, int ipType) {
1770 ns_msg handle;
1771 int ancount, n = 0;
1772 ns_rr rr;
1773
1774 if (ns_initparse((const uint8_t*) buf, bufLen, &handle) >= 0) {
1775 ancount = ns_msg_count(handle, ns_s_an);
1776 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1777 const uint8_t* rdata = ns_rr_rdata(rr);
1778 char buffer[INET6_ADDRSTRLEN];
1779 if (inet_ntop(ipType, (const char*) rdata, buffer, sizeof(buffer))) {
1780 return buffer;
1781 }
1782 }
1783 }
1784 return "";
1785 }
1786
dns_open_proxy()1787 int dns_open_proxy() {
1788 int s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
1789 if (s == -1) {
1790 return -1;
1791 }
1792 const int one = 1;
1793 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
1794
1795 static const struct sockaddr_un proxy_addr = {
1796 .sun_family = AF_UNIX,
1797 .sun_path = "/dev/socket/dnsproxyd",
1798 };
1799
1800 if (TEMP_FAILURE_RETRY(connect(s, (const struct sockaddr*) &proxy_addr, sizeof(proxy_addr))) !=
1801 0) {
1802 close(s);
1803 return -1;
1804 }
1805
1806 return s;
1807 }
1808
expectAnswersValid(int fd,int ipType,const std::string & expectedAnswer)1809 void expectAnswersValid(int fd, int ipType, const std::string& expectedAnswer) {
1810 int rcode = -1;
1811 uint8_t buf[MAXPACKET] = {};
1812
1813 int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
1814 EXPECT_GT(res, 0);
1815 EXPECT_EQ(expectedAnswer, toString(buf, res, ipType));
1816 }
1817
expectAnswersNotValid(int fd,int expectedErrno)1818 void expectAnswersNotValid(int fd, int expectedErrno) {
1819 int rcode = -1;
1820 uint8_t buf[MAXPACKET] = {};
1821
1822 int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
1823 EXPECT_EQ(expectedErrno, res);
1824 }
1825
1826 } // namespace
1827
TEST_F(ResolverTest,Async_NormalQueryV4V6)1828 TEST_F(ResolverTest, Async_NormalQueryV4V6) {
1829 constexpr char listen_addr[] = "127.0.0.4";
1830 constexpr char host_name[] = "howdy.example.com.";
1831 const std::vector<DnsRecord> records = {
1832 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1833 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1834 };
1835
1836 test::DNSResponder dns(listen_addr);
1837 StartDns(dns, records);
1838 std::vector<std::string> servers = {listen_addr};
1839 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
1840
1841 int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1842 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
1843 EXPECT_TRUE(fd1 != -1);
1844 EXPECT_TRUE(fd2 != -1);
1845
1846 uint8_t buf[MAXPACKET] = {};
1847 int rcode;
1848 int res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
1849 EXPECT_GT(res, 0);
1850 EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
1851
1852 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
1853 EXPECT_GT(res, 0);
1854 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
1855
1856 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
1857
1858 // Re-query verify cache works
1859 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1860 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
1861
1862 EXPECT_TRUE(fd1 != -1);
1863 EXPECT_TRUE(fd2 != -1);
1864
1865 res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
1866 EXPECT_GT(res, 0);
1867 EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
1868
1869 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
1870 EXPECT_GT(res, 0);
1871 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
1872
1873 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
1874 }
1875
TEST_F(ResolverTest,Async_BadQuery)1876 TEST_F(ResolverTest, Async_BadQuery) {
1877 constexpr char listen_addr[] = "127.0.0.4";
1878 constexpr char host_name[] = "howdy.example.com.";
1879 const std::vector<DnsRecord> records = {
1880 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1881 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1882 };
1883
1884 test::DNSResponder dns(listen_addr);
1885 StartDns(dns, records);
1886 std::vector<std::string> servers = {listen_addr};
1887 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
1888
1889 static struct {
1890 int fd;
1891 const char* dname;
1892 const int queryType;
1893 const int expectRcode;
1894 } kTestData[] = {
1895 {-1, "", ns_t_aaaa, 0},
1896 {-1, "as65ass46", ns_t_aaaa, 0},
1897 {-1, "454564564564", ns_t_aaaa, 0},
1898 {-1, "h645235", ns_t_a, 0},
1899 {-1, "www.google.com", ns_t_a, 0},
1900 };
1901
1902 for (auto& td : kTestData) {
1903 SCOPED_TRACE(td.dname);
1904 td.fd = resNetworkQuery(TEST_NETID, td.dname, ns_c_in, td.queryType, 0);
1905 EXPECT_TRUE(td.fd != -1);
1906 }
1907
1908 // dns_responder return empty resp(packet only contains query part) with no error currently
1909 for (const auto& td : kTestData) {
1910 uint8_t buf[MAXPACKET] = {};
1911 int rcode;
1912 SCOPED_TRACE(td.dname);
1913 int res = getAsyncResponse(td.fd, &rcode, buf, MAXPACKET);
1914 EXPECT_GT(res, 0);
1915 EXPECT_EQ(rcode, td.expectRcode);
1916 }
1917 }
1918
TEST_F(ResolverTest,Async_EmptyAnswer)1919 TEST_F(ResolverTest, Async_EmptyAnswer) {
1920 constexpr char listen_addr[] = "127.0.0.4";
1921 constexpr char host_name[] = "howdy.example.com.";
1922 const std::vector<DnsRecord> records = {
1923 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1924 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1925 };
1926
1927 test::DNSResponder dns(listen_addr);
1928 StartDns(dns, records);
1929 std::vector<std::string> servers = {listen_addr};
1930 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
1931
1932 // TODO: Disable retry to make this test explicit.
1933 auto& cv = dns.getCv();
1934 auto& cvMutex = dns.getCvMutex();
1935 int fd1;
1936 // Wait on the condition variable to ensure that the DNS server has handled our first query.
1937 {
1938 std::unique_lock lk(cvMutex);
1939 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
1940 EXPECT_TRUE(fd1 != -1);
1941 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lk, std::chrono::seconds(1)));
1942 }
1943
1944 dns.setResponseProbability(0.0);
1945
1946 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1947 EXPECT_TRUE(fd2 != -1);
1948
1949 int fd3 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1950 EXPECT_TRUE(fd3 != -1);
1951
1952 uint8_t buf[MAXPACKET] = {};
1953 int rcode;
1954
1955 // expect no response
1956 int res = getAsyncResponse(fd3, &rcode, buf, MAXPACKET);
1957 EXPECT_EQ(-ETIMEDOUT, res);
1958
1959 // expect no response
1960 memset(buf, 0, MAXPACKET);
1961 res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
1962 EXPECT_EQ(-ETIMEDOUT, res);
1963
1964 dns.setResponseProbability(1.0);
1965
1966 int fd4 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1967 EXPECT_TRUE(fd4 != -1);
1968
1969 memset(buf, 0, MAXPACKET);
1970 res = getAsyncResponse(fd4, &rcode, buf, MAXPACKET);
1971 EXPECT_GT(res, 0);
1972 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
1973
1974 memset(buf, 0, MAXPACKET);
1975 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
1976 EXPECT_GT(res, 0);
1977 EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
1978 }
1979
TEST_F(ResolverTest,Async_MalformedQuery)1980 TEST_F(ResolverTest, Async_MalformedQuery) {
1981 constexpr char listen_addr[] = "127.0.0.4";
1982 constexpr char host_name[] = "howdy.example.com.";
1983 const std::vector<DnsRecord> records = {
1984 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1985 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1986 };
1987
1988 test::DNSResponder dns(listen_addr);
1989 StartDns(dns, records);
1990 std::vector<std::string> servers = {listen_addr};
1991 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
1992
1993 int fd = dns_open_proxy();
1994 EXPECT_TRUE(fd > 0);
1995
1996 const std::string badMsg = "16-52512#";
1997 static const struct {
1998 const std::string cmd;
1999 const int expectErr;
2000 } kTestData[] = {
2001 // Too few arguments
2002 {"resnsend " + badMsg + '\0', -EINVAL},
2003 // Bad netId
2004 {"resnsend badnetId 0 " + badMsg + '\0', -EINVAL},
2005 // Bad raw data
2006 {"resnsend " + std::to_string(TEST_NETID) + " 0 " + badMsg + '\0', -EILSEQ},
2007 };
2008
2009 for (unsigned int i = 0; i < std::size(kTestData); i++) {
2010 auto& td = kTestData[i];
2011 SCOPED_TRACE(td.cmd);
2012 ssize_t rc = TEMP_FAILURE_RETRY(write(fd, td.cmd.c_str(), td.cmd.size()));
2013 EXPECT_EQ(rc, static_cast<ssize_t>(td.cmd.size()));
2014
2015 int32_t tmp;
2016 rc = TEMP_FAILURE_RETRY(read(fd, &tmp, sizeof(tmp)));
2017 EXPECT_TRUE(rc > 0);
2018 EXPECT_EQ(static_cast<int>(ntohl(tmp)), td.expectErr);
2019 }
2020 // Normal query with answer buffer
2021 // This is raw data of query "howdy.example.com" type 1 class 1
2022 std::string query = "81sBAAABAAAAAAAABWhvd2R5B2V4YW1wbGUDY29tAAABAAE=";
2023 std::string cmd = "resnsend " + std::to_string(TEST_NETID) + " 0 " + query + '\0';
2024 ssize_t rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
2025 EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
2026
2027 uint8_t smallBuf[1] = {};
2028 int rcode;
2029 rc = getAsyncResponse(fd, &rcode, smallBuf, 1);
2030 EXPECT_EQ(-EMSGSIZE, rc);
2031
2032 // Do the normal test with large buffer again
2033 fd = dns_open_proxy();
2034 EXPECT_TRUE(fd > 0);
2035 rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
2036 EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
2037 uint8_t buf[MAXPACKET] = {};
2038 rc = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2039 EXPECT_EQ("1.2.3.4", toString(buf, rc, AF_INET));
2040 }
2041
TEST_F(ResolverTest,Async_CacheFlags)2042 TEST_F(ResolverTest, Async_CacheFlags) {
2043 constexpr char listen_addr[] = "127.0.0.4";
2044 constexpr char host_name[] = "howdy.example.com.";
2045 constexpr char another_host_name[] = "howdy.example2.com.";
2046 const std::vector<DnsRecord> records = {
2047 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2048 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2049 {another_host_name, ns_type::ns_t_a, "1.2.3.5"},
2050 {another_host_name, ns_type::ns_t_aaaa, "::1.2.3.5"},
2051 };
2052
2053 test::DNSResponder dns(listen_addr);
2054 StartDns(dns, records);
2055 std::vector<std::string> servers = {listen_addr};
2056 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2057
2058 // ANDROID_RESOLV_NO_CACHE_STORE
2059 int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2060 ANDROID_RESOLV_NO_CACHE_STORE);
2061 EXPECT_TRUE(fd1 != -1);
2062 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2063 ANDROID_RESOLV_NO_CACHE_STORE);
2064 EXPECT_TRUE(fd2 != -1);
2065 int fd3 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2066 ANDROID_RESOLV_NO_CACHE_STORE);
2067 EXPECT_TRUE(fd3 != -1);
2068
2069 expectAnswersValid(fd3, AF_INET, "1.2.3.4");
2070 expectAnswersValid(fd2, AF_INET, "1.2.3.4");
2071 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
2072
2073 // No cache exists, expect 3 queries
2074 EXPECT_EQ(3U, GetNumQueries(dns, host_name));
2075
2076 // Re-query and cache
2077 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2078
2079 EXPECT_TRUE(fd1 != -1);
2080
2081 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
2082
2083 // Now we have cache, expect 4 queries
2084 EXPECT_EQ(4U, GetNumQueries(dns, host_name));
2085
2086 // ANDROID_RESOLV_NO_CACHE_LOOKUP
2087 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2088 ANDROID_RESOLV_NO_CACHE_LOOKUP);
2089 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2090 ANDROID_RESOLV_NO_CACHE_LOOKUP);
2091
2092 EXPECT_TRUE(fd1 != -1);
2093 EXPECT_TRUE(fd2 != -1);
2094
2095 expectAnswersValid(fd2, AF_INET, "1.2.3.4");
2096 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
2097
2098 // Skip cache, expect 6 queries
2099 EXPECT_EQ(6U, GetNumQueries(dns, host_name));
2100
2101 // Re-query verify cache works
2102 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2103 ANDROID_RESOLV_NO_CACHE_STORE);
2104 EXPECT_TRUE(fd1 != -1);
2105 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
2106
2107 // Cache hits, expect still 6 queries
2108 EXPECT_EQ(6U, GetNumQueries(dns, host_name));
2109
2110 // Start to verify if ANDROID_RESOLV_NO_CACHE_LOOKUP does write response into cache
2111 dns.clearQueries();
2112
2113 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa,
2114 ANDROID_RESOLV_NO_CACHE_LOOKUP);
2115 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa,
2116 ANDROID_RESOLV_NO_CACHE_LOOKUP);
2117
2118 EXPECT_TRUE(fd1 != -1);
2119 EXPECT_TRUE(fd2 != -1);
2120
2121 expectAnswersValid(fd2, AF_INET6, "::1.2.3.4");
2122 expectAnswersValid(fd1, AF_INET6, "::1.2.3.4");
2123
2124 // Skip cache, expect 2 queries
2125 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
2126
2127 // Re-query without flags
2128 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2129 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2130
2131 EXPECT_TRUE(fd1 != -1);
2132 EXPECT_TRUE(fd2 != -1);
2133
2134 expectAnswersValid(fd2, AF_INET6, "::1.2.3.4");
2135 expectAnswersValid(fd1, AF_INET6, "::1.2.3.4");
2136
2137 // Cache hits, expect still 2 queries
2138 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
2139
2140 // Test both ANDROID_RESOLV_NO_CACHE_STORE and ANDROID_RESOLV_NO_CACHE_LOOKUP are set
2141 dns.clearQueries();
2142
2143 // Make sure that the cache of "howdy.example2.com" exists.
2144 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa, 0);
2145 EXPECT_TRUE(fd1 != -1);
2146 expectAnswersValid(fd1, AF_INET6, "::1.2.3.5");
2147 EXPECT_EQ(1U, GetNumQueries(dns, another_host_name));
2148
2149 // Re-query with testFlags
2150 const int testFlag = ANDROID_RESOLV_NO_CACHE_STORE | ANDROID_RESOLV_NO_CACHE_LOOKUP;
2151 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa, testFlag);
2152 EXPECT_TRUE(fd1 != -1);
2153 expectAnswersValid(fd1, AF_INET6, "::1.2.3.5");
2154 // Expect cache lookup is skipped.
2155 EXPECT_EQ(2U, GetNumQueries(dns, another_host_name));
2156
2157 // Do another query with testFlags
2158 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_a, testFlag);
2159 EXPECT_TRUE(fd1 != -1);
2160 expectAnswersValid(fd1, AF_INET, "1.2.3.5");
2161 // Expect cache lookup is skipped.
2162 EXPECT_EQ(3U, GetNumQueries(dns, another_host_name));
2163
2164 // Re-query with no flags
2165 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_a, 0);
2166 EXPECT_TRUE(fd1 != -1);
2167 expectAnswersValid(fd1, AF_INET, "1.2.3.5");
2168 // Expect no cache hit because cache storing is also skipped in previous query.
2169 EXPECT_EQ(4U, GetNumQueries(dns, another_host_name));
2170 }
2171
TEST_F(ResolverTest,Async_NoRetryFlag)2172 TEST_F(ResolverTest, Async_NoRetryFlag) {
2173 constexpr char listen_addr0[] = "127.0.0.4";
2174 constexpr char listen_addr1[] = "127.0.0.6";
2175 constexpr char host_name[] = "howdy.example.com.";
2176 const std::vector<DnsRecord> records = {
2177 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2178 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2179 };
2180
2181 test::DNSResponder dns0(listen_addr0);
2182 test::DNSResponder dns1(listen_addr1);
2183 StartDns(dns0, records);
2184 StartDns(dns1, records);
2185 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr0, listen_addr1}));
2186
2187 dns0.clearQueries();
2188 dns1.clearQueries();
2189
2190 dns0.setResponseProbability(0.0);
2191 dns1.setResponseProbability(0.0);
2192
2193 int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2194 ANDROID_RESOLV_NO_RETRY);
2195 EXPECT_TRUE(fd1 != -1);
2196
2197 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa,
2198 ANDROID_RESOLV_NO_RETRY);
2199 EXPECT_TRUE(fd2 != -1);
2200
2201 // expect no response
2202 expectAnswersNotValid(fd1, -ETIMEDOUT);
2203 expectAnswersNotValid(fd2, -ETIMEDOUT);
2204
2205 // No retry case, expect total 2 queries. The server is selected randomly.
2206 EXPECT_EQ(2U, GetNumQueries(dns0, host_name) + GetNumQueries(dns1, host_name));
2207
2208 dns0.clearQueries();
2209 dns1.clearQueries();
2210
2211 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2212 EXPECT_TRUE(fd1 != -1);
2213
2214 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2215 EXPECT_TRUE(fd2 != -1);
2216
2217 // expect no response
2218 expectAnswersNotValid(fd1, -ETIMEDOUT);
2219 expectAnswersNotValid(fd2, -ETIMEDOUT);
2220
2221 // Retry case, expect 4 queries
2222 EXPECT_EQ(4U, GetNumQueries(dns0, host_name));
2223 EXPECT_EQ(4U, GetNumQueries(dns1, host_name));
2224 }
2225
TEST_F(ResolverTest,Async_VerifyQueryID)2226 TEST_F(ResolverTest, Async_VerifyQueryID) {
2227 constexpr char listen_addr[] = "127.0.0.4";
2228 constexpr char host_name[] = "howdy.example.com.";
2229 const std::vector<DnsRecord> records = {
2230 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2231 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2232 };
2233
2234 test::DNSResponder dns(listen_addr);
2235 StartDns(dns, records);
2236 std::vector<std::string> servers = {listen_addr};
2237 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2238
2239 const uint8_t queryBuf1[] = {
2240 /* Header */
2241 0x55, 0x66, /* Transaction ID */
2242 0x01, 0x00, /* Flags */
2243 0x00, 0x01, /* Questions */
2244 0x00, 0x00, /* Answer RRs */
2245 0x00, 0x00, /* Authority RRs */
2246 0x00, 0x00, /* Additional RRs */
2247 /* Queries */
2248 0x05, 0x68, 0x6f, 0x77, 0x64, 0x79, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
2249 0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */
2250 0x00, 0x01, /* Type */
2251 0x00, 0x01 /* Class */
2252 };
2253
2254 int fd = resNetworkSend(TEST_NETID, queryBuf1, sizeof(queryBuf1), 0);
2255 EXPECT_TRUE(fd != -1);
2256
2257 uint8_t buf[MAXPACKET] = {};
2258 int rcode;
2259
2260 int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2261 EXPECT_GT(res, 0);
2262 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2263
2264 auto hp = reinterpret_cast<HEADER*>(buf);
2265 EXPECT_EQ(21862U, htons(hp->id));
2266
2267 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2268
2269 const uint8_t queryBuf2[] = {
2270 /* Header */
2271 0x00, 0x53, /* Transaction ID */
2272 0x01, 0x00, /* Flags */
2273 0x00, 0x01, /* Questions */
2274 0x00, 0x00, /* Answer RRs */
2275 0x00, 0x00, /* Authority RRs */
2276 0x00, 0x00, /* Additional RRs */
2277 /* Queries */
2278 0x05, 0x68, 0x6f, 0x77, 0x64, 0x79, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
2279 0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */
2280 0x00, 0x01, /* Type */
2281 0x00, 0x01 /* Class */
2282 };
2283
2284 // Re-query verify cache works and query id is correct
2285 fd = resNetworkSend(TEST_NETID, queryBuf2, sizeof(queryBuf2), 0);
2286
2287 EXPECT_TRUE(fd != -1);
2288
2289 res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2290 EXPECT_GT(res, 0);
2291 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2292
2293 EXPECT_EQ(0x0053U, htons(hp->id));
2294
2295 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2296 }
2297
2298 // This test checks that the resolver should not generate the request containing OPT RR when using
2299 // cleartext DNS. If we query the DNS server not supporting EDNS0 and it reponds with
2300 // FORMERR_ON_EDNS, we will fallback to no EDNS0 and try again. If the server does no response, we
2301 // won't retry so that we get no answer.
TEST_F(ResolverTest,BrokenEdns)2302 TEST_F(ResolverTest, BrokenEdns) {
2303 typedef test::DNSResponder::Edns Edns;
2304 enum ExpectResult { EXPECT_FAILURE, EXPECT_SUCCESS };
2305
2306 const char OFF[] = "off";
2307 const char OPPORTUNISTIC_UDP[] = "opportunistic_udp";
2308 const char OPPORTUNISTIC_TLS[] = "opportunistic_tls";
2309 const char STRICT[] = "strict";
2310 const char GETHOSTBYNAME[] = "gethostbyname";
2311 const char GETADDRINFO[] = "getaddrinfo";
2312 const std::vector<uint8_t> NOOP_FINGERPRINT(SHA256_SIZE, 0U);
2313 const char ADDR4[] = "192.0.2.1";
2314 const char CLEARTEXT_ADDR[] = "127.0.0.53";
2315 const char CLEARTEXT_PORT[] = "53";
2316 const char TLS_PORT[] = "853";
2317 const std::vector<std::string> servers = { CLEARTEXT_ADDR };
2318
2319 test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, 250, ns_rcode::ns_r_servfail);
2320 ASSERT_TRUE(dns.startServer());
2321
2322 test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2323
2324 static const struct TestConfig {
2325 std::string mode;
2326 std::string method;
2327 Edns edns;
2328 ExpectResult expectResult;
2329
2330 std::string asHostName() const {
2331 const char* ednsString;
2332 switch (edns) {
2333 case Edns::ON:
2334 ednsString = "ednsOn";
2335 break;
2336 case Edns::FORMERR_ON_EDNS:
2337 ednsString = "ednsFormerr";
2338 break;
2339 case Edns::DROP:
2340 ednsString = "ednsDrop";
2341 break;
2342 default:
2343 ednsString = "";
2344 break;
2345 }
2346 return StringPrintf("%s.%s.%s.", mode.c_str(), method.c_str(), ednsString);
2347 }
2348 } testConfigs[] = {
2349 // In OPPORTUNISTIC_TLS, we get no answer if the DNS server supports TLS but not EDNS0.
2350 // Could such server exist? if so, we might need to fallback to query cleartext DNS.
2351 // Another thing is that {OPPORTUNISTIC_TLS, Edns::DROP} and {STRICT, Edns::DROP} are
2352 // commented out since TLS timeout is not configurable.
2353 // TODO: Uncomment them after TLS timeout is configurable.
2354 {OFF, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
2355 {OPPORTUNISTIC_UDP, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
2356 {OPPORTUNISTIC_TLS, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
2357 {STRICT, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
2358 {OFF, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2359 {OPPORTUNISTIC_UDP, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2360 {OPPORTUNISTIC_TLS, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
2361 {STRICT, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
2362 {OFF, GETHOSTBYNAME, Edns::DROP, EXPECT_SUCCESS},
2363 {OPPORTUNISTIC_UDP, GETHOSTBYNAME, Edns::DROP, EXPECT_SUCCESS},
2364 //{OPPORTUNISTIC_TLS, GETHOSTBYNAME, Edns::DROP, EXPECT_FAILURE},
2365 //{STRICT, GETHOSTBYNAME, Edns::DROP, EXPECT_FAILURE},
2366 {OFF, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
2367 {OPPORTUNISTIC_UDP, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
2368 {OPPORTUNISTIC_TLS, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
2369 {STRICT, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
2370 {OFF, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2371 {OPPORTUNISTIC_UDP, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2372 {OPPORTUNISTIC_TLS, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
2373 {STRICT, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
2374 {OFF, GETADDRINFO, Edns::DROP, EXPECT_SUCCESS},
2375 {OPPORTUNISTIC_UDP, GETADDRINFO, Edns::DROP, EXPECT_SUCCESS},
2376 //{OPPORTUNISTIC_TLS, GETADDRINFO, Edns::DROP, EXPECT_FAILURE},
2377 //{STRICT, GETADDRINFO, Edns::DROP, EXPECT_FAILURE},
2378 };
2379
2380 for (const auto& config : testConfigs) {
2381 const std::string testHostName = config.asHostName();
2382 SCOPED_TRACE(testHostName);
2383
2384 const char* host_name = testHostName.c_str();
2385 dns.addMapping(host_name, ns_type::ns_t_a, ADDR4);
2386 dns.setEdns(config.edns);
2387
2388 if (config.mode == OFF) {
2389 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2390 } else if (config.mode == OPPORTUNISTIC_UDP) {
2391 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
2392 kDefaultParams, "", {}));
2393 } else if (config.mode == OPPORTUNISTIC_TLS) {
2394 ASSERT_TRUE(tls.startServer());
2395 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
2396 kDefaultParams, "", {}));
2397 // Wait for validation to complete.
2398 EXPECT_TRUE(tls.waitForQueries(1, 5000));
2399 } else if (config.mode == STRICT) {
2400 ASSERT_TRUE(tls.startServer());
2401 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
2402 kDefaultParams, "",
2403 {base64Encode(tls.fingerprint())}));
2404 // Wait for validation to complete.
2405 EXPECT_TRUE(tls.waitForQueries(1, 5000));
2406 }
2407
2408 if (config.method == GETHOSTBYNAME) {
2409 const hostent* h_result = gethostbyname(host_name);
2410 if (config.expectResult == EXPECT_SUCCESS) {
2411 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2412 ASSERT_TRUE(h_result != nullptr);
2413 ASSERT_EQ(4, h_result->h_length);
2414 ASSERT_FALSE(h_result->h_addr_list[0] == nullptr);
2415 EXPECT_EQ(ADDR4, ToString(h_result));
2416 EXPECT_TRUE(h_result->h_addr_list[1] == nullptr);
2417 } else {
2418 EXPECT_EQ(0U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
2419 ASSERT_TRUE(h_result == nullptr);
2420 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2421 }
2422 } else if (config.method == GETADDRINFO) {
2423 ScopedAddrinfo ai_result;
2424 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2425 ai_result = safe_getaddrinfo(host_name, nullptr, &hints);
2426 if (config.expectResult == EXPECT_SUCCESS) {
2427 EXPECT_TRUE(ai_result != nullptr);
2428 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2429 const std::string result_str = ToString(ai_result);
2430 EXPECT_EQ(ADDR4, result_str);
2431 } else {
2432 EXPECT_TRUE(ai_result == nullptr);
2433 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
2434 }
2435 } else {
2436 FAIL() << "Unsupported query method: " << config.method;
2437 }
2438
2439 tls.stopServer();
2440 dns.clearQueries();
2441 }
2442 }
2443
2444 // DNS-over-TLS validation success, but server does not respond to TLS query after a while.
2445 // Resolver should have a reasonable number of retries instead of spinning forever. We don't have
2446 // an efficient way to know if resolver is stuck in an infinite loop. However, test case will be
2447 // failed due to timeout.
TEST_F(ResolverTest,UnstableTls)2448 TEST_F(ResolverTest, UnstableTls) {
2449 const char CLEARTEXT_ADDR[] = "127.0.0.53";
2450 const char CLEARTEXT_PORT[] = "53";
2451 const char TLS_PORT[] = "853";
2452 const char* host_name1 = "nonexistent1.example.com.";
2453 const char* host_name2 = "nonexistent2.example.com.";
2454 const std::vector<std::string> servers = {CLEARTEXT_ADDR};
2455
2456 test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, 250, ns_rcode::ns_r_servfail);
2457 ASSERT_TRUE(dns.startServer());
2458 dns.setEdns(test::DNSResponder::Edns::FORMERR_ON_EDNS);
2459 test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2460 ASSERT_TRUE(tls.startServer());
2461 ASSERT_TRUE(
2462 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
2463 // Wait for validation complete.
2464 EXPECT_TRUE(tls.waitForQueries(1, 5000));
2465 // Shutdown TLS server to get an error. It's similar to no response case but without waiting.
2466 tls.stopServer();
2467
2468 const hostent* h_result = gethostbyname(host_name1);
2469 EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
2470 ASSERT_TRUE(h_result == nullptr);
2471 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2472
2473 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2474 ScopedAddrinfo ai_result = safe_getaddrinfo(host_name2, nullptr, &hints);
2475 EXPECT_TRUE(ai_result == nullptr);
2476 EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
2477 }
2478
2479 // DNS-over-TLS validation success, but server does not respond to TLS query after a while.
2480 // Moreover, server responds RCODE=FORMERR even on non-EDNS query.
TEST_F(ResolverTest,BogusDnsServer)2481 TEST_F(ResolverTest, BogusDnsServer) {
2482 const char CLEARTEXT_ADDR[] = "127.0.0.53";
2483 const char CLEARTEXT_PORT[] = "53";
2484 const char TLS_PORT[] = "853";
2485 const char* host_name1 = "nonexistent1.example.com.";
2486 const char* host_name2 = "nonexistent2.example.com.";
2487 const std::vector<std::string> servers = {CLEARTEXT_ADDR};
2488
2489 test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, 250, ns_rcode::ns_r_servfail);
2490 ASSERT_TRUE(dns.startServer());
2491 test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2492 ASSERT_TRUE(tls.startServer());
2493 ASSERT_TRUE(
2494 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
2495 // Wait for validation complete.
2496 EXPECT_TRUE(tls.waitForQueries(1, 5000));
2497 // Shutdown TLS server to get an error. It's similar to no response case but without waiting.
2498 tls.stopServer();
2499 dns.setEdns(test::DNSResponder::Edns::FORMERR_UNCOND);
2500
2501 const hostent* h_result = gethostbyname(host_name1);
2502 EXPECT_EQ(0U, GetNumQueries(dns, host_name1));
2503 ASSERT_TRUE(h_result == nullptr);
2504 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2505
2506 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2507 ScopedAddrinfo ai_result = safe_getaddrinfo(host_name2, nullptr, &hints);
2508 EXPECT_TRUE(ai_result == nullptr);
2509 EXPECT_EQ(0U, GetNumQueries(dns, host_name2));
2510 }
2511
TEST_F(ResolverTest,GetAddrInfo_Dns64Synthesize)2512 TEST_F(ResolverTest, GetAddrInfo_Dns64Synthesize) {
2513 constexpr char listen_addr[] = "::1";
2514 constexpr char dns64_name[] = "ipv4only.arpa.";
2515 constexpr char host_name[] = "v4only.example.com.";
2516 const std::vector<DnsRecord> records = {
2517 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2518 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2519 };
2520
2521 test::DNSResponder dns(listen_addr);
2522 StartDns(dns, records);
2523
2524 std::vector<std::string> servers = {listen_addr};
2525 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2526
2527 // Start NAT64 prefix discovery and wait for it to complete.
2528 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2529 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2530
2531 // hints are necessary in order to let netd know which type of addresses the caller is
2532 // interested in.
2533 const addrinfo hints = {.ai_family = AF_UNSPEC};
2534 ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, &hints);
2535 EXPECT_TRUE(result != nullptr);
2536 // TODO: BUG: there should only be two queries, one AAAA (which returns no records) and one A
2537 // (which returns 1.2.3.4). But there is an extra AAAA.
2538 EXPECT_EQ(3U, GetNumQueries(dns, host_name));
2539
2540 std::string result_str = ToString(result);
2541 EXPECT_EQ(result_str, "64:ff9b::102:304");
2542
2543 // Stopping NAT64 prefix discovery disables synthesis.
2544 EXPECT_TRUE(mDnsClient.resolvService()->stopPrefix64Discovery(TEST_NETID).isOk());
2545 EXPECT_FALSE(WaitForPrefix64Detected(TEST_NETID, 300));
2546
2547 dns.clearQueries();
2548
2549 result = safe_getaddrinfo("v4only", nullptr, &hints);
2550 EXPECT_TRUE(result != nullptr);
2551 // TODO: BUG: there should only be one query, an AAAA (which returns no records), because the
2552 // A is already cached. But there is an extra AAAA.
2553 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
2554
2555 result_str = ToString(result);
2556 EXPECT_EQ(result_str, "1.2.3.4");
2557 }
2558
TEST_F(ResolverTest,GetAddrInfo_Dns64QuerySpecified)2559 TEST_F(ResolverTest, GetAddrInfo_Dns64QuerySpecified) {
2560 constexpr char listen_addr[] = "::1";
2561 constexpr char dns64_name[] = "ipv4only.arpa.";
2562 constexpr char host_name[] = "v4only.example.com.";
2563 const std::vector<DnsRecord> records = {
2564 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2565 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2566 };
2567
2568 test::DNSResponder dns(listen_addr);
2569 StartDns(dns, records);
2570 const std::vector<std::string> servers = {listen_addr};
2571 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2572
2573 // Start NAT64 prefix discovery and wait for it to complete.
2574 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2575 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2576
2577 // Ensure to synthesize AAAA if AF_INET6 is specified, and not to synthesize AAAA
2578 // in AF_INET case.
2579 addrinfo hints;
2580 memset(&hints, 0, sizeof(hints));
2581 hints.ai_family = AF_INET6;
2582 ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, &hints);
2583 EXPECT_TRUE(result != nullptr);
2584 std::string result_str = ToString(result);
2585 EXPECT_EQ(result_str, "64:ff9b::102:304");
2586
2587 hints.ai_family = AF_INET;
2588 result = safe_getaddrinfo("v4only", nullptr, &hints);
2589 EXPECT_TRUE(result != nullptr);
2590 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2591 result_str = ToString(result);
2592 EXPECT_EQ(result_str, "1.2.3.4");
2593 }
2594
TEST_F(ResolverTest,GetAddrInfo_Dns64QueryUnspecifiedV6)2595 TEST_F(ResolverTest, GetAddrInfo_Dns64QueryUnspecifiedV6) {
2596 constexpr char listen_addr[] = "::1";
2597 constexpr char dns64_name[] = "ipv4only.arpa.";
2598 constexpr char host_name[] = "v4v6.example.com.";
2599 const std::vector<DnsRecord> records = {
2600 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2601 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2602 {host_name, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
2603 };
2604
2605 test::DNSResponder dns(listen_addr);
2606 StartDns(dns, records);
2607 const std::vector<std::string> servers = {listen_addr};
2608 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2609
2610 // Start NAT64 prefix discovery and wait for it to complete.
2611 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2612 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2613
2614 const addrinfo hints = {.ai_family = AF_UNSPEC};
2615 ScopedAddrinfo result = safe_getaddrinfo("v4v6", nullptr, &hints);
2616 EXPECT_TRUE(result != nullptr);
2617 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2618
2619 // In AF_UNSPEC case, do not synthesize AAAA if there's at least one AAAA answer.
2620 const std::vector<std::string> result_strs = ToStrings(result);
2621 for (const auto& str : result_strs) {
2622 EXPECT_TRUE(str == "1.2.3.4" || str == "2001:db8::102:304")
2623 << ", result_str='" << str << "'";
2624 }
2625 }
2626
TEST_F(ResolverTest,GetAddrInfo_Dns64QueryUnspecifiedNoV6)2627 TEST_F(ResolverTest, GetAddrInfo_Dns64QueryUnspecifiedNoV6) {
2628 constexpr char listen_addr[] = "::1";
2629 constexpr char dns64_name[] = "ipv4only.arpa.";
2630 constexpr char host_name[] = "v4v6.example.com.";
2631 const std::vector<DnsRecord> records = {
2632 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2633 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2634 };
2635
2636 test::DNSResponder dns(listen_addr);
2637 StartDns(dns, records);
2638 const std::vector<std::string> servers = {listen_addr};
2639 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2640
2641 // Start NAT64 prefix discovery and wait for it to complete.
2642 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2643 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2644
2645 const addrinfo hints = {.ai_family = AF_UNSPEC};
2646 ScopedAddrinfo result = safe_getaddrinfo("v4v6", nullptr, &hints);
2647 EXPECT_TRUE(result != nullptr);
2648 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2649
2650 // In AF_UNSPEC case, synthesize AAAA if there's no AAAA answer.
2651 std::string result_str = ToString(result);
2652 EXPECT_EQ(result_str, "64:ff9b::102:304");
2653 }
2654
TEST_F(ResolverTest,GetAddrInfo_Dns64QuerySpecialUseIPv4Addresses)2655 TEST_F(ResolverTest, GetAddrInfo_Dns64QuerySpecialUseIPv4Addresses) {
2656 constexpr char THIS_NETWORK[] = "this_network";
2657 constexpr char LOOPBACK[] = "loopback";
2658 constexpr char LINK_LOCAL[] = "link_local";
2659 constexpr char MULTICAST[] = "multicast";
2660 constexpr char LIMITED_BROADCAST[] = "limited_broadcast";
2661
2662 constexpr char ADDR_THIS_NETWORK[] = "0.0.0.1";
2663 constexpr char ADDR_LOOPBACK[] = "127.0.0.1";
2664 constexpr char ADDR_LINK_LOCAL[] = "169.254.0.1";
2665 constexpr char ADDR_MULTICAST[] = "224.0.0.1";
2666 constexpr char ADDR_LIMITED_BROADCAST[] = "255.255.255.255";
2667
2668 constexpr char listen_addr[] = "::1";
2669 constexpr char dns64_name[] = "ipv4only.arpa.";
2670
2671 test::DNSResponder dns(listen_addr);
2672 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
2673 const std::vector<std::string> servers = {listen_addr};
2674 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2675
2676 // Start NAT64 prefix discovery and wait for it to complete.
2677 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2678 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2679
2680 static const struct TestConfig {
2681 std::string name;
2682 std::string addr;
2683
2684 std::string asHostName() const { return StringPrintf("%s.example.com.", name.c_str()); }
2685 } testConfigs[]{
2686 {THIS_NETWORK, ADDR_THIS_NETWORK},
2687 {LOOPBACK, ADDR_LOOPBACK},
2688 {LINK_LOCAL, ADDR_LINK_LOCAL},
2689 {MULTICAST, ADDR_MULTICAST},
2690 {LIMITED_BROADCAST, ADDR_LIMITED_BROADCAST}
2691 };
2692
2693 for (const auto& config : testConfigs) {
2694 const std::string testHostName = config.asHostName();
2695 SCOPED_TRACE(testHostName);
2696
2697 const char* host_name = testHostName.c_str();
2698 dns.addMapping(host_name, ns_type::ns_t_a, config.addr.c_str());
2699
2700 addrinfo hints;
2701 memset(&hints, 0, sizeof(hints));
2702 hints.ai_family = AF_INET6;
2703 ScopedAddrinfo result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
2704 // In AF_INET6 case, don't return IPv4 answers
2705 EXPECT_TRUE(result == nullptr);
2706 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2707 dns.clearQueries();
2708
2709 memset(&hints, 0, sizeof(hints));
2710 hints.ai_family = AF_UNSPEC;
2711 result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
2712 EXPECT_TRUE(result != nullptr);
2713 // Expect IPv6 query only. IPv4 answer has been cached in previous query.
2714 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2715 // In AF_UNSPEC case, don't synthesize special use IPv4 address.
2716 std::string result_str = ToString(result);
2717 EXPECT_EQ(result_str, config.addr.c_str());
2718 dns.clearQueries();
2719 }
2720 }
2721
TEST_F(ResolverTest,GetAddrInfo_Dns64QueryWithNullArgumentHints)2722 TEST_F(ResolverTest, GetAddrInfo_Dns64QueryWithNullArgumentHints) {
2723 constexpr char listen_addr[] = "::1";
2724 constexpr char dns64_name[] = "ipv4only.arpa.";
2725 constexpr char host_name[] = "v4only.example.com.";
2726 constexpr char host_name2[] = "v4v6.example.com.";
2727 const std::vector<DnsRecord> records = {
2728 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2729 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2730 {host_name2, ns_type::ns_t_a, "1.2.3.4"},
2731 {host_name2, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
2732 };
2733
2734 test::DNSResponder dns(listen_addr);
2735 StartDns(dns, records);
2736 const std::vector<std::string> servers = {listen_addr};
2737 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2738
2739 // Start NAT64 prefix discovery and wait for it to complete.
2740 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2741 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2742
2743 // Assign argument hints of getaddrinfo() as null is equivalent to set ai_family AF_UNSPEC.
2744 // In AF_UNSPEC case, synthesize AAAA if there has A answer only.
2745 ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, nullptr);
2746 EXPECT_TRUE(result != nullptr);
2747 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2748 std::string result_str = ToString(result);
2749 EXPECT_EQ(result_str, "64:ff9b::102:304");
2750 dns.clearQueries();
2751
2752 // In AF_UNSPEC case, do not synthesize AAAA if there's at least one AAAA answer.
2753 result = safe_getaddrinfo("v4v6", nullptr, nullptr);
2754 EXPECT_TRUE(result != nullptr);
2755 EXPECT_LE(2U, GetNumQueries(dns, host_name2));
2756 std::vector<std::string> result_strs = ToStrings(result);
2757 for (const auto& str : result_strs) {
2758 EXPECT_TRUE(str == "1.2.3.4" || str == "2001:db8::102:304")
2759 << ", result_str='" << str << "'";
2760 }
2761 }
2762
TEST_F(ResolverTest,GetAddrInfo_Dns64QueryNullArgumentNode)2763 TEST_F(ResolverTest, GetAddrInfo_Dns64QueryNullArgumentNode) {
2764 constexpr char ADDR_ANYADDR_V4[] = "0.0.0.0";
2765 constexpr char ADDR_ANYADDR_V6[] = "::";
2766 constexpr char ADDR_LOCALHOST_V4[] = "127.0.0.1";
2767 constexpr char ADDR_LOCALHOST_V6[] = "::1";
2768
2769 constexpr char PORT_NAME_HTTP[] = "http";
2770 constexpr char PORT_NUMBER_HTTP[] = "80";
2771
2772 constexpr char listen_addr[] = "::1";
2773 constexpr char dns64_name[] = "ipv4only.arpa.";
2774
2775 test::DNSResponder dns(listen_addr);
2776 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
2777 const std::vector<std::string> servers = {listen_addr};
2778 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2779
2780 // Start NAT64 prefix discovery and wait for it to complete.
2781 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2782 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2783
2784 // If node is null, return address is listed by libc/getaddrinfo.c as follows.
2785 // - passive socket -> anyaddr (0.0.0.0 or ::)
2786 // - non-passive socket -> localhost (127.0.0.1 or ::1)
2787 static const struct TestConfig {
2788 int flag;
2789 std::string addr_v4;
2790 std::string addr_v6;
2791
2792 std::string asParameters() const {
2793 return StringPrintf("flag=%d, addr_v4=%s, addr_v6=%s", flag, addr_v4.c_str(),
2794 addr_v6.c_str());
2795 }
2796 } testConfigs[]{
2797 {0 /* non-passive */, ADDR_LOCALHOST_V4, ADDR_LOCALHOST_V6},
2798 {AI_PASSIVE, ADDR_ANYADDR_V4, ADDR_ANYADDR_V6}
2799 };
2800
2801 for (const auto& config : testConfigs) {
2802 SCOPED_TRACE(config.asParameters());
2803
2804 addrinfo hints = {
2805 .ai_family = AF_UNSPEC, // any address family
2806 .ai_socktype = 0, // any type
2807 .ai_protocol = 0, // any protocol
2808 .ai_flags = config.flag,
2809 };
2810
2811 // Assign hostname as null and service as port name.
2812 ScopedAddrinfo result = safe_getaddrinfo(nullptr, PORT_NAME_HTTP, &hints);
2813 ASSERT_TRUE(result != nullptr);
2814
2815 // Can't be synthesized because it should not get into Netd.
2816 std::vector<std::string> result_strs = ToStrings(result);
2817 for (const auto& str : result_strs) {
2818 EXPECT_TRUE(str == config.addr_v4 || str == config.addr_v6)
2819 << ", result_str='" << str << "'";
2820 }
2821
2822 // Assign hostname as null and service as numeric port number.
2823 hints.ai_flags = config.flag | AI_NUMERICSERV;
2824 result = safe_getaddrinfo(nullptr, PORT_NUMBER_HTTP, &hints);
2825 ASSERT_TRUE(result != nullptr);
2826
2827 // Can't be synthesized because it should not get into Netd.
2828 result_strs = ToStrings(result);
2829 for (const auto& str : result_strs) {
2830 EXPECT_TRUE(str == config.addr_v4 || str == config.addr_v6)
2831 << ", result_str='" << str << "'";
2832 }
2833 }
2834 }
2835
TEST_F(ResolverTest,GetHostByAddr_ReverseDnsQueryWithHavingNat64Prefix)2836 TEST_F(ResolverTest, GetHostByAddr_ReverseDnsQueryWithHavingNat64Prefix) {
2837 struct hostent* result = nullptr;
2838 struct in_addr v4addr;
2839 struct in6_addr v6addr;
2840
2841 constexpr char listen_addr[] = "::1";
2842 constexpr char dns64_name[] = "ipv4only.arpa.";
2843 constexpr char ptr_name[] = "v4v6.example.com.";
2844 // PTR record for IPv4 address 1.2.3.4
2845 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2846 // PTR record for IPv6 address 2001:db8::102:304
2847 constexpr char ptr_addr_v6[] =
2848 "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.";
2849 const std::vector<DnsRecord> records = {
2850 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2851 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2852 {ptr_addr_v6, ns_type::ns_t_ptr, ptr_name},
2853 };
2854
2855 test::DNSResponder dns(listen_addr);
2856 StartDns(dns, records);
2857 const std::vector<std::string> servers = {listen_addr};
2858 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2859
2860 // Start NAT64 prefix discovery and wait for it to complete.
2861 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2862 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2863
2864 // Reverse IPv4 DNS query. Prefix should have no effect on it.
2865 inet_pton(AF_INET, "1.2.3.4", &v4addr);
2866 result = gethostbyaddr(&v4addr, sizeof(v4addr), AF_INET);
2867 ASSERT_TRUE(result != nullptr);
2868 std::string result_str = result->h_name ? result->h_name : "null";
2869 EXPECT_EQ(result_str, "v4v6.example.com");
2870
2871 // Reverse IPv6 DNS query. Prefix should have no effect on it.
2872 inet_pton(AF_INET6, "2001:db8::102:304", &v6addr);
2873 result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2874 ASSERT_TRUE(result != nullptr);
2875 result_str = result->h_name ? result->h_name : "null";
2876 EXPECT_EQ(result_str, "v4v6.example.com");
2877 }
2878
TEST_F(ResolverTest,GetHostByAddr_ReverseDns64Query)2879 TEST_F(ResolverTest, GetHostByAddr_ReverseDns64Query) {
2880 constexpr char listen_addr[] = "::1";
2881 constexpr char dns64_name[] = "ipv4only.arpa.";
2882 constexpr char ptr_name[] = "v4only.example.com.";
2883 // PTR record for IPv4 address 1.2.3.4
2884 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2885 // PTR record for IPv6 address 64:ff9b::1.2.3.4
2886 constexpr char ptr_addr_v6_nomapping[] =
2887 "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.";
2888 constexpr char ptr_name_v6_synthesis[] = "v6synthesis.example.com.";
2889 // PTR record for IPv6 address 64:ff9b::5.6.7.8
2890 constexpr char ptr_addr_v6_synthesis[] =
2891 "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.";
2892 const std::vector<DnsRecord> records = {
2893 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2894 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2895 {ptr_addr_v6_synthesis, ns_type::ns_t_ptr, ptr_name_v6_synthesis},
2896 };
2897
2898 test::DNSResponder dns(listen_addr);
2899 StartDns(dns, records);
2900 // "ptr_addr_v6_nomapping" is not mapped in DNS server
2901 const std::vector<std::string> servers = {listen_addr};
2902 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2903
2904 // Start NAT64 prefix discovery and wait for it to complete.
2905 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2906 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2907
2908 // Synthesized PTR record doesn't exist on DNS server
2909 // Reverse IPv6 DNS64 query while DNS server doesn't have an answer for synthesized address.
2910 // After querying synthesized address failed, expect that prefix is removed from IPv6
2911 // synthesized address and do reverse IPv4 query instead.
2912 struct in6_addr v6addr;
2913 inet_pton(AF_INET6, "64:ff9b::1.2.3.4", &v6addr);
2914 struct hostent* result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2915 ASSERT_TRUE(result != nullptr);
2916 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_nomapping)); // PTR record not exist
2917 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4)); // PTR record exist
2918 std::string result_str = result->h_name ? result->h_name : "null";
2919 EXPECT_EQ(result_str, "v4only.example.com");
2920 // Check that return address has been mapped from IPv4 to IPv6 address because Netd
2921 // removes NAT64 prefix and does IPv4 DNS reverse lookup in this case. Then, Netd
2922 // fakes the return IPv4 address as original queried IPv6 address.
2923 result_str = ToString(result);
2924 EXPECT_EQ(result_str, "64:ff9b::102:304");
2925 dns.clearQueries();
2926
2927 // Synthesized PTR record exists on DNS server
2928 // Reverse IPv6 DNS64 query while DNS server has an answer for synthesized address.
2929 // Expect to Netd pass through synthesized address for DNS queries.
2930 inet_pton(AF_INET6, "64:ff9b::5.6.7.8", &v6addr);
2931 result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2932 ASSERT_TRUE(result != nullptr);
2933 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_synthesis));
2934 result_str = result->h_name ? result->h_name : "null";
2935 EXPECT_EQ(result_str, "v6synthesis.example.com");
2936 }
2937
TEST_F(ResolverTest,GetHostByAddr_ReverseDns64QueryFromHostFile)2938 TEST_F(ResolverTest, GetHostByAddr_ReverseDns64QueryFromHostFile) {
2939 constexpr char dns64_name[] = "ipv4only.arpa.";
2940 constexpr char host_name[] = "localhost";
2941 // The address is synthesized by prefix64:localhost.
2942 constexpr char host_addr[] = "64:ff9b::7f00:1";
2943 constexpr char listen_addr[] = "::1";
2944
2945 test::DNSResponder dns(listen_addr);
2946 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
2947 const std::vector<std::string> servers = {listen_addr};
2948 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2949
2950 // Start NAT64 prefix discovery and wait for it to complete.
2951 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2952 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2953
2954 // Using synthesized "localhost" address to be a trick for resolving host name
2955 // from host file /etc/hosts and "localhost" is the only name in /etc/hosts. Note that this is
2956 // not realistic: the code never synthesizes AAAA records for addresses in 127.0.0.0/8.
2957 struct in6_addr v6addr;
2958 inet_pton(AF_INET6, host_addr, &v6addr);
2959 struct hostent* result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2960 ASSERT_TRUE(result != nullptr);
2961 // Expect no DNS queries; localhost is resolved via /etc/hosts.
2962 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
2963
2964 ASSERT_EQ(sizeof(in6_addr), (unsigned) result->h_length);
2965 ASSERT_EQ(AF_INET6, result->h_addrtype);
2966 std::string result_str = ToString(result);
2967 EXPECT_EQ(result_str, host_addr);
2968 result_str = result->h_name ? result->h_name : "null";
2969 EXPECT_EQ(result_str, host_name);
2970 }
2971
TEST_F(ResolverTest,GetNameInfo_ReverseDnsQueryWithHavingNat64Prefix)2972 TEST_F(ResolverTest, GetNameInfo_ReverseDnsQueryWithHavingNat64Prefix) {
2973 constexpr char listen_addr[] = "::1";
2974 constexpr char dns64_name[] = "ipv4only.arpa.";
2975 constexpr char ptr_name[] = "v4v6.example.com.";
2976 // PTR record for IPv4 address 1.2.3.4
2977 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2978 // PTR record for IPv6 address 2001:db8::102:304
2979 constexpr char ptr_addr_v6[] =
2980 "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.";
2981 const std::vector<DnsRecord> records = {
2982 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2983 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2984 {ptr_addr_v6, ns_type::ns_t_ptr, ptr_name},
2985 };
2986
2987 test::DNSResponder dns(listen_addr);
2988 StartDns(dns, records);
2989 const std::vector<std::string> servers = {listen_addr};
2990 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2991
2992 // Start NAT64 prefix discovery and wait for it to complete.
2993 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
2994 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2995
2996 static const struct TestConfig {
2997 int flag;
2998 int family;
2999 std::string addr;
3000 std::string host;
3001
3002 std::string asParameters() const {
3003 return StringPrintf("flag=%d, family=%d, addr=%s, host=%s", flag, family, addr.c_str(),
3004 host.c_str());
3005 }
3006 } testConfigs[]{
3007 {NI_NAMEREQD, AF_INET, "1.2.3.4", "v4v6.example.com"},
3008 {NI_NUMERICHOST, AF_INET, "1.2.3.4", "1.2.3.4"},
3009 {0, AF_INET, "1.2.3.4", "v4v6.example.com"},
3010 {0, AF_INET, "5.6.7.8", "5.6.7.8"}, // unmapped
3011 {NI_NAMEREQD, AF_INET6, "2001:db8::102:304", "v4v6.example.com"},
3012 {NI_NUMERICHOST, AF_INET6, "2001:db8::102:304", "2001:db8::102:304"},
3013 {0, AF_INET6, "2001:db8::102:304", "v4v6.example.com"},
3014 {0, AF_INET6, "2001:db8::506:708", "2001:db8::506:708"}, // unmapped
3015 };
3016
3017 // Reverse IPv4/IPv6 DNS query. Prefix should have no effect on it.
3018 for (const auto& config : testConfigs) {
3019 SCOPED_TRACE(config.asParameters());
3020
3021 int rv;
3022 char host[NI_MAXHOST];
3023 struct sockaddr_in sin;
3024 struct sockaddr_in6 sin6;
3025 if (config.family == AF_INET) {
3026 memset(&sin, 0, sizeof(sin));
3027 sin.sin_family = AF_INET;
3028 inet_pton(AF_INET, config.addr.c_str(), &sin.sin_addr);
3029 rv = getnameinfo((const struct sockaddr*) &sin, sizeof(sin), host, sizeof(host),
3030 nullptr, 0, config.flag);
3031 if (config.flag == NI_NAMEREQD) EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4));
3032 } else if (config.family == AF_INET6) {
3033 memset(&sin6, 0, sizeof(sin6));
3034 sin6.sin6_family = AF_INET6;
3035 inet_pton(AF_INET6, config.addr.c_str(), &sin6.sin6_addr);
3036 rv = getnameinfo((const struct sockaddr*) &sin6, sizeof(sin6), host, sizeof(host),
3037 nullptr, 0, config.flag);
3038 if (config.flag == NI_NAMEREQD) EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6));
3039 }
3040 ASSERT_EQ(0, rv);
3041 std::string result_str = host;
3042 EXPECT_EQ(result_str, config.host);
3043 dns.clearQueries();
3044 }
3045 }
3046
TEST_F(ResolverTest,GetNameInfo_ReverseDns64Query)3047 TEST_F(ResolverTest, GetNameInfo_ReverseDns64Query) {
3048 constexpr char listen_addr[] = "::1";
3049 constexpr char dns64_name[] = "ipv4only.arpa.";
3050 constexpr char ptr_name[] = "v4only.example.com.";
3051 // PTR record for IPv4 address 1.2.3.4
3052 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
3053 // PTR record for IPv6 address 64:ff9b::1.2.3.4
3054 constexpr char ptr_addr_v6_nomapping[] =
3055 "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.";
3056 constexpr char ptr_name_v6_synthesis[] = "v6synthesis.example.com.";
3057 // PTR record for IPv6 address 64:ff9b::5.6.7.8
3058 constexpr char ptr_addr_v6_synthesis[] =
3059 "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.";
3060 const std::vector<DnsRecord> records = {
3061 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3062 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
3063 {ptr_addr_v6_synthesis, ns_type::ns_t_ptr, ptr_name_v6_synthesis},
3064 };
3065
3066 test::DNSResponder dns(listen_addr);
3067 StartDns(dns, records);
3068 const std::vector<std::string> servers = {listen_addr};
3069 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3070
3071 // Start NAT64 prefix discovery and wait for it to complete.
3072 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3073 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
3074
3075 static const struct TestConfig {
3076 bool hasSynthesizedPtrRecord;
3077 int flag;
3078 std::string addr;
3079 std::string host;
3080
3081 std::string asParameters() const {
3082 return StringPrintf("hasSynthesizedPtrRecord=%d, flag=%d, addr=%s, host=%s",
3083 hasSynthesizedPtrRecord, flag, addr.c_str(), host.c_str());
3084 }
3085 } testConfigs[]{
3086 {false, NI_NAMEREQD, "64:ff9b::102:304", "v4only.example.com"},
3087 {false, NI_NUMERICHOST, "64:ff9b::102:304", "64:ff9b::102:304"},
3088 {false, 0, "64:ff9b::102:304", "v4only.example.com"},
3089 {true, NI_NAMEREQD, "64:ff9b::506:708", "v6synthesis.example.com"},
3090 {true, NI_NUMERICHOST, "64:ff9b::506:708", "64:ff9b::506:708"},
3091 {true, 0, "64:ff9b::506:708", "v6synthesis.example.com"}
3092 };
3093
3094 // hasSynthesizedPtrRecord = false
3095 // Synthesized PTR record doesn't exist on DNS server
3096 // Reverse IPv6 DNS64 query while DNS server doesn't have an answer for synthesized address.
3097 // After querying synthesized address failed, expect that prefix is removed from IPv6
3098 // synthesized address and do reverse IPv4 query instead.
3099 //
3100 // hasSynthesizedPtrRecord = true
3101 // Synthesized PTR record exists on DNS server
3102 // Reverse IPv6 DNS64 query while DNS server has an answer for synthesized address.
3103 // Expect to just pass through synthesized address for DNS queries.
3104 for (const auto& config : testConfigs) {
3105 SCOPED_TRACE(config.asParameters());
3106
3107 char host[NI_MAXHOST];
3108 struct sockaddr_in6 sin6;
3109 memset(&sin6, 0, sizeof(sin6));
3110 sin6.sin6_family = AF_INET6;
3111 inet_pton(AF_INET6, config.addr.c_str(), &sin6.sin6_addr);
3112 int rv = getnameinfo((const struct sockaddr*) &sin6, sizeof(sin6), host, sizeof(host),
3113 nullptr, 0, config.flag);
3114 ASSERT_EQ(0, rv);
3115 if (config.flag == NI_NAMEREQD) {
3116 if (config.hasSynthesizedPtrRecord) {
3117 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_synthesis));
3118 } else {
3119 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_nomapping)); // PTR record not exist.
3120 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4)); // PTR record exist.
3121 }
3122 }
3123 std::string result_str = host;
3124 EXPECT_EQ(result_str, config.host);
3125 dns.clearQueries();
3126 }
3127 }
3128
TEST_F(ResolverTest,GetNameInfo_ReverseDns64QueryFromHostFile)3129 TEST_F(ResolverTest, GetNameInfo_ReverseDns64QueryFromHostFile) {
3130 constexpr char dns64_name[] = "ipv4only.arpa.";
3131 constexpr char host_name[] = "localhost";
3132 // The address is synthesized by prefix64:localhost.
3133 constexpr char host_addr[] = "64:ff9b::7f00:1";
3134 constexpr char listen_addr[] = "::1";
3135
3136 test::DNSResponder dns(listen_addr);
3137 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
3138 const std::vector<std::string> servers = {listen_addr};
3139 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3140
3141 // Start NAT64 prefix discovery and wait for it to complete.
3142 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3143 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
3144
3145 // Using synthesized "localhost" address to be a trick for resolving host name
3146 // from host file /etc/hosts and "localhost" is the only name in /etc/hosts. Note that this is
3147 // not realistic: the code never synthesizes AAAA records for addresses in 127.0.0.0/8.
3148 char host[NI_MAXHOST];
3149 struct sockaddr_in6 sin6 = {.sin6_family = AF_INET6};
3150 inet_pton(AF_INET6, host_addr, &sin6.sin6_addr);
3151 int rv = getnameinfo((const struct sockaddr*) &sin6, sizeof(sin6), host, sizeof(host), nullptr,
3152 0, NI_NAMEREQD);
3153 ASSERT_EQ(0, rv);
3154 // Expect no DNS queries; localhost is resolved via /etc/hosts.
3155 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
3156
3157 std::string result_str = host;
3158 EXPECT_EQ(result_str, host_name);
3159 }
3160
TEST_F(ResolverTest,GetHostByName2_Dns64Synthesize)3161 TEST_F(ResolverTest, GetHostByName2_Dns64Synthesize) {
3162 constexpr char listen_addr[] = "::1";
3163 constexpr char dns64_name[] = "ipv4only.arpa.";
3164 constexpr char host_name[] = "ipv4only.example.com.";
3165 const std::vector<DnsRecord> records = {
3166 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3167 {host_name, ns_type::ns_t_a, "1.2.3.4"},
3168 };
3169
3170 test::DNSResponder dns(listen_addr);
3171 StartDns(dns, records);
3172 const std::vector<std::string> servers = {listen_addr};
3173 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3174
3175 // Start NAT64 prefix discovery and wait for it to complete.
3176 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3177 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
3178
3179 // Query an IPv4-only hostname. Expect that gets a synthesized address.
3180 struct hostent* result = gethostbyname2("ipv4only", AF_INET6);
3181 ASSERT_TRUE(result != nullptr);
3182 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3183 std::string result_str = ToString(result);
3184 EXPECT_EQ(result_str, "64:ff9b::102:304");
3185 }
3186
TEST_F(ResolverTest,GetHostByName2_DnsQueryWithHavingNat64Prefix)3187 TEST_F(ResolverTest, GetHostByName2_DnsQueryWithHavingNat64Prefix) {
3188 constexpr char dns64_name[] = "ipv4only.arpa.";
3189 constexpr char host_name[] = "v4v6.example.com.";
3190 constexpr char listen_addr[] = "::1";
3191 const std::vector<DnsRecord> records = {
3192 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3193 {host_name, ns_type::ns_t_a, "1.2.3.4"},
3194 {host_name, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
3195 };
3196
3197 test::DNSResponder dns(listen_addr);
3198 StartDns(dns, records);
3199 const std::vector<std::string> servers = {listen_addr};
3200 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3201
3202 // Start NAT64 prefix discovery and wait for it to complete.
3203 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3204 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
3205
3206 // IPv4 DNS query. Prefix should have no effect on it.
3207 struct hostent* result = gethostbyname2("v4v6", AF_INET);
3208 ASSERT_TRUE(result != nullptr);
3209 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3210 std::string result_str = ToString(result);
3211 EXPECT_EQ(result_str, "1.2.3.4");
3212 dns.clearQueries();
3213
3214 // IPv6 DNS query. Prefix should have no effect on it.
3215 result = gethostbyname2("v4v6", AF_INET6);
3216 ASSERT_TRUE(result != nullptr);
3217 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3218 result_str = ToString(result);
3219 EXPECT_EQ(result_str, "2001:db8::102:304");
3220 }
3221
TEST_F(ResolverTest,GetHostByName2_Dns64QuerySpecialUseIPv4Addresses)3222 TEST_F(ResolverTest, GetHostByName2_Dns64QuerySpecialUseIPv4Addresses) {
3223 constexpr char THIS_NETWORK[] = "this_network";
3224 constexpr char LOOPBACK[] = "loopback";
3225 constexpr char LINK_LOCAL[] = "link_local";
3226 constexpr char MULTICAST[] = "multicast";
3227 constexpr char LIMITED_BROADCAST[] = "limited_broadcast";
3228
3229 constexpr char ADDR_THIS_NETWORK[] = "0.0.0.1";
3230 constexpr char ADDR_LOOPBACK[] = "127.0.0.1";
3231 constexpr char ADDR_LINK_LOCAL[] = "169.254.0.1";
3232 constexpr char ADDR_MULTICAST[] = "224.0.0.1";
3233 constexpr char ADDR_LIMITED_BROADCAST[] = "255.255.255.255";
3234
3235 constexpr char listen_addr[] = "::1";
3236 constexpr char dns64_name[] = "ipv4only.arpa.";
3237
3238 test::DNSResponder dns(listen_addr);
3239 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
3240 const std::vector<std::string> servers = {listen_addr};
3241 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3242
3243 // Start NAT64 prefix discovery and wait for it to complete.
3244 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3245 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
3246
3247 static const struct TestConfig {
3248 std::string name;
3249 std::string addr;
3250
3251 std::string asHostName() const {
3252 return StringPrintf("%s.example.com.",
3253 name.c_str());
3254 }
3255 } testConfigs[]{
3256 {THIS_NETWORK, ADDR_THIS_NETWORK},
3257 {LOOPBACK, ADDR_LOOPBACK},
3258 {LINK_LOCAL, ADDR_LINK_LOCAL},
3259 {MULTICAST, ADDR_MULTICAST},
3260 {LIMITED_BROADCAST, ADDR_LIMITED_BROADCAST}
3261 };
3262
3263 for (const auto& config : testConfigs) {
3264 const std::string testHostName = config.asHostName();
3265 SCOPED_TRACE(testHostName);
3266
3267 const char* host_name = testHostName.c_str();
3268 dns.addMapping(host_name, ns_type::ns_t_a, config.addr.c_str());
3269
3270 struct hostent* result = gethostbyname2(config.name.c_str(), AF_INET6);
3271 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3272
3273 // In AF_INET6 case, don't synthesize special use IPv4 address.
3274 // Expect to have no answer
3275 EXPECT_EQ(nullptr, result);
3276
3277 dns.clearQueries();
3278 }
3279 }
3280
TEST_F(ResolverTest,PrefixDiscoveryBypassTls)3281 TEST_F(ResolverTest, PrefixDiscoveryBypassTls) {
3282 constexpr char listen_addr[] = "::1";
3283 constexpr char cleartext_port[] = "53";
3284 constexpr char tls_port[] = "853";
3285 constexpr char dns64_name[] = "ipv4only.arpa.";
3286 const std::vector<std::string> servers = {listen_addr};
3287
3288 test::DNSResponder dns(listen_addr);
3289 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
3290 test::DnsTlsFrontend tls(listen_addr, tls_port, listen_addr, cleartext_port);
3291 ASSERT_TRUE(tls.startServer());
3292
3293 // Setup OPPORTUNISTIC mode and wait for the validation complete.
3294 ASSERT_TRUE(
3295 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
3296 EXPECT_TRUE(tls.waitForQueries(1, 5000));
3297 tls.clearQueries();
3298
3299 // Start NAT64 prefix discovery and wait for it complete.
3300 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3301 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
3302
3303 // Verify it bypassed TLS even though there's a TLS server available.
3304 EXPECT_EQ(0, tls.queries());
3305 EXPECT_EQ(1U, GetNumQueries(dns, dns64_name));
3306
3307 // Restart the testing network to reset the cache.
3308 mDnsClient.TearDown();
3309 mDnsClient.SetUp();
3310 dns.clearQueries();
3311
3312 // Setup STRICT mode and wait for the validation complete.
3313 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "",
3314 {base64Encode(tls.fingerprint())}));
3315 EXPECT_TRUE(tls.waitForQueries(1, 5000));
3316 tls.clearQueries();
3317
3318 // Start NAT64 prefix discovery and wait for it to complete.
3319 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
3320 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
3321
3322 // Verify it bypassed TLS despite STRICT mode.
3323 EXPECT_EQ(0, tls.queries());
3324 EXPECT_EQ(1U, GetNumQueries(dns, dns64_name));
3325 }
3326
3327 namespace {
3328
3329 class ScopedSetNetworkForProcess {
3330 public:
ScopedSetNetworkForProcess(unsigned netId)3331 explicit ScopedSetNetworkForProcess(unsigned netId) {
3332 mStoredNetId = getNetworkForProcess();
3333 if (netId == mStoredNetId) return;
3334 EXPECT_EQ(0, setNetworkForProcess(netId));
3335 }
~ScopedSetNetworkForProcess()3336 ~ScopedSetNetworkForProcess() { EXPECT_EQ(0, setNetworkForProcess(mStoredNetId)); }
3337
3338 private:
3339 unsigned mStoredNetId;
3340 };
3341
3342 class ScopedSetNetworkForResolv {
3343 public:
ScopedSetNetworkForResolv(unsigned netId)3344 explicit ScopedSetNetworkForResolv(unsigned netId) { EXPECT_EQ(0, setNetworkForResolv(netId)); }
~ScopedSetNetworkForResolv()3345 ~ScopedSetNetworkForResolv() { EXPECT_EQ(0, setNetworkForResolv(NETID_UNSET)); }
3346 };
3347
sendCommand(int fd,const std::string & cmd)3348 void sendCommand(int fd, const std::string& cmd) {
3349 ssize_t rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size() + 1));
3350 EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size() + 1));
3351 }
3352
readBE32(int fd)3353 int32_t readBE32(int fd) {
3354 int32_t tmp;
3355 int n = TEMP_FAILURE_RETRY(read(fd, &tmp, sizeof(tmp)));
3356 EXPECT_TRUE(n > 0);
3357 return ntohl(tmp);
3358 }
3359
readResponseCode(int fd)3360 int readResponseCode(int fd) {
3361 char buf[4];
3362 int n = TEMP_FAILURE_RETRY(read(fd, &buf, sizeof(buf)));
3363 EXPECT_TRUE(n > 0);
3364 // The format of response code is that 4 bytes for the code & null.
3365 buf[3] = '\0';
3366 int result;
3367 EXPECT_TRUE(ParseInt(buf, &result));
3368 return result;
3369 }
3370
checkAndClearUseLocalNameserversFlag(unsigned * netid)3371 bool checkAndClearUseLocalNameserversFlag(unsigned* netid) {
3372 if (netid == nullptr || ((*netid) & NETID_USE_LOCAL_NAMESERVERS) == 0) {
3373 return false;
3374 }
3375 *netid = (*netid) & ~NETID_USE_LOCAL_NAMESERVERS;
3376 return true;
3377 }
3378
makeUidRangeParcel(int start,int stop)3379 android::net::UidRangeParcel makeUidRangeParcel(int start, int stop) {
3380 android::net::UidRangeParcel res;
3381 res.start = start;
3382 res.stop = stop;
3383
3384 return res;
3385 }
3386
expectNetIdWithLocalNameserversFlag(unsigned netId)3387 void expectNetIdWithLocalNameserversFlag(unsigned netId) {
3388 unsigned dnsNetId = 0;
3389 EXPECT_EQ(0, getNetworkForDns(&dnsNetId));
3390 EXPECT_TRUE(checkAndClearUseLocalNameserversFlag(&dnsNetId));
3391 EXPECT_EQ(netId, static_cast<unsigned>(dnsNetId));
3392 }
3393
expectDnsNetIdEquals(unsigned netId)3394 void expectDnsNetIdEquals(unsigned netId) {
3395 unsigned dnsNetId = 0;
3396 EXPECT_EQ(0, getNetworkForDns(&dnsNetId));
3397 EXPECT_EQ(netId, static_cast<unsigned>(dnsNetId));
3398 }
3399
expectDnsNetIdIsDefaultNetwork(android::net::INetd * netdService)3400 void expectDnsNetIdIsDefaultNetwork(android::net::INetd* netdService) {
3401 int currentNetid;
3402 EXPECT_TRUE(netdService->networkGetDefault(¤tNetid).isOk());
3403 expectDnsNetIdEquals(currentNetid);
3404 }
3405
expectDnsNetIdWithVpn(android::net::INetd * netdService,unsigned vpnNetId,unsigned expectedNetId)3406 void expectDnsNetIdWithVpn(android::net::INetd* netdService, unsigned vpnNetId,
3407 unsigned expectedNetId) {
3408 EXPECT_TRUE(netdService->networkCreateVpn(vpnNetId, false /* secure */).isOk());
3409 uid_t uid = getuid();
3410 // Add uid to VPN
3411 EXPECT_TRUE(netdService->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3412 expectDnsNetIdEquals(expectedNetId);
3413 EXPECT_TRUE(netdService->networkDestroy(vpnNetId).isOk());
3414 }
3415
3416 } // namespace
3417
TEST_F(ResolverTest,getDnsNetId)3418 TEST_F(ResolverTest, getDnsNetId) {
3419 // We've called setNetworkForProcess in SetupOemNetwork, so reset to default first.
3420 setNetworkForProcess(NETID_UNSET);
3421
3422 expectDnsNetIdIsDefaultNetwork(mDnsClient.netdService());
3423 expectDnsNetIdWithVpn(mDnsClient.netdService(), TEST_VPN_NETID, TEST_VPN_NETID);
3424
3425 // Test with setNetworkForProcess
3426 {
3427 ScopedSetNetworkForProcess scopedSetNetworkForProcess(TEST_NETID);
3428 expectDnsNetIdEquals(TEST_NETID);
3429 }
3430
3431 // Test with setNetworkForProcess with NETID_USE_LOCAL_NAMESERVERS
3432 {
3433 ScopedSetNetworkForProcess scopedSetNetworkForProcess(TEST_NETID |
3434 NETID_USE_LOCAL_NAMESERVERS);
3435 expectNetIdWithLocalNameserversFlag(TEST_NETID);
3436 }
3437
3438 // Test with setNetworkForResolv
3439 {
3440 ScopedSetNetworkForResolv scopedSetNetworkForResolv(TEST_NETID);
3441 expectDnsNetIdEquals(TEST_NETID);
3442 }
3443
3444 // Test with setNetworkForResolv with NETID_USE_LOCAL_NAMESERVERS
3445 {
3446 ScopedSetNetworkForResolv scopedSetNetworkForResolv(TEST_NETID |
3447 NETID_USE_LOCAL_NAMESERVERS);
3448 expectNetIdWithLocalNameserversFlag(TEST_NETID);
3449 }
3450
3451 // Test with setNetworkForResolv under bypassable vpn
3452 {
3453 ScopedSetNetworkForResolv scopedSetNetworkForResolv(TEST_NETID);
3454 expectDnsNetIdWithVpn(mDnsClient.netdService(), TEST_VPN_NETID, TEST_NETID);
3455 }
3456
3457 // Create socket connected to DnsProxyListener
3458 int fd = dns_open_proxy();
3459 EXPECT_TRUE(fd > 0);
3460 unique_fd ufd(fd);
3461
3462 // Test command with wrong netId
3463 sendCommand(fd, "getdnsnetid abc");
3464 EXPECT_EQ(ResponseCode::DnsProxyQueryResult, readResponseCode(fd));
3465 EXPECT_EQ(-EINVAL, readBE32(fd));
3466
3467 // Test unsupported command
3468 sendCommand(fd, "getdnsnetidNotSupported");
3469 // Keep in sync with FrameworkListener.cpp (500, "Command not recognized")
3470 EXPECT_EQ(500, readResponseCode(fd));
3471 }
3472