blob: 0cce121609348262472665f681869853d91e0708 [file] [log] [blame]
Bernie Innocenti443489e2018-08-10 14:27:23 +09001/*
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
Bernie Innocentic165ce82018-10-16 23:35:28 +090018#define LOG_TAG "netd_test"
19
Bernie Innocenti443489e2018-08-10 14:27:23 +090020#include <arpa/inet.h>
Luke Huangc68f1b92018-11-21 20:13:38 +080021#include <arpa/nameser.h>
Bernie Innocenti443489e2018-08-10 14:27:23 +090022#include <netdb.h>
Luke Huangc68f1b92018-11-21 20:13:38 +080023#include <netinet/in.h>
24#include <poll.h> /* poll */
25#include <resolv.h>
Bernie Innocenti443489e2018-08-10 14:27:23 +090026#include <stdarg.h>
27#include <stdio.h>
28#include <stdlib.h>
Luke Huangc68f1b92018-11-21 20:13:38 +080029#include <sys/socket.h>
30#include <sys/un.h>
Bernie Innocenti443489e2018-08-10 14:27:23 +090031#include <unistd.h>
32
33#include <algorithm>
34#include <chrono>
35#include <iterator>
36#include <numeric>
37#include <thread>
38
Bernie Innocenti443489e2018-08-10 14:27:23 +090039#include <android-base/stringprintf.h>
Luke Huang952d0942018-12-26 16:53:03 +080040#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocenti0298c682018-10-02 23:18:11 +090041#include <cutils/sockets.h>
Bernie Innocentic165ce82018-10-16 23:35:28 +090042#include <gtest/gtest.h>
Bernie Innocenti443489e2018-08-10 14:27:23 +090043#include <openssl/base64.h>
Bernie Innocentic165ce82018-10-16 23:35:28 +090044#include <private/android_filesystem_config.h>
45#include <utils/Log.h>
Bernie Innocenti443489e2018-08-10 14:27:23 +090046
Bernie Innocenti443489e2018-08-10 14:27:23 +090047#include "NetdClient.h"
Bernie Innocenti189eb502018-10-01 23:10:18 +090048#include "netid_client.h" // NETID_UNSET
Bernie Innocentic165ce82018-10-16 23:35:28 +090049#include "netd_resolv/params.h" // MAX_NS
Bernie Innocenti443489e2018-08-10 14:27:23 +090050
Ken Chenc68c2de2018-11-13 21:51:13 +080051#include "dns_responder/dns_responder.h"
52#include "dns_responder/dns_responder_client.h"
53#include "dns_responder/dns_tls_frontend.h"
Bernie Innocenti9bf749f2018-08-30 08:37:22 +090054
55#include "NetdConstants.h"
Bernie Innocenti443489e2018-08-10 14:27:23 +090056#include "ResolverStats.h"
57
58#include "android/net/INetd.h"
Bernie Innocenti443489e2018-08-10 14:27:23 +090059#include "binder/IServiceManager.h"
60#include "netdutils/SocketOption.h"
61
Bernie Innocentic165ce82018-10-16 23:35:28 +090062// TODO: make this dynamic and stop depending on implementation details.
Luke Huangc68f1b92018-11-21 20:13:38 +080063constexpr int TEST_NETID = 30;
64constexpr int MAXPACKET = (8 * 1024);
Bernie Innocentic165ce82018-10-16 23:35:28 +090065
66// Semi-public Bionic hook used by the NDK (frameworks/base/native/android/net.c)
67// Tested here for convenience.
68extern "C" int android_getaddrinfofornet(const char* hostname, const char* servname,
69 const addrinfo* hints, unsigned netid, unsigned mark,
70 struct addrinfo** result);
71
Bernie Innocenti443489e2018-08-10 14:27:23 +090072using android::base::StringPrintf;
73using android::net::ResolverStats;
Bernie Innocenti443489e2018-08-10 14:27:23 +090074using android::netdutils::enableSockopt;
75
Bernie Innocenti9bf749f2018-08-30 08:37:22 +090076// TODO: move into libnetdutils?
77namespace {
78ScopedAddrinfo safe_getaddrinfo(const char* node, const char* service,
79 const struct addrinfo* hints) {
80 addrinfo* result = nullptr;
81 if (getaddrinfo(node, service, hints, &result) != 0) {
82 result = nullptr; // Should already be the case, but...
83 }
84 return ScopedAddrinfo(result);
85}
86} // namespace
87
Bernie Innocenti443489e2018-08-10 14:27:23 +090088// Emulates the behavior of UnorderedElementsAreArray, which currently cannot be used.
89// TODO: Use UnorderedElementsAreArray, which depends on being able to compile libgmock_host,
90// if that is not possible, improve this hacky algorithm, which is O(n**2)
91template <class A, class B>
92bool UnorderedCompareArray(const A& a, const B& b) {
93 if (a.size() != b.size()) return false;
94 for (const auto& a_elem : a) {
95 size_t a_count = 0;
96 for (const auto& a_elem2 : a) {
97 if (a_elem == a_elem2) {
98 ++a_count;
99 }
100 }
101 size_t b_count = 0;
102 for (const auto& b_elem : b) {
103 if (a_elem == b_elem) ++b_count;
104 }
105 if (a_count != b_count) return false;
106 }
107 return true;
108}
109
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900110class ResolverTest : public ::testing::Test {
Bernie Innocenti0298c682018-10-02 23:18:11 +0900111 protected:
Xiao Ma7c75f452018-12-11 17:56:32 +0900112 struct DnsRecord {
113 std::string host_name; // host name
114 ns_type type; // record type
115 std::string addr; // ipv4/v6 address
116 };
117
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900118 void SetUp() { mDnsClient.SetUp(); }
119 void TearDown() { mDnsClient.TearDown(); }
Bernie Innocenti443489e2018-08-10 14:27:23 +0900120
121 bool GetResolverInfo(std::vector<std::string>* servers, std::vector<std::string>* domains,
Mike Yuda77e8e2018-11-26 13:26:21 +0900122 std::vector<std::string>* tlsServers, __res_params* params,
123 std::vector<ResolverStats>* stats) {
Bernie Innocenti443489e2018-08-10 14:27:23 +0900124 using android::net::INetd;
125 std::vector<int32_t> params32;
126 std::vector<int32_t> stats32;
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900127 auto rv = mDnsClient.netdService()->getResolverInfo(TEST_NETID, servers, domains,
128 tlsServers, &params32, &stats32);
Bernie Innocenti45238a12018-12-04 14:57:48 +0900129 if (!rv.isOk() || params32.size() != static_cast<size_t>(INetd::RESOLVER_PARAMS_COUNT)) {
Bernie Innocenti443489e2018-08-10 14:27:23 +0900130 return false;
131 }
132 *params = __res_params {
133 .sample_validity = static_cast<uint16_t>(
134 params32[INetd::RESOLVER_PARAMS_SAMPLE_VALIDITY]),
135 .success_threshold = static_cast<uint8_t>(
136 params32[INetd::RESOLVER_PARAMS_SUCCESS_THRESHOLD]),
137 .min_samples = static_cast<uint8_t>(
138 params32[INetd::RESOLVER_PARAMS_MIN_SAMPLES]),
139 .max_samples = static_cast<uint8_t>(
140 params32[INetd::RESOLVER_PARAMS_MAX_SAMPLES]),
141 .base_timeout_msec = params32[INetd::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
142 };
143 return ResolverStats::decodeAll(stats32, stats);
144 }
145
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900146 static std::string ToString(const hostent* he) {
Bernie Innocenti443489e2018-08-10 14:27:23 +0900147 if (he == nullptr) return "<null>";
148 char buffer[INET6_ADDRSTRLEN];
149 if (!inet_ntop(he->h_addrtype, he->h_addr_list[0], buffer, sizeof(buffer))) {
150 return "<invalid>";
151 }
152 return buffer;
153 }
154
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900155 static std::string ToString(const addrinfo* ai) {
Bernie Innocenti443489e2018-08-10 14:27:23 +0900156 if (!ai)
157 return "<null>";
158 for (const auto* aip = ai ; aip != nullptr ; aip = aip->ai_next) {
159 char host[NI_MAXHOST];
160 int rv = getnameinfo(aip->ai_addr, aip->ai_addrlen, host, sizeof(host), nullptr, 0,
161 NI_NUMERICHOST);
162 if (rv != 0)
163 return gai_strerror(rv);
164 return host;
165 }
166 return "<invalid>";
167 }
168
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900169 static std::string ToString(const ScopedAddrinfo& ai) { return ToString(ai.get()); }
170
nuccachenf52f7a52018-07-17 18:07:23 +0800171 static std::vector<std::string> ToStrings(const addrinfo* ai) {
172 std::vector<std::string> hosts;
173 if (!ai) {
174 hosts.push_back("<null>");
175 return hosts;
176 }
177 for (const auto* aip = ai; aip != nullptr; aip = aip->ai_next) {
178 char host[NI_MAXHOST];
179 int rv = getnameinfo(aip->ai_addr, aip->ai_addrlen, host, sizeof(host), nullptr, 0,
180 NI_NUMERICHOST);
181 if (rv != 0) {
182 hosts.clear();
183 hosts.push_back(gai_strerror(rv));
184 return hosts;
185 } else {
186 hosts.push_back(host);
187 }
188 }
189 if (hosts.empty()) hosts.push_back("<invalid>");
190 return hosts;
191 }
192
193 static std::vector<std::string> ToStrings(const ScopedAddrinfo& ai) {
194 return ToStrings(ai.get());
195 }
196
Bernie Innocenti443489e2018-08-10 14:27:23 +0900197 size_t GetNumQueries(const test::DNSResponder& dns, const char* name) const {
198 auto queries = dns.queries();
199 size_t found = 0;
200 for (const auto& p : queries) {
201 if (p.first == name) {
202 ++found;
203 }
204 }
205 return found;
206 }
207
208 size_t GetNumQueriesForType(const test::DNSResponder& dns, ns_type type,
Bernie Innocenti0298c682018-10-02 23:18:11 +0900209 const char* name) const {
Bernie Innocenti443489e2018-08-10 14:27:23 +0900210 auto queries = dns.queries();
211 size_t found = 0;
212 for (const auto& p : queries) {
213 if (p.second == type && p.first == name) {
214 ++found;
215 }
216 }
217 return found;
218 }
219
nuccachenf52f7a52018-07-17 18:07:23 +0800220 bool WaitForPrefix64Detected(int netId, int timeoutMs) {
221 constexpr int intervalMs = 2;
222 const int limit = timeoutMs / intervalMs;
223 for (int count = 0; count <= limit; ++count) {
224 std::string prefix;
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900225 auto rv = mDnsClient.netdService()->getPrefix64(netId, &prefix);
nuccachenf52f7a52018-07-17 18:07:23 +0800226 if (rv.isOk()) {
227 return true;
228 }
229 usleep(intervalMs * 1000);
230 }
231 return false;
232 }
233
Bernie Innocenti443489e2018-08-10 14:27:23 +0900234 void RunGetAddrInfoStressTest_Binder(unsigned num_hosts, unsigned num_threads,
235 unsigned num_queries) {
236 std::vector<std::string> domains = { "example.com" };
237 std::vector<std::unique_ptr<test::DNSResponder>> dns;
238 std::vector<std::string> servers;
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900239 std::vector<DnsResponderClient::DnsResponderClient::Mapping> mappings;
240 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(num_hosts, domains, &mappings));
241 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(MAXNS, mappings, &dns, &servers));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900242
Xiao Ma7c75f452018-12-11 17:56:32 +0900243 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains, kDefaultParams));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900244
245 auto t0 = std::chrono::steady_clock::now();
246 std::vector<std::thread> threads(num_threads);
247 for (std::thread& thread : threads) {
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900248 thread = std::thread([&mappings, num_queries]() {
Bernie Innocenti443489e2018-08-10 14:27:23 +0900249 for (unsigned i = 0 ; i < num_queries ; ++i) {
250 uint32_t ofs = arc4random_uniform(mappings.size());
251 auto& mapping = mappings[ofs];
252 addrinfo* result = nullptr;
253 int rv = getaddrinfo(mapping.host.c_str(), nullptr, nullptr, &result);
254 EXPECT_EQ(0, rv) << "error [" << rv << "] " << gai_strerror(rv);
255 if (rv == 0) {
256 std::string result_str = ToString(result);
257 EXPECT_TRUE(result_str == mapping.ip4 || result_str == mapping.ip6)
258 << "result='" << result_str << "', ip4='" << mapping.ip4
259 << "', ip6='" << mapping.ip6;
260 }
261 if (result) {
262 freeaddrinfo(result);
263 result = nullptr;
264 }
265 }
266 });
267 }
268
269 for (std::thread& thread : threads) {
270 thread.join();
271 }
272 auto t1 = std::chrono::steady_clock::now();
273 ALOGI("%u hosts, %u threads, %u queries, %Es", num_hosts, num_threads, num_queries,
274 std::chrono::duration<double>(t1 - t0).count());
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900275 ASSERT_NO_FATAL_FAILURE(mDnsClient.ShutdownDNSServers(&dns));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900276 }
277
Xiao Ma7c75f452018-12-11 17:56:32 +0900278 void StartDns(test::DNSResponder& dns, const std::vector<DnsRecord>& records) {
279 for (const auto& r : records) {
280 dns.addMapping(r.host_name, r.type, r.addr);
281 }
282
283 ASSERT_TRUE(dns.startServer());
284 dns.clearQueries();
285 }
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900286
287 DnsResponderClient mDnsClient;
Xiao Ma7c75f452018-12-11 17:56:32 +0900288
289 static constexpr char kLocalHost[] = "localhost";
290 static constexpr char kLocalHostAddr[] = "127.0.0.1";
291 static constexpr char kIp6LocalHost[] = "ip6-localhost";
292 static constexpr char kIp6LocalHostAddr[] = "::1";
293 static constexpr char kHelloExampleCom[] = "hello.example.com.";
Bernie Innocenti443489e2018-08-10 14:27:23 +0900294};
295
296TEST_F(ResolverTest, GetHostByName) {
Xiao Ma7c75f452018-12-11 17:56:32 +0900297 constexpr char nonexistent_host_name[] = "nonexistent.example.com.";
298
299 test::DNSResponder dns;
300 StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.3"}});
301 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Bernie Innocenti443489e2018-08-10 14:27:23 +0900302
303 const hostent* result;
Bernie Innocenti443489e2018-08-10 14:27:23 +0900304 result = gethostbyname("nonexistent");
305 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, nonexistent_host_name));
306 ASSERT_TRUE(result == nullptr);
307 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
308
309 dns.clearQueries();
310 result = gethostbyname("hello");
Xiao Ma7c75f452018-12-11 17:56:32 +0900311 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, kHelloExampleCom));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900312 ASSERT_FALSE(result == nullptr);
313 ASSERT_EQ(4, result->h_length);
314 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
315 EXPECT_EQ("1.2.3.3", ToString(result));
316 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
Bernie Innocenti443489e2018-08-10 14:27:23 +0900317}
318
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900319TEST_F(ResolverTest, GetHostByName_localhost) {
Bernie Innocenti6118bf82018-09-14 15:21:19 +0900320 constexpr char name_camelcase[] = "LocalHost";
Bernie Innocenti0298c682018-10-02 23:18:11 +0900321 constexpr char name_ip6_dot[] = "ip6-localhost.";
322 constexpr char name_ip6_fqdn[] = "ip6-localhost.example.com.";
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900323
Bernie Innocenti974233e2018-09-04 20:35:34 +0900324 // Add a dummy nameserver which shouldn't receive any queries
Xiao Ma7c75f452018-12-11 17:56:32 +0900325 test::DNSResponder dns;
326 StartDns(dns, {});
327 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Bernie Innocenti6118bf82018-09-14 15:21:19 +0900328
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900329 // Expect no DNS queries; localhost is resolved via /etc/hosts
Xiao Ma7c75f452018-12-11 17:56:32 +0900330 const hostent* result = gethostbyname(kLocalHost);
Bernie Innocenti0298c682018-10-02 23:18:11 +0900331 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900332 ASSERT_FALSE(result == nullptr);
333 ASSERT_EQ(4, result->h_length);
334 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
Xiao Ma7c75f452018-12-11 17:56:32 +0900335 EXPECT_EQ(kLocalHostAddr, ToString(result));
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900336 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
337
Bernie Innocenti6118bf82018-09-14 15:21:19 +0900338 // Ensure the hosts file resolver ignores case of hostnames
339 result = gethostbyname(name_camelcase);
Bernie Innocenti0298c682018-10-02 23:18:11 +0900340 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
Bernie Innocenti6118bf82018-09-14 15:21:19 +0900341 ASSERT_FALSE(result == nullptr);
342 ASSERT_EQ(4, result->h_length);
343 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
Xiao Ma7c75f452018-12-11 17:56:32 +0900344 EXPECT_EQ(kLocalHostAddr, ToString(result));
Bernie Innocenti6118bf82018-09-14 15:21:19 +0900345 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
346
347 // The hosts file also contains ip6-localhost, but gethostbyname() won't
Bernie Innocenti0298c682018-10-02 23:18:11 +0900348 // return it unless the RES_USE_INET6 option is set. This would be easy to
349 // change, but there's no point in changing the legacy behavior; new code
350 // should be calling getaddrinfo() anyway.
351 // So we check the legacy behavior, which results in amusing A-record
352 // lookups for ip6-localhost, with and without search domains appended.
353 dns.clearQueries();
Xiao Ma7c75f452018-12-11 17:56:32 +0900354 result = gethostbyname(kIp6LocalHost);
Sehee Park8659b8d2018-11-16 10:53:16 +0900355 EXPECT_EQ(2U, dns.queries().size()) << dns.dumpQueries();
356 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, name_ip6_dot)) << dns.dumpQueries();
357 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, name_ip6_fqdn)) << dns.dumpQueries();
Bernie Innocenti6118bf82018-09-14 15:21:19 +0900358 ASSERT_TRUE(result == nullptr);
359
Bernie Innocenti0298c682018-10-02 23:18:11 +0900360 // Finally, use gethostbyname2() to resolve ip6-localhost to ::1 from
361 // the hosts file.
362 dns.clearQueries();
Xiao Ma7c75f452018-12-11 17:56:32 +0900363 result = gethostbyname2(kIp6LocalHost, AF_INET6);
Bernie Innocenti0298c682018-10-02 23:18:11 +0900364 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
Bernie Innocenti6118bf82018-09-14 15:21:19 +0900365 ASSERT_FALSE(result == nullptr);
366 ASSERT_EQ(16, result->h_length);
367 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
Xiao Ma7c75f452018-12-11 17:56:32 +0900368 EXPECT_EQ(kIp6LocalHostAddr, ToString(result));
Bernie Innocenti6118bf82018-09-14 15:21:19 +0900369 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900370}
371
Bernie Innocentic1545232018-10-04 17:12:24 +0900372TEST_F(ResolverTest, GetHostByName_numeric) {
373 // Add a dummy nameserver which shouldn't receive any queries
Xiao Ma7c75f452018-12-11 17:56:32 +0900374 test::DNSResponder dns;
375 StartDns(dns, {});
376 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Bernie Innocentic1545232018-10-04 17:12:24 +0900377
378 // Numeric v4 address: expect no DNS queries
379 constexpr char numeric_v4[] = "192.168.0.1";
Bernie Innocentic1545232018-10-04 17:12:24 +0900380 const hostent* result = gethostbyname(numeric_v4);
Sehee Park8659b8d2018-11-16 10:53:16 +0900381 EXPECT_EQ(0U, dns.queries().size());
Bernie Innocentic1545232018-10-04 17:12:24 +0900382 ASSERT_FALSE(result == nullptr);
383 ASSERT_EQ(4, result->h_length); // v4
384 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
385 EXPECT_EQ(numeric_v4, ToString(result));
386 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
387
388 // gethostbyname() recognizes a v6 address, and fails with no DNS queries
389 constexpr char numeric_v6[] = "2001:db8::42";
390 dns.clearQueries();
391 result = gethostbyname(numeric_v6);
Sehee Park8659b8d2018-11-16 10:53:16 +0900392 EXPECT_EQ(0U, dns.queries().size());
Bernie Innocentic1545232018-10-04 17:12:24 +0900393 EXPECT_TRUE(result == nullptr);
394
395 // Numeric v6 address with gethostbyname2(): succeeds with no DNS queries
396 dns.clearQueries();
397 result = gethostbyname2(numeric_v6, AF_INET6);
Sehee Park8659b8d2018-11-16 10:53:16 +0900398 EXPECT_EQ(0U, dns.queries().size());
Bernie Innocentic1545232018-10-04 17:12:24 +0900399 ASSERT_FALSE(result == nullptr);
400 ASSERT_EQ(16, result->h_length); // v6
401 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
402 EXPECT_EQ(numeric_v6, ToString(result));
403 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
404
405 // Numeric v6 address with scope work with getaddrinfo(),
406 // but gethostbyname2() does not understand them; it issues two dns
407 // queries, then fails. This hardly ever happens, there's no point
408 // in fixing this. This test simply verifies the current (bogus)
409 // behavior to avoid further regressions (like crashes, or leaks).
410 constexpr char numeric_v6_scope[] = "fe80::1%lo";
411 dns.clearQueries();
412 result = gethostbyname2(numeric_v6_scope, AF_INET6);
Sehee Park8659b8d2018-11-16 10:53:16 +0900413 EXPECT_EQ(2U, dns.queries().size()); // OUCH!
Bernie Innocentic1545232018-10-04 17:12:24 +0900414 ASSERT_TRUE(result == nullptr);
Bernie Innocentic1545232018-10-04 17:12:24 +0900415}
416
Bernie Innocenti443489e2018-08-10 14:27:23 +0900417TEST_F(ResolverTest, BinderSerialization) {
418 using android::net::INetd;
419 std::vector<int> params_offsets = {
420 INetd::RESOLVER_PARAMS_SAMPLE_VALIDITY,
421 INetd::RESOLVER_PARAMS_SUCCESS_THRESHOLD,
422 INetd::RESOLVER_PARAMS_MIN_SAMPLES,
423 INetd::RESOLVER_PARAMS_MAX_SAMPLES,
424 INetd::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC,
425 };
Bernie Innocenti45238a12018-12-04 14:57:48 +0900426 const int size = static_cast<int>(params_offsets.size());
Bernie Innocenti443489e2018-08-10 14:27:23 +0900427 EXPECT_EQ(size, INetd::RESOLVER_PARAMS_COUNT);
428 std::sort(params_offsets.begin(), params_offsets.end());
Bernie Innocenti45238a12018-12-04 14:57:48 +0900429 for (int i = 0; i < size; ++i) {
Bernie Innocenti443489e2018-08-10 14:27:23 +0900430 EXPECT_EQ(params_offsets[i], i);
431 }
432}
433
434TEST_F(ResolverTest, GetHostByName_Binder) {
435 using android::net::INetd;
436
437 std::vector<std::string> domains = { "example.com" };
438 std::vector<std::unique_ptr<test::DNSResponder>> dns;
439 std::vector<std::string> servers;
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900440 std::vector<DnsResponderClient::Mapping> mappings;
441 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(1, domains, &mappings));
442 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(4, mappings, &dns, &servers));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900443 ASSERT_EQ(1U, mappings.size());
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900444 const DnsResponderClient::Mapping& mapping = mappings[0];
Bernie Innocenti443489e2018-08-10 14:27:23 +0900445
Xiao Ma7c75f452018-12-11 17:56:32 +0900446 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains, kDefaultParams));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900447
448 const hostent* result = gethostbyname(mapping.host.c_str());
Bernie Innocenti45238a12018-12-04 14:57:48 +0900449 const size_t total_queries =
450 std::accumulate(dns.begin(), dns.end(), 0, [this, &mapping](size_t total, auto& d) {
Bernie Innocenti443489e2018-08-10 14:27:23 +0900451 return total + GetNumQueriesForType(*d, ns_type::ns_t_a, mapping.entry.c_str());
452 });
453
454 EXPECT_LE(1U, total_queries);
455 ASSERT_FALSE(result == nullptr);
456 ASSERT_EQ(4, result->h_length);
457 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
458 EXPECT_EQ(mapping.ip4, ToString(result));
459 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
460
461 std::vector<std::string> res_servers;
462 std::vector<std::string> res_domains;
Mike Yuda77e8e2018-11-26 13:26:21 +0900463 std::vector<std::string> res_tls_servers;
Bernie Innocenti443489e2018-08-10 14:27:23 +0900464 __res_params res_params;
465 std::vector<ResolverStats> res_stats;
Mike Yuda77e8e2018-11-26 13:26:21 +0900466 ASSERT_TRUE(
467 GetResolverInfo(&res_servers, &res_domains, &res_tls_servers, &res_params, &res_stats));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900468 EXPECT_EQ(servers.size(), res_servers.size());
469 EXPECT_EQ(domains.size(), res_domains.size());
Mike Yuda77e8e2018-11-26 13:26:21 +0900470 EXPECT_EQ(0U, res_tls_servers.size());
Xiao Ma7c75f452018-12-11 17:56:32 +0900471 ASSERT_EQ(static_cast<size_t>(INetd::RESOLVER_PARAMS_COUNT), kDefaultParams.size());
472 EXPECT_EQ(kDefaultParams[INetd::RESOLVER_PARAMS_SAMPLE_VALIDITY], res_params.sample_validity);
473 EXPECT_EQ(kDefaultParams[INetd::RESOLVER_PARAMS_SUCCESS_THRESHOLD],
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900474 res_params.success_threshold);
Xiao Ma7c75f452018-12-11 17:56:32 +0900475 EXPECT_EQ(kDefaultParams[INetd::RESOLVER_PARAMS_MIN_SAMPLES], res_params.min_samples);
476 EXPECT_EQ(kDefaultParams[INetd::RESOLVER_PARAMS_MAX_SAMPLES], res_params.max_samples);
477 EXPECT_EQ(kDefaultParams[INetd::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
Bernie Innocenti443489e2018-08-10 14:27:23 +0900478 res_params.base_timeout_msec);
479 EXPECT_EQ(servers.size(), res_stats.size());
480
481 EXPECT_TRUE(UnorderedCompareArray(res_servers, servers));
482 EXPECT_TRUE(UnorderedCompareArray(res_domains, domains));
483
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900484 ASSERT_NO_FATAL_FAILURE(mDnsClient.ShutdownDNSServers(&dns));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900485}
486
487TEST_F(ResolverTest, GetAddrInfo) {
Xiao Ma7c75f452018-12-11 17:56:32 +0900488 constexpr char listen_addr[] = "127.0.0.4";
489 constexpr char listen_addr2[] = "127.0.0.5";
490 constexpr char host_name[] = "howdy.example.com.";
Bernie Innocenti443489e2018-08-10 14:27:23 +0900491
Xiao Ma7c75f452018-12-11 17:56:32 +0900492 const std::vector<DnsRecord> records = {
493 {host_name, ns_type::ns_t_a, "1.2.3.4"},
494 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
495 };
496 test::DNSResponder dns(listen_addr);
497 test::DNSResponder dns2(listen_addr2);
498 StartDns(dns, records);
499 StartDns(dns2, records);
Bernie Innocenti443489e2018-08-10 14:27:23 +0900500
Xiao Ma7c75f452018-12-11 17:56:32 +0900501 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr}));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900502 dns.clearQueries();
503 dns2.clearQueries();
504
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900505 ScopedAddrinfo result = safe_getaddrinfo("howdy", nullptr, nullptr);
506 EXPECT_TRUE(result != nullptr);
Bernie Innocenti443489e2018-08-10 14:27:23 +0900507 size_t found = GetNumQueries(dns, host_name);
508 EXPECT_LE(1U, found);
509 // Could be A or AAAA
510 std::string result_str = ToString(result);
511 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
512 << ", result_str='" << result_str << "'";
Bernie Innocenti443489e2018-08-10 14:27:23 +0900513
514 // Verify that the name is cached.
515 size_t old_found = found;
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900516 result = safe_getaddrinfo("howdy", nullptr, nullptr);
517 EXPECT_TRUE(result != nullptr);
Bernie Innocenti443489e2018-08-10 14:27:23 +0900518 found = GetNumQueries(dns, host_name);
519 EXPECT_LE(1U, found);
520 EXPECT_EQ(old_found, found);
521 result_str = ToString(result);
522 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
523 << result_str;
Bernie Innocenti443489e2018-08-10 14:27:23 +0900524
525 // Change the DNS resolver, ensure that queries are still cached.
Xiao Ma7c75f452018-12-11 17:56:32 +0900526 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr2}));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900527 dns.clearQueries();
528 dns2.clearQueries();
529
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900530 result = safe_getaddrinfo("howdy", nullptr, nullptr);
531 EXPECT_TRUE(result != nullptr);
Bernie Innocenti443489e2018-08-10 14:27:23 +0900532 found = GetNumQueries(dns, host_name);
533 size_t found2 = GetNumQueries(dns2, host_name);
534 EXPECT_EQ(0U, found);
535 EXPECT_LE(0U, found2);
536
537 // Could be A or AAAA
538 result_str = ToString(result);
539 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
540 << ", result_str='" << result_str << "'";
Bernie Innocenti443489e2018-08-10 14:27:23 +0900541}
542
543TEST_F(ResolverTest, GetAddrInfoV4) {
Xiao Ma7c75f452018-12-11 17:56:32 +0900544 test::DNSResponder dns;
545 StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.5"}});
546 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Bernie Innocenti443489e2018-08-10 14:27:23 +0900547
Xiao Ma7c75f452018-12-11 17:56:32 +0900548 const addrinfo hints = {.ai_family = AF_INET};
549 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900550 EXPECT_TRUE(result != nullptr);
Xiao Ma7c75f452018-12-11 17:56:32 +0900551 EXPECT_EQ(1U, GetNumQueries(dns, kHelloExampleCom));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900552 EXPECT_EQ("1.2.3.5", ToString(result));
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900553}
554
555TEST_F(ResolverTest, GetAddrInfo_localhost) {
Bernie Innocenti974233e2018-09-04 20:35:34 +0900556 // Add a dummy nameserver which shouldn't receive any queries
Xiao Ma7c75f452018-12-11 17:56:32 +0900557 test::DNSResponder dns;
558 StartDns(dns, {});
559 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900560
Xiao Ma7c75f452018-12-11 17:56:32 +0900561 ScopedAddrinfo result = safe_getaddrinfo(kLocalHost, nullptr, nullptr);
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900562 EXPECT_TRUE(result != nullptr);
563 // Expect no DNS queries; localhost is resolved via /etc/hosts
Bernie Innocenti0298c682018-10-02 23:18:11 +0900564 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
Xiao Ma7c75f452018-12-11 17:56:32 +0900565 EXPECT_EQ(kLocalHostAddr, ToString(result));
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900566
Xiao Ma7c75f452018-12-11 17:56:32 +0900567 result = safe_getaddrinfo(kIp6LocalHost, nullptr, nullptr);
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900568 EXPECT_TRUE(result != nullptr);
Bernie Innocenti0298c682018-10-02 23:18:11 +0900569 // Expect no DNS queries; ip6-localhost is resolved via /etc/hosts
570 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
Xiao Ma7c75f452018-12-11 17:56:32 +0900571 EXPECT_EQ(kIp6LocalHostAddr, ToString(result));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900572}
573
Bernie Innocenti443489e2018-08-10 14:27:23 +0900574TEST_F(ResolverTest, MultidomainResolution) {
Xiao Ma7c75f452018-12-11 17:56:32 +0900575 constexpr char host_name[] = "nihao.example2.com.";
Bernie Innocenti443489e2018-08-10 14:27:23 +0900576 std::vector<std::string> searchDomains = { "example1.com", "example2.com", "example3.com" };
Bernie Innocenti443489e2018-08-10 14:27:23 +0900577
Xiao Ma7c75f452018-12-11 17:56:32 +0900578 test::DNSResponder dns("127.0.0.6");
579 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.3"}});
580 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({"127.0.0.6"}, searchDomains));
581
Bernie Innocenti443489e2018-08-10 14:27:23 +0900582 const hostent* result = gethostbyname("nihao");
Xiao Ma7c75f452018-12-11 17:56:32 +0900583
Bernie Innocenti443489e2018-08-10 14:27:23 +0900584 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
585 ASSERT_FALSE(result == nullptr);
586 ASSERT_EQ(4, result->h_length);
587 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
588 EXPECT_EQ("1.2.3.3", ToString(result));
589 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
590 dns.stopServer();
591}
592
Bernie Innocenti974233e2018-09-04 20:35:34 +0900593TEST_F(ResolverTest, GetAddrInfoV6_numeric) {
Bernie Innocenti974233e2018-09-04 20:35:34 +0900594 constexpr char host_name[] = "ohayou.example.com.";
595 constexpr char numeric_addr[] = "fe80::1%lo";
596
Xiao Ma7c75f452018-12-11 17:56:32 +0900597 test::DNSResponder dns;
Bernie Innocenti974233e2018-09-04 20:35:34 +0900598 dns.setResponseProbability(0.0);
Xiao Ma7c75f452018-12-11 17:56:32 +0900599 StartDns(dns, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
600 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Bernie Innocenti974233e2018-09-04 20:35:34 +0900601
602 addrinfo hints = {.ai_family = AF_INET6};
603 ScopedAddrinfo result = safe_getaddrinfo(numeric_addr, nullptr, &hints);
604 EXPECT_TRUE(result != nullptr);
605 EXPECT_EQ(numeric_addr, ToString(result));
606 EXPECT_TRUE(dns.queries().empty()); // Ensure no DNS queries were sent out
607
608 // Now try a non-numeric hostname query with the AI_NUMERICHOST flag set.
609 // We should fail without sending out a DNS query.
610 hints.ai_flags |= AI_NUMERICHOST;
611 result = safe_getaddrinfo(host_name, nullptr, &hints);
612 EXPECT_TRUE(result == nullptr);
613 EXPECT_TRUE(dns.queries().empty()); // Ensure no DNS queries were sent out
614}
615
Bernie Innocenti443489e2018-08-10 14:27:23 +0900616TEST_F(ResolverTest, GetAddrInfoV6_failing) {
Xiao Ma7c75f452018-12-11 17:56:32 +0900617 constexpr char listen_addr0[] = "127.0.0.7";
618 constexpr char listen_addr1[] = "127.0.0.8";
Bernie Innocenti443489e2018-08-10 14:27:23 +0900619 const char* host_name = "ohayou.example.com.";
Xiao Ma7c75f452018-12-11 17:56:32 +0900620
621 test::DNSResponder dns0(listen_addr0);
622 test::DNSResponder dns1(listen_addr1);
Bernie Innocenti443489e2018-08-10 14:27:23 +0900623 dns0.setResponseProbability(0.0);
Xiao Ma7c75f452018-12-11 17:56:32 +0900624 StartDns(dns0, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
625 StartDns(dns1, {{host_name, ns_type::ns_t_aaaa, "2001:db8::6"}});
626
Bernie Innocenti443489e2018-08-10 14:27:23 +0900627 std::vector<std::string> servers = { listen_addr0, listen_addr1 };
628 // <sample validity in s> <success threshold in percent> <min samples> <max samples>
629 int sample_count = 8;
630 const std::vector<int> params = { 300, 25, sample_count, sample_count };
Xiao Ma7c75f452018-12-11 17:56:32 +0900631 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, kDefaultSearchDomains, params));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900632
633 // Repeatedly perform resolutions for non-existing domains until MAXNSSAMPLES resolutions have
634 // reached the dns0, which is set to fail. No more requests should then arrive at that server
635 // for the next sample_lifetime seconds.
636 // TODO: This approach is implementation-dependent, change once metrics reporting is available.
Xiao Ma7c75f452018-12-11 17:56:32 +0900637 const addrinfo hints = {.ai_family = AF_INET6};
Bernie Innocenti45238a12018-12-04 14:57:48 +0900638 for (int i = 0; i < sample_count; ++i) {
Bernie Innocenti443489e2018-08-10 14:27:23 +0900639 std::string domain = StringPrintf("nonexistent%d", i);
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900640 ScopedAddrinfo result = safe_getaddrinfo(domain.c_str(), nullptr, &hints);
Bernie Innocenti443489e2018-08-10 14:27:23 +0900641 }
642 // Due to 100% errors for all possible samples, the server should be ignored from now on and
643 // only the second one used for all following queries, until NSSAMPLE_VALIDITY is reached.
644 dns0.clearQueries();
645 dns1.clearQueries();
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900646 ScopedAddrinfo result = safe_getaddrinfo("ohayou", nullptr, &hints);
647 EXPECT_TRUE(result != nullptr);
Bernie Innocenti443489e2018-08-10 14:27:23 +0900648 EXPECT_EQ(0U, GetNumQueries(dns0, host_name));
649 EXPECT_EQ(1U, GetNumQueries(dns1, host_name));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900650}
651
652TEST_F(ResolverTest, GetAddrInfoV6_nonresponsive) {
Xiao Ma7c75f452018-12-11 17:56:32 +0900653 constexpr char listen_addr0[] = "127.0.0.7";
654 constexpr char listen_addr1[] = "127.0.0.8";
655 constexpr char listen_srv[] = "53";
656 constexpr char host_name1[] = "ohayou.example.com.";
657 constexpr char host_name2[] = "ciao.example.com.";
658 const std::vector<DnsRecord> records0 = {
659 {host_name1, ns_type::ns_t_aaaa, "2001:db8::5"},
660 {host_name2, ns_type::ns_t_aaaa, "2001:db8::5"},
661 };
662 const std::vector<DnsRecord> records1 = {
663 {host_name1, ns_type::ns_t_aaaa, "2001:db8::6"},
664 {host_name2, ns_type::ns_t_aaaa, "2001:db8::6"},
665 };
Bernie Innocenti443489e2018-08-10 14:27:23 +0900666
667 // dns0 does not respond with 100% probability, while
668 // dns1 responds normally, at least initially.
669 test::DNSResponder dns0(listen_addr0, listen_srv, 250, static_cast<ns_rcode>(-1));
670 test::DNSResponder dns1(listen_addr1, listen_srv, 250, static_cast<ns_rcode>(-1));
671 dns0.setResponseProbability(0.0);
Xiao Ma7c75f452018-12-11 17:56:32 +0900672 StartDns(dns0, records0);
673 StartDns(dns1, records1);
674 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr0, listen_addr1}));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900675
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900676 const addrinfo hints = {.ai_family = AF_INET6};
Bernie Innocenti443489e2018-08-10 14:27:23 +0900677
678 // dns0 will ignore the request, and we'll fallback to dns1 after the first
679 // retry.
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900680 ScopedAddrinfo result = safe_getaddrinfo(host_name1, nullptr, &hints);
681 EXPECT_TRUE(result != nullptr);
Bernie Innocenti443489e2018-08-10 14:27:23 +0900682 EXPECT_EQ(1U, GetNumQueries(dns0, host_name1));
683 EXPECT_EQ(1U, GetNumQueries(dns1, host_name1));
684
685 // Now make dns1 also ignore 100% requests... The resolve should alternate
686 // retries between the nameservers and fail after 4 attempts.
687 dns1.setResponseProbability(0.0);
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900688 addrinfo* result2 = nullptr;
689 EXPECT_EQ(EAI_NODATA, getaddrinfo(host_name2, nullptr, &hints, &result2));
690 EXPECT_EQ(nullptr, result2);
Bernie Innocenti443489e2018-08-10 14:27:23 +0900691 EXPECT_EQ(4U, GetNumQueries(dns0, host_name2));
692 EXPECT_EQ(4U, GetNumQueries(dns1, host_name2));
693}
694
695TEST_F(ResolverTest, GetAddrInfoV6_concurrent) {
Xiao Ma7c75f452018-12-11 17:56:32 +0900696 constexpr char listen_addr0[] = "127.0.0.9";
697 constexpr char listen_addr1[] = "127.0.0.10";
698 constexpr char listen_addr2[] = "127.0.0.11";
699 constexpr char host_name[] = "konbanha.example.com.";
700
701 test::DNSResponder dns0(listen_addr0);
702 test::DNSResponder dns1(listen_addr1);
703 test::DNSResponder dns2(listen_addr2);
704 StartDns(dns0, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
705 StartDns(dns1, {{host_name, ns_type::ns_t_aaaa, "2001:db8::6"}});
706 StartDns(dns2, {{host_name, ns_type::ns_t_aaaa, "2001:db8::7"}});
707
Bernie Innocenti443489e2018-08-10 14:27:23 +0900708 const std::vector<std::string> servers = { listen_addr0, listen_addr1, listen_addr2 };
709 std::vector<std::thread> threads(10);
710 for (std::thread& thread : threads) {
711 thread = std::thread([this, &servers]() {
712 unsigned delay = arc4random_uniform(1*1000*1000); // <= 1s
713 usleep(delay);
714 std::vector<std::string> serverSubset;
715 for (const auto& server : servers) {
716 if (arc4random_uniform(2)) {
717 serverSubset.push_back(server);
718 }
719 }
720 if (serverSubset.empty()) serverSubset = servers;
Xiao Ma7c75f452018-12-11 17:56:32 +0900721 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(serverSubset));
722 const addrinfo hints = {.ai_family = AF_INET6};
Bernie Innocenti443489e2018-08-10 14:27:23 +0900723 addrinfo* result = nullptr;
724 int rv = getaddrinfo("konbanha", nullptr, &hints, &result);
725 EXPECT_EQ(0, rv) << "error [" << rv << "] " << gai_strerror(rv);
726 if (result) {
727 freeaddrinfo(result);
728 result = nullptr;
729 }
730 });
731 }
732 for (std::thread& thread : threads) {
733 thread.join();
734 }
735}
736
737TEST_F(ResolverTest, GetAddrInfoStressTest_Binder_100) {
738 const unsigned num_hosts = 100;
739 const unsigned num_threads = 100;
740 const unsigned num_queries = 100;
741 ASSERT_NO_FATAL_FAILURE(RunGetAddrInfoStressTest_Binder(num_hosts, num_threads, num_queries));
742}
743
744TEST_F(ResolverTest, GetAddrInfoStressTest_Binder_100000) {
745 const unsigned num_hosts = 100000;
746 const unsigned num_threads = 100;
747 const unsigned num_queries = 100;
748 ASSERT_NO_FATAL_FAILURE(RunGetAddrInfoStressTest_Binder(num_hosts, num_threads, num_queries));
749}
750
751TEST_F(ResolverTest, EmptySetup) {
752 using android::net::INetd;
753 std::vector<std::string> servers;
754 std::vector<std::string> domains;
Xiao Ma7c75f452018-12-11 17:56:32 +0900755 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900756 std::vector<std::string> res_servers;
757 std::vector<std::string> res_domains;
Mike Yuda77e8e2018-11-26 13:26:21 +0900758 std::vector<std::string> res_tls_servers;
Bernie Innocenti443489e2018-08-10 14:27:23 +0900759 __res_params res_params;
760 std::vector<ResolverStats> res_stats;
Mike Yuda77e8e2018-11-26 13:26:21 +0900761 ASSERT_TRUE(
762 GetResolverInfo(&res_servers, &res_domains, &res_tls_servers, &res_params, &res_stats));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900763 EXPECT_EQ(0U, res_servers.size());
764 EXPECT_EQ(0U, res_domains.size());
Mike Yuda77e8e2018-11-26 13:26:21 +0900765 EXPECT_EQ(0U, res_tls_servers.size());
Xiao Ma7c75f452018-12-11 17:56:32 +0900766 ASSERT_EQ(static_cast<size_t>(INetd::RESOLVER_PARAMS_COUNT), kDefaultParams.size());
767 EXPECT_EQ(kDefaultParams[INetd::RESOLVER_PARAMS_SAMPLE_VALIDITY], res_params.sample_validity);
768 EXPECT_EQ(kDefaultParams[INetd::RESOLVER_PARAMS_SUCCESS_THRESHOLD],
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900769 res_params.success_threshold);
Xiao Ma7c75f452018-12-11 17:56:32 +0900770 EXPECT_EQ(kDefaultParams[INetd::RESOLVER_PARAMS_MIN_SAMPLES], res_params.min_samples);
771 EXPECT_EQ(kDefaultParams[INetd::RESOLVER_PARAMS_MAX_SAMPLES], res_params.max_samples);
772 EXPECT_EQ(kDefaultParams[INetd::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
Bernie Innocenti443489e2018-08-10 14:27:23 +0900773 res_params.base_timeout_msec);
774}
775
776TEST_F(ResolverTest, SearchPathChange) {
Xiao Ma7c75f452018-12-11 17:56:32 +0900777 constexpr char listen_addr[] = "127.0.0.13";
778 constexpr char host_name1[] = "test13.domain1.org.";
779 constexpr char host_name2[] = "test13.domain2.org.";
Bernie Innocenti443489e2018-08-10 14:27:23 +0900780 std::vector<std::string> servers = { listen_addr };
781 std::vector<std::string> domains = { "domain1.org" };
Xiao Ma7c75f452018-12-11 17:56:32 +0900782
783 const std::vector<DnsRecord> records = {
784 {host_name1, ns_type::ns_t_aaaa, "2001:db8::13"},
785 {host_name2, ns_type::ns_t_aaaa, "2001:db8::1:13"},
786 };
787 test::DNSResponder dns(listen_addr);
788 StartDns(dns, records);
789 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900790
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900791 const addrinfo hints = {.ai_family = AF_INET6};
792 ScopedAddrinfo result = safe_getaddrinfo("test13", nullptr, &hints);
793 EXPECT_TRUE(result != nullptr);
Bernie Innocenti443489e2018-08-10 14:27:23 +0900794 EXPECT_EQ(1U, dns.queries().size());
795 EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
796 EXPECT_EQ("2001:db8::13", ToString(result));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900797
798 // Test that changing the domain search path on its own works.
799 domains = { "domain2.org" };
Xiao Ma7c75f452018-12-11 17:56:32 +0900800 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900801 dns.clearQueries();
802
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900803 result = safe_getaddrinfo("test13", nullptr, &hints);
804 EXPECT_TRUE(result != nullptr);
Bernie Innocenti443489e2018-08-10 14:27:23 +0900805 EXPECT_EQ(1U, dns.queries().size());
806 EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
807 EXPECT_EQ("2001:db8::1:13", ToString(result));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900808}
809
Bernie Innocenti443489e2018-08-10 14:27:23 +0900810static std::string base64Encode(const std::vector<uint8_t>& input) {
811 size_t out_len;
812 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
813 // out_len includes the trailing NULL.
814 uint8_t output_bytes[out_len];
815 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
816 return std::string(reinterpret_cast<char*>(output_bytes));
817}
818
Mike Yuda77e8e2018-11-26 13:26:21 +0900819// If we move this function to dns_responder_client, it will complicate the dependency need of
820// dns_tls_frontend.h.
821static void setupTlsServers(const std::vector<std::string>& servers,
822 std::vector<std::unique_ptr<test::DnsTlsFrontend>>* tls,
823 std::vector<std::string>* fingerprints) {
Xiao Ma7c75f452018-12-11 17:56:32 +0900824 constexpr char listen_udp[] = "53";
825 constexpr char listen_tls[] = "853";
Mike Yuda77e8e2018-11-26 13:26:21 +0900826
827 for (const auto& server : servers) {
828 auto t = std::make_unique<test::DnsTlsFrontend>(server, listen_tls, server, listen_udp);
829 t = std::make_unique<test::DnsTlsFrontend>(server, listen_tls, server, listen_udp);
830 t->startServer();
831 fingerprints->push_back(base64Encode(t->fingerprint()));
832 tls->push_back(std::move(t));
833 }
834}
835
836static void shutdownTlsServers(std::vector<std::unique_ptr<test::DnsTlsFrontend>>* tls) {
837 for (const auto& t : *tls) {
838 t->stopServer();
839 }
840 tls->clear();
841}
842
843TEST_F(ResolverTest, MaxServerPrune_Binder) {
844 using android::net::INetd;
845
846 std::vector<std::string> domains;
847 std::vector<std::unique_ptr<test::DNSResponder>> dns;
848 std::vector<std::unique_ptr<test::DnsTlsFrontend>> tls;
849 std::vector<std::string> servers;
850 std::vector<std::string> fingerprints;
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900851 std::vector<DnsResponderClient::Mapping> mappings;
Mike Yuda77e8e2018-11-26 13:26:21 +0900852
853 for (unsigned i = 0; i < MAXDNSRCH + 1; i++) {
854 domains.push_back(StringPrintf("example%u.com", i));
855 }
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900856 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(1, domains, &mappings));
857 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(MAXNS + 1, mappings, &dns, &servers));
Mike Yuda77e8e2018-11-26 13:26:21 +0900858 ASSERT_NO_FATAL_FAILURE(setupTlsServers(servers, &tls, &fingerprints));
859
Xiao Ma7c75f452018-12-11 17:56:32 +0900860 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, domains, kDefaultParams, "", fingerprints));
Mike Yuda77e8e2018-11-26 13:26:21 +0900861
862 std::vector<std::string> res_servers;
863 std::vector<std::string> res_domains;
864 std::vector<std::string> res_tls_servers;
865 __res_params res_params;
866 std::vector<ResolverStats> res_stats;
867 ASSERT_TRUE(
868 GetResolverInfo(&res_servers, &res_domains, &res_tls_servers, &res_params, &res_stats));
869
870 // Check the size of the stats and its contents.
871 EXPECT_EQ(static_cast<size_t>(MAXNS), res_servers.size());
872 EXPECT_EQ(static_cast<size_t>(MAXNS), res_tls_servers.size());
873 EXPECT_EQ(static_cast<size_t>(MAXDNSRCH), res_domains.size());
874 EXPECT_TRUE(std::equal(servers.begin(), servers.begin() + MAXNS, res_servers.begin()));
875 EXPECT_TRUE(std::equal(servers.begin(), servers.begin() + MAXNS, res_tls_servers.begin()));
876 EXPECT_TRUE(std::equal(domains.begin(), domains.begin() + MAXDNSRCH, res_domains.begin()));
877
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900878 ASSERT_NO_FATAL_FAILURE(mDnsClient.ShutdownDNSServers(&dns));
Mike Yuda77e8e2018-11-26 13:26:21 +0900879 ASSERT_NO_FATAL_FAILURE(shutdownTlsServers(&tls));
880}
881
882TEST_F(ResolverTest, ResolverStats) {
Xiao Ma7c75f452018-12-11 17:56:32 +0900883 constexpr char listen_addr1[] = "127.0.0.4";
884 constexpr char listen_addr2[] = "127.0.0.5";
885 constexpr char listen_addr3[] = "127.0.0.6";
Mike Yuda77e8e2018-11-26 13:26:21 +0900886
887 // Set server 1 timeout.
Xiao Ma7c75f452018-12-11 17:56:32 +0900888 test::DNSResponder dns1(listen_addr1, "53", 250, static_cast<ns_rcode>(-1));
Mike Yuda77e8e2018-11-26 13:26:21 +0900889 dns1.setResponseProbability(0.0);
890 ASSERT_TRUE(dns1.startServer());
891
892 // Set server 2 responding server failure.
Xiao Ma7c75f452018-12-11 17:56:32 +0900893 test::DNSResponder dns2(listen_addr2);
Mike Yuda77e8e2018-11-26 13:26:21 +0900894 dns2.setResponseProbability(0.0);
895 ASSERT_TRUE(dns2.startServer());
896
897 // Set server 3 workable.
Xiao Ma7c75f452018-12-11 17:56:32 +0900898 test::DNSResponder dns3(listen_addr3);
899 dns3.addMapping(kHelloExampleCom, ns_type::ns_t_a, "1.2.3.4");
Mike Yuda77e8e2018-11-26 13:26:21 +0900900 ASSERT_TRUE(dns3.startServer());
901
902 std::vector<std::string> servers = {listen_addr1, listen_addr2, listen_addr3};
Xiao Ma7c75f452018-12-11 17:56:32 +0900903 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Mike Yuda77e8e2018-11-26 13:26:21 +0900904
905 dns3.clearQueries();
Xiao Ma7c75f452018-12-11 17:56:32 +0900906 const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
Mike Yuda77e8e2018-11-26 13:26:21 +0900907 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
Xiao Ma7c75f452018-12-11 17:56:32 +0900908 size_t found = GetNumQueries(dns3, kHelloExampleCom);
Mike Yuda77e8e2018-11-26 13:26:21 +0900909 EXPECT_LE(1U, found);
910 std::string result_str = ToString(result);
911 EXPECT_TRUE(result_str == "1.2.3.4") << ", result_str='" << result_str << "'";
912
913 std::vector<std::string> res_servers;
914 std::vector<std::string> res_domains;
915 std::vector<std::string> res_tls_servers;
916 __res_params res_params;
917 std::vector<ResolverStats> res_stats;
918 ASSERT_TRUE(
919 GetResolverInfo(&res_servers, &res_domains, &res_tls_servers, &res_params, &res_stats));
920
921 EXPECT_EQ(1, res_stats[0].timeouts);
922 EXPECT_EQ(1, res_stats[1].errors);
923 EXPECT_EQ(1, res_stats[2].successes);
Mike Yuda77e8e2018-11-26 13:26:21 +0900924}
925
Bernie Innocenti443489e2018-08-10 14:27:23 +0900926// Test what happens if the specified TLS server is nonexistent.
927TEST_F(ResolverTest, GetHostByName_TlsMissing) {
Xiao Ma7c75f452018-12-11 17:56:32 +0900928 constexpr char listen_addr[] = "127.0.0.3";
929 constexpr char host_name[] = "tlsmissing.example.com.";
930
931 test::DNSResponder dns;
932 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.3"}});
Bernie Innocenti443489e2018-08-10 14:27:23 +0900933 std::vector<std::string> servers = { listen_addr };
934
935 // There's nothing listening on this address, so validation will either fail or
936 /// hang. Either way, queries will continue to flow to the DNSResponder.
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900937 ASSERT_TRUE(
Xiao Ma7c75f452018-12-11 17:56:32 +0900938 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900939
940 const hostent* result;
941
942 result = gethostbyname("tlsmissing");
943 ASSERT_FALSE(result == nullptr);
944 EXPECT_EQ("1.2.3.3", ToString(result));
945
946 // Clear TLS bit.
Xiao Ma7c75f452018-12-11 17:56:32 +0900947 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Bernie Innocenti443489e2018-08-10 14:27:23 +0900948}
949
950// Test what happens if the specified TLS server replies with garbage.
951TEST_F(ResolverTest, GetHostByName_TlsBroken) {
Xiao Ma7c75f452018-12-11 17:56:32 +0900952 constexpr char listen_addr[] = "127.0.0.3";
953 constexpr char host_name1[] = "tlsbroken1.example.com.";
954 constexpr char host_name2[] = "tlsbroken2.example.com.";
955 const std::vector<DnsRecord> records = {
956 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
957 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
958 };
959
960 test::DNSResponder dns;
961 StartDns(dns, records);
Bernie Innocenti443489e2018-08-10 14:27:23 +0900962 std::vector<std::string> servers = { listen_addr };
963
964 // Bind the specified private DNS socket but don't respond to any client sockets yet.
965 int s = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP);
966 ASSERT_TRUE(s >= 0);
967 struct sockaddr_in tlsServer = {
968 .sin_family = AF_INET,
969 .sin_port = htons(853),
970 };
971 ASSERT_TRUE(inet_pton(AF_INET, listen_addr, &tlsServer.sin_addr));
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900972 ASSERT_TRUE(enableSockopt(s, SOL_SOCKET, SO_REUSEPORT).ok());
973 ASSERT_TRUE(enableSockopt(s, SOL_SOCKET, SO_REUSEADDR).ok());
Bernie Innocenti443489e2018-08-10 14:27:23 +0900974 ASSERT_FALSE(bind(s, reinterpret_cast<struct sockaddr*>(&tlsServer), sizeof(tlsServer)));
975 ASSERT_FALSE(listen(s, 1));
976
977 // Trigger TLS validation.
Bernie Innocenti3e411a32019-01-17 21:28:24 +0900978 ASSERT_TRUE(
Xiao Ma7c75f452018-12-11 17:56:32 +0900979 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
Bernie Innocenti443489e2018-08-10 14:27:23 +0900980
981 struct sockaddr_storage cliaddr;
982 socklen_t sin_size = sizeof(cliaddr);
983 int new_fd = accept4(s, reinterpret_cast<struct sockaddr *>(&cliaddr), &sin_size, SOCK_CLOEXEC);
984 ASSERT_TRUE(new_fd > 0);
985
986 // We've received the new file descriptor but not written to it or closed, so the
987 // validation is still pending. Queries should still flow correctly because the
988 // server is not used until validation succeeds.
989 const hostent* result;
990 result = gethostbyname("tlsbroken1");
991 ASSERT_FALSE(result == nullptr);
992 EXPECT_EQ("1.2.3.1", ToString(result));
993
994 // Now we cause the validation to fail.
995 std::string garbage = "definitely not a valid TLS ServerHello";
996 write(new_fd, garbage.data(), garbage.size());
997 close(new_fd);
998
999 // Validation failure shouldn't interfere with lookups, because lookups won't be sent
1000 // to the TLS server unless validation succeeds.
1001 result = gethostbyname("tlsbroken2");
1002 ASSERT_FALSE(result == nullptr);
1003 EXPECT_EQ("1.2.3.2", ToString(result));
1004
1005 // Clear TLS bit.
Xiao Ma7c75f452018-12-11 17:56:32 +09001006 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Bernie Innocenti443489e2018-08-10 14:27:23 +09001007 close(s);
1008}
1009
1010TEST_F(ResolverTest, GetHostByName_Tls) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001011 constexpr char listen_addr[] = "127.0.0.3";
1012 constexpr char listen_udp[] = "53";
1013 constexpr char listen_tls[] = "853";
1014 constexpr char host_name1[] = "tls1.example.com.";
1015 constexpr char host_name2[] = "tls2.example.com.";
1016 constexpr char host_name3[] = "tls3.example.com.";
1017 const std::vector<DnsRecord> records = {
1018 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1019 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1020 {host_name3, ns_type::ns_t_a, "1.2.3.3"},
1021 };
1022
1023 test::DNSResponder dns;
1024 StartDns(dns, records);
Bernie Innocenti443489e2018-08-10 14:27:23 +09001025 std::vector<std::string> servers = { listen_addr };
1026
1027 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1028 ASSERT_TRUE(tls.startServer());
Bernie Innocenti3e411a32019-01-17 21:28:24 +09001029 ASSERT_TRUE(
Xiao Ma7c75f452018-12-11 17:56:32 +09001030 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
Bernie Innocenti443489e2018-08-10 14:27:23 +09001031
1032 const hostent* result;
1033
1034 // Wait for validation to complete.
1035 EXPECT_TRUE(tls.waitForQueries(1, 5000));
1036
1037 result = gethostbyname("tls1");
1038 ASSERT_FALSE(result == nullptr);
1039 EXPECT_EQ("1.2.3.1", ToString(result));
1040
1041 // Wait for query to get counted.
1042 EXPECT_TRUE(tls.waitForQueries(2, 5000));
1043
1044 // Stop the TLS server. Since we're in opportunistic mode, queries will
1045 // fall back to the locally-assigned (clear text) nameservers.
1046 tls.stopServer();
1047
1048 dns.clearQueries();
1049 result = gethostbyname("tls2");
1050 EXPECT_FALSE(result == nullptr);
1051 EXPECT_EQ("1.2.3.2", ToString(result));
1052 const auto queries = dns.queries();
1053 EXPECT_EQ(1U, queries.size());
1054 EXPECT_EQ("tls2.example.com.", queries[0].first);
1055 EXPECT_EQ(ns_t_a, queries[0].second);
1056
1057 // Reset the resolvers without enabling TLS. Queries should still be routed
1058 // to the UDP endpoint.
Xiao Ma7c75f452018-12-11 17:56:32 +09001059 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Bernie Innocenti443489e2018-08-10 14:27:23 +09001060
1061 result = gethostbyname("tls3");
1062 ASSERT_FALSE(result == nullptr);
1063 EXPECT_EQ("1.2.3.3", ToString(result));
Bernie Innocenti443489e2018-08-10 14:27:23 +09001064}
1065
1066TEST_F(ResolverTest, GetHostByName_TlsFingerprint) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001067 constexpr char listen_addr[] = "127.0.0.3";
1068 constexpr char listen_udp[] = "53";
1069 constexpr char listen_tls[] = "853";
1070 test::DNSResponder dns;
Bernie Innocenti443489e2018-08-10 14:27:23 +09001071 ASSERT_TRUE(dns.startServer());
1072 for (int chain_length = 1; chain_length <= 3; ++chain_length) {
Bernie Innocentif2572392018-10-02 19:04:56 +09001073 std::string host_name = StringPrintf("tlsfingerprint%d.example.com.", chain_length);
Bernie Innocenti443489e2018-08-10 14:27:23 +09001074 dns.addMapping(host_name, ns_type::ns_t_a, "1.2.3.1");
1075 std::vector<std::string> servers = { listen_addr };
1076
1077 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1078 tls.set_chain_length(chain_length);
1079 ASSERT_TRUE(tls.startServer());
Xiao Ma7c75f452018-12-11 17:56:32 +09001080 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
Bernie Innocenti3e411a32019-01-17 21:28:24 +09001081 "", {base64Encode(tls.fingerprint())}));
Bernie Innocenti443489e2018-08-10 14:27:23 +09001082
1083 const hostent* result;
1084
1085 // Wait for validation to complete.
1086 EXPECT_TRUE(tls.waitForQueries(1, 5000));
1087
1088 result = gethostbyname(StringPrintf("tlsfingerprint%d", chain_length).c_str());
1089 EXPECT_FALSE(result == nullptr);
1090 if (result) {
1091 EXPECT_EQ("1.2.3.1", ToString(result));
1092
1093 // Wait for query to get counted.
1094 EXPECT_TRUE(tls.waitForQueries(2, 5000));
1095 }
1096
1097 // Clear TLS bit to ensure revalidation.
Xiao Ma7c75f452018-12-11 17:56:32 +09001098 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Bernie Innocenti443489e2018-08-10 14:27:23 +09001099 tls.stopServer();
1100 }
Bernie Innocenti443489e2018-08-10 14:27:23 +09001101}
1102
1103TEST_F(ResolverTest, GetHostByName_BadTlsFingerprint) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001104 constexpr char listen_addr[] = "127.0.0.3";
1105 constexpr char listen_udp[] = "53";
1106 constexpr char listen_tls[] = "853";
1107 constexpr char host_name[] = "badtlsfingerprint.example.com.";
1108
1109 test::DNSResponder dns;
1110 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.1"}});
Bernie Innocenti443489e2018-08-10 14:27:23 +09001111 std::vector<std::string> servers = { listen_addr };
1112
1113 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1114 ASSERT_TRUE(tls.startServer());
1115 std::vector<uint8_t> bad_fingerprint = tls.fingerprint();
1116 bad_fingerprint[5] += 1; // Corrupt the fingerprint.
Xiao Ma7c75f452018-12-11 17:56:32 +09001117 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "",
Bernie Innocenti3e411a32019-01-17 21:28:24 +09001118 {base64Encode(bad_fingerprint)}));
Bernie Innocenti443489e2018-08-10 14:27:23 +09001119
1120 // The initial validation should fail at the fingerprint check before
1121 // issuing a query.
1122 EXPECT_FALSE(tls.waitForQueries(1, 500));
1123
1124 // A fingerprint was provided and failed to match, so the query should fail.
1125 EXPECT_EQ(nullptr, gethostbyname("badtlsfingerprint"));
1126
1127 // Clear TLS bit.
Xiao Ma7c75f452018-12-11 17:56:32 +09001128 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Bernie Innocenti443489e2018-08-10 14:27:23 +09001129}
1130
1131// Test that we can pass two different fingerprints, and connection succeeds as long as
1132// at least one of them matches the server.
1133TEST_F(ResolverTest, GetHostByName_TwoTlsFingerprints) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001134 constexpr char listen_addr[] = "127.0.0.3";
1135 constexpr char listen_udp[] = "53";
1136 constexpr char listen_tls[] = "853";
1137 constexpr char host_name[] = "twotlsfingerprints.example.com.";
1138
1139 test::DNSResponder dns;
1140 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.1"}});
Bernie Innocenti443489e2018-08-10 14:27:23 +09001141 std::vector<std::string> servers = { listen_addr };
1142
1143 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1144 ASSERT_TRUE(tls.startServer());
1145 std::vector<uint8_t> bad_fingerprint = tls.fingerprint();
1146 bad_fingerprint[5] += 1; // Corrupt the fingerprint.
Bernie Innocenti3e411a32019-01-17 21:28:24 +09001147 ASSERT_TRUE(mDnsClient.SetResolversWithTls(
Xiao Ma7c75f452018-12-11 17:56:32 +09001148 servers, kDefaultSearchDomains, kDefaultParams, "",
Bernie Innocenti3e411a32019-01-17 21:28:24 +09001149 {base64Encode(bad_fingerprint), base64Encode(tls.fingerprint())}));
Bernie Innocenti443489e2018-08-10 14:27:23 +09001150
1151 const hostent* result;
1152
1153 // Wait for validation to complete.
1154 EXPECT_TRUE(tls.waitForQueries(1, 5000));
1155
1156 result = gethostbyname("twotlsfingerprints");
1157 ASSERT_FALSE(result == nullptr);
1158 EXPECT_EQ("1.2.3.1", ToString(result));
1159
1160 // Wait for query to get counted.
1161 EXPECT_TRUE(tls.waitForQueries(2, 5000));
1162
1163 // Clear TLS bit.
Xiao Ma7c75f452018-12-11 17:56:32 +09001164 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Bernie Innocenti443489e2018-08-10 14:27:23 +09001165}
1166
1167TEST_F(ResolverTest, GetHostByName_TlsFingerprintGoesBad) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001168 constexpr char listen_addr[] = "127.0.0.3";
1169 constexpr char listen_udp[] = "53";
1170 constexpr char listen_tls[] = "853";
1171 constexpr char host_name1[] = "tlsfingerprintgoesbad1.example.com.";
1172 constexpr char host_name2[] = "tlsfingerprintgoesbad2.example.com.";
1173 const std::vector<DnsRecord> records = {
1174 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1175 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1176 };
1177
1178 test::DNSResponder dns;
1179 StartDns(dns, records);
Bernie Innocenti443489e2018-08-10 14:27:23 +09001180 std::vector<std::string> servers = { listen_addr };
1181
1182 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1183 ASSERT_TRUE(tls.startServer());
Xiao Ma7c75f452018-12-11 17:56:32 +09001184 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "",
Bernie Innocenti3e411a32019-01-17 21:28:24 +09001185 {base64Encode(tls.fingerprint())}));
Bernie Innocenti443489e2018-08-10 14:27:23 +09001186
1187 const hostent* result;
1188
1189 // Wait for validation to complete.
1190 EXPECT_TRUE(tls.waitForQueries(1, 5000));
1191
1192 result = gethostbyname("tlsfingerprintgoesbad1");
1193 ASSERT_FALSE(result == nullptr);
1194 EXPECT_EQ("1.2.3.1", ToString(result));
1195
1196 // Wait for query to get counted.
1197 EXPECT_TRUE(tls.waitForQueries(2, 5000));
1198
1199 // Restart the TLS server. This will generate a new certificate whose fingerprint
1200 // no longer matches the stored fingerprint.
1201 tls.stopServer();
1202 tls.startServer();
1203
1204 result = gethostbyname("tlsfingerprintgoesbad2");
1205 ASSERT_TRUE(result == nullptr);
1206 EXPECT_EQ(HOST_NOT_FOUND, h_errno);
1207
1208 // Clear TLS bit.
Xiao Ma7c75f452018-12-11 17:56:32 +09001209 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Bernie Innocenti443489e2018-08-10 14:27:23 +09001210}
1211
1212TEST_F(ResolverTest, GetHostByName_TlsFailover) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001213 constexpr char listen_addr1[] = "127.0.0.3";
1214 constexpr char listen_addr2[] = "127.0.0.4";
1215 constexpr char listen_udp[] = "53";
1216 constexpr char listen_tls[] = "853";
1217 constexpr char host_name1[] = "tlsfailover1.example.com.";
1218 constexpr char host_name2[] = "tlsfailover2.example.com.";
1219 const std::vector<DnsRecord> records1 = {
1220 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1221 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1222 };
1223 const std::vector<DnsRecord> records2 = {
1224 {host_name1, ns_type::ns_t_a, "1.2.3.3"},
1225 {host_name2, ns_type::ns_t_a, "1.2.3.4"},
1226 };
1227
1228 test::DNSResponder dns1(listen_addr1);
1229 test::DNSResponder dns2(listen_addr2);
1230 StartDns(dns1, records1);
1231 StartDns(dns2, records2);
1232
Bernie Innocenti443489e2018-08-10 14:27:23 +09001233 std::vector<std::string> servers = { listen_addr1, listen_addr2 };
1234
1235 test::DnsTlsFrontend tls1(listen_addr1, listen_tls, listen_addr1, listen_udp);
1236 test::DnsTlsFrontend tls2(listen_addr2, listen_tls, listen_addr2, listen_udp);
1237 ASSERT_TRUE(tls1.startServer());
1238 ASSERT_TRUE(tls2.startServer());
Bernie Innocenti3e411a32019-01-17 21:28:24 +09001239 ASSERT_TRUE(mDnsClient.SetResolversWithTls(
Xiao Ma7c75f452018-12-11 17:56:32 +09001240 servers, kDefaultSearchDomains, kDefaultParams, "",
Bernie Innocenti3e411a32019-01-17 21:28:24 +09001241 {base64Encode(tls1.fingerprint()), base64Encode(tls2.fingerprint())}));
Bernie Innocenti443489e2018-08-10 14:27:23 +09001242
1243 const hostent* result;
1244
1245 // Wait for validation to complete.
1246 EXPECT_TRUE(tls1.waitForQueries(1, 5000));
1247 EXPECT_TRUE(tls2.waitForQueries(1, 5000));
1248
1249 result = gethostbyname("tlsfailover1");
1250 ASSERT_FALSE(result == nullptr);
1251 EXPECT_EQ("1.2.3.1", ToString(result));
1252
1253 // Wait for query to get counted.
1254 EXPECT_TRUE(tls1.waitForQueries(2, 5000));
1255 // No new queries should have reached tls2.
1256 EXPECT_EQ(1, tls2.queries());
1257
1258 // Stop tls1. Subsequent queries should attempt to reach tls1, fail, and retry to tls2.
1259 tls1.stopServer();
1260
1261 result = gethostbyname("tlsfailover2");
1262 EXPECT_EQ("1.2.3.4", ToString(result));
1263
1264 // Wait for query to get counted.
1265 EXPECT_TRUE(tls2.waitForQueries(2, 5000));
1266
1267 // No additional queries should have reached the insecure servers.
1268 EXPECT_EQ(2U, dns1.queries().size());
1269 EXPECT_EQ(2U, dns2.queries().size());
1270
1271 // Clear TLS bit.
Xiao Ma7c75f452018-12-11 17:56:32 +09001272 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Bernie Innocenti443489e2018-08-10 14:27:23 +09001273}
1274
1275TEST_F(ResolverTest, GetHostByName_BadTlsName) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001276 constexpr char listen_addr[] = "127.0.0.3";
1277 constexpr char listen_udp[] = "53";
1278 constexpr char listen_tls[] = "853";
1279 constexpr char host_name[] = "badtlsname.example.com.";
1280
1281 test::DNSResponder dns;
1282 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.1"}});
Bernie Innocenti443489e2018-08-10 14:27:23 +09001283 std::vector<std::string> servers = { listen_addr };
1284
1285 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1286 ASSERT_TRUE(tls.startServer());
Xiao Ma7c75f452018-12-11 17:56:32 +09001287 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
Bernie Innocenti3e411a32019-01-17 21:28:24 +09001288 "www.example.com", {}));
Bernie Innocenti443489e2018-08-10 14:27:23 +09001289
1290 // The TLS server's certificate doesn't chain to a known CA, and a nonempty name was specified,
1291 // so the client should fail the TLS handshake before ever issuing a query.
1292 EXPECT_FALSE(tls.waitForQueries(1, 500));
1293
1294 // The query should fail hard, because a name was specified.
1295 EXPECT_EQ(nullptr, gethostbyname("badtlsname"));
1296
1297 // Clear TLS bit.
Xiao Ma7c75f452018-12-11 17:56:32 +09001298 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Bernie Innocenti443489e2018-08-10 14:27:23 +09001299}
1300
1301TEST_F(ResolverTest, GetAddrInfo_Tls) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001302 constexpr char listen_addr[] = "127.0.0.3";
1303 constexpr char listen_udp[] = "53";
1304 constexpr char listen_tls[] = "853";
1305 constexpr char host_name[] = "addrinfotls.example.com.";
1306 const std::vector<DnsRecord> records = {
1307 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1308 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1309 };
1310
1311 test::DNSResponder dns;
1312 StartDns(dns, records);
Bernie Innocenti443489e2018-08-10 14:27:23 +09001313 std::vector<std::string> servers = { listen_addr };
1314
1315 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1316 ASSERT_TRUE(tls.startServer());
Xiao Ma7c75f452018-12-11 17:56:32 +09001317 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "",
Bernie Innocenti3e411a32019-01-17 21:28:24 +09001318 {base64Encode(tls.fingerprint())}));
Bernie Innocenti443489e2018-08-10 14:27:23 +09001319
1320 // Wait for validation to complete.
1321 EXPECT_TRUE(tls.waitForQueries(1, 5000));
1322
1323 dns.clearQueries();
Bernie Innocenti9bf749f2018-08-30 08:37:22 +09001324 ScopedAddrinfo result = safe_getaddrinfo("addrinfotls", nullptr, nullptr);
1325 EXPECT_TRUE(result != nullptr);
Bernie Innocenti443489e2018-08-10 14:27:23 +09001326 size_t found = GetNumQueries(dns, host_name);
1327 EXPECT_LE(1U, found);
1328 // Could be A or AAAA
1329 std::string result_str = ToString(result);
1330 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
1331 << ", result_str='" << result_str << "'";
Bernie Innocenti443489e2018-08-10 14:27:23 +09001332 // Wait for both A and AAAA queries to get counted.
1333 EXPECT_TRUE(tls.waitForQueries(3, 5000));
1334
1335 // Clear TLS bit.
Xiao Ma7c75f452018-12-11 17:56:32 +09001336 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Bernie Innocenti443489e2018-08-10 14:27:23 +09001337}
1338
1339TEST_F(ResolverTest, TlsBypass) {
1340 const char OFF[] = "off";
1341 const char OPPORTUNISTIC[] = "opportunistic";
1342 const char STRICT[] = "strict";
1343
1344 const char GETHOSTBYNAME[] = "gethostbyname";
1345 const char GETADDRINFO[] = "getaddrinfo";
1346 const char GETADDRINFOFORNET[] = "getaddrinfofornet";
1347
1348 const unsigned BYPASS_NETID = NETID_USE_LOCAL_NAMESERVERS | TEST_NETID;
1349
Mike Yu5ae61542018-10-19 22:11:43 +08001350 const std::vector<uint8_t> NOOP_FINGERPRINT(SHA256_SIZE, 0U);
Bernie Innocenti443489e2018-08-10 14:27:23 +09001351
1352 const char ADDR4[] = "192.0.2.1";
1353 const char ADDR6[] = "2001:db8::1";
1354
1355 const char cleartext_addr[] = "127.0.0.53";
1356 const char cleartext_port[] = "53";
1357 const char tls_port[] = "853";
1358 const std::vector<std::string> servers = { cleartext_addr };
1359
Xiao Ma7c75f452018-12-11 17:56:32 +09001360 test::DNSResponder dns(cleartext_addr);
Bernie Innocenti443489e2018-08-10 14:27:23 +09001361 ASSERT_TRUE(dns.startServer());
1362
1363 test::DnsTlsFrontend tls(cleartext_addr, tls_port, cleartext_addr, cleartext_port);
1364
1365 struct TestConfig {
1366 const std::string mode;
1367 const bool withWorkingTLS;
1368 const std::string method;
1369
1370 std::string asHostName() const {
1371 return StringPrintf("%s.%s.%s.",
1372 mode.c_str(),
1373 withWorkingTLS ? "tlsOn" : "tlsOff",
1374 method.c_str());
1375 }
1376 } testConfigs[]{
1377 {OFF, false, GETHOSTBYNAME},
1378 {OPPORTUNISTIC, false, GETHOSTBYNAME},
1379 {STRICT, false, GETHOSTBYNAME},
1380 {OFF, true, GETHOSTBYNAME},
1381 {OPPORTUNISTIC, true, GETHOSTBYNAME},
1382 {STRICT, true, GETHOSTBYNAME},
1383 {OFF, false, GETADDRINFO},
1384 {OPPORTUNISTIC, false, GETADDRINFO},
1385 {STRICT, false, GETADDRINFO},
1386 {OFF, true, GETADDRINFO},
1387 {OPPORTUNISTIC, true, GETADDRINFO},
1388 {STRICT, true, GETADDRINFO},
1389 {OFF, false, GETADDRINFOFORNET},
1390 {OPPORTUNISTIC, false, GETADDRINFOFORNET},
1391 {STRICT, false, GETADDRINFOFORNET},
1392 {OFF, true, GETADDRINFOFORNET},
1393 {OPPORTUNISTIC, true, GETADDRINFOFORNET},
1394 {STRICT, true, GETADDRINFOFORNET},
1395 };
1396
1397 for (const auto& config : testConfigs) {
1398 const std::string testHostName = config.asHostName();
1399 SCOPED_TRACE(testHostName);
1400
1401 // Don't tempt test bugs due to caching.
1402 const char* host_name = testHostName.c_str();
1403 dns.addMapping(host_name, ns_type::ns_t_a, ADDR4);
1404 dns.addMapping(host_name, ns_type::ns_t_aaaa, ADDR6);
1405
1406 if (config.withWorkingTLS) ASSERT_TRUE(tls.startServer());
1407
1408 if (config.mode == OFF) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001409 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, kDefaultSearchDomains,
1410 kDefaultParams));
Bernie Innocenti443489e2018-08-10 14:27:23 +09001411 } else if (config.mode == OPPORTUNISTIC) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001412 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
1413 kDefaultParams, "", {}));
Bernie Innocenti443489e2018-08-10 14:27:23 +09001414 // Wait for validation to complete.
1415 if (config.withWorkingTLS) EXPECT_TRUE(tls.waitForQueries(1, 5000));
1416 } else if (config.mode == STRICT) {
1417 // We use the existence of fingerprints to trigger strict mode,
1418 // rather than hostname validation.
1419 const auto& fingerprint =
1420 (config.withWorkingTLS) ? tls.fingerprint() : NOOP_FINGERPRINT;
Xiao Ma7c75f452018-12-11 17:56:32 +09001421 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
1422 kDefaultParams, "",
Bernie Innocenti3e411a32019-01-17 21:28:24 +09001423 {base64Encode(fingerprint)}));
Bernie Innocenti443489e2018-08-10 14:27:23 +09001424 // Wait for validation to complete.
1425 if (config.withWorkingTLS) EXPECT_TRUE(tls.waitForQueries(1, 5000));
1426 } else {
1427 FAIL() << "Unsupported Private DNS mode: " << config.mode;
1428 }
1429
1430 const int tlsQueriesBefore = tls.queries();
1431
1432 const hostent* h_result = nullptr;
Bernie Innocenti9bf749f2018-08-30 08:37:22 +09001433 ScopedAddrinfo ai_result;
Bernie Innocenti443489e2018-08-10 14:27:23 +09001434
1435 if (config.method == GETHOSTBYNAME) {
1436 ASSERT_EQ(0, setNetworkForResolv(BYPASS_NETID));
1437 h_result = gethostbyname(host_name);
1438
1439 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
1440 ASSERT_FALSE(h_result == nullptr);
1441 ASSERT_EQ(4, h_result->h_length);
1442 ASSERT_FALSE(h_result->h_addr_list[0] == nullptr);
1443 EXPECT_EQ(ADDR4, ToString(h_result));
1444 EXPECT_TRUE(h_result->h_addr_list[1] == nullptr);
1445 } else if (config.method == GETADDRINFO) {
1446 ASSERT_EQ(0, setNetworkForResolv(BYPASS_NETID));
Bernie Innocenti9bf749f2018-08-30 08:37:22 +09001447 ai_result = safe_getaddrinfo(host_name, nullptr, nullptr);
1448 EXPECT_TRUE(ai_result != nullptr);
Bernie Innocenti443489e2018-08-10 14:27:23 +09001449
1450 EXPECT_LE(1U, GetNumQueries(dns, host_name));
1451 // Could be A or AAAA
1452 const std::string result_str = ToString(ai_result);
1453 EXPECT_TRUE(result_str == ADDR4 || result_str == ADDR6)
1454 << ", result_str='" << result_str << "'";
1455 } else if (config.method == GETADDRINFOFORNET) {
Bernie Innocenti9bf749f2018-08-30 08:37:22 +09001456 addrinfo* raw_ai_result = nullptr;
Bernie Innocentic165ce82018-10-16 23:35:28 +09001457 EXPECT_EQ(0, android_getaddrinfofornet(host_name, /*servname=*/nullptr,
1458 /*hints=*/nullptr, BYPASS_NETID, MARK_UNSET,
1459 &raw_ai_result));
Bernie Innocenti9bf749f2018-08-30 08:37:22 +09001460 ai_result.reset(raw_ai_result);
Bernie Innocenti443489e2018-08-10 14:27:23 +09001461
1462 EXPECT_LE(1U, GetNumQueries(dns, host_name));
1463 // Could be A or AAAA
1464 const std::string result_str = ToString(ai_result);
1465 EXPECT_TRUE(result_str == ADDR4 || result_str == ADDR6)
1466 << ", result_str='" << result_str << "'";
1467 } else {
1468 FAIL() << "Unsupported query method: " << config.method;
1469 }
1470
1471 const int tlsQueriesAfter = tls.queries();
1472 EXPECT_EQ(0, tlsQueriesAfter - tlsQueriesBefore);
1473
Bernie Innocenti443489e2018-08-10 14:27:23 +09001474 // Clear per-process resolv netid.
1475 ASSERT_EQ(0, setNetworkForResolv(NETID_UNSET));
1476 tls.stopServer();
1477 dns.clearQueries();
1478 }
Bernie Innocenti443489e2018-08-10 14:27:23 +09001479}
1480
1481TEST_F(ResolverTest, StrictMode_NoTlsServers) {
Mike Yu5ae61542018-10-19 22:11:43 +08001482 const std::vector<uint8_t> NOOP_FINGERPRINT(SHA256_SIZE, 0U);
Xiao Ma7c75f452018-12-11 17:56:32 +09001483 constexpr char cleartext_addr[] = "127.0.0.53";
Bernie Innocenti443489e2018-08-10 14:27:23 +09001484 const std::vector<std::string> servers = { cleartext_addr };
Xiao Ma7c75f452018-12-11 17:56:32 +09001485 constexpr char host_name[] = "strictmode.notlsips.example.com.";
1486 const std::vector<DnsRecord> records = {
1487 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1488 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1489 };
Bernie Innocenti443489e2018-08-10 14:27:23 +09001490
Xiao Ma7c75f452018-12-11 17:56:32 +09001491 test::DNSResponder dns(cleartext_addr);
1492 StartDns(dns, records);
Bernie Innocenti443489e2018-08-10 14:27:23 +09001493
Xiao Ma7c75f452018-12-11 17:56:32 +09001494 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, {},
Bernie Innocenti3e411a32019-01-17 21:28:24 +09001495 "", {base64Encode(NOOP_FINGERPRINT)}));
Bernie Innocenti443489e2018-08-10 14:27:23 +09001496
1497 addrinfo* ai_result = nullptr;
1498 EXPECT_NE(0, getaddrinfo(host_name, nullptr, nullptr, &ai_result));
1499 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
1500}
Luke Huangc68f1b92018-11-21 20:13:38 +08001501
1502namespace {
1503
1504int getAsyncResponse(int fd, int* rcode, u_char* buf, int bufLen) {
1505 struct pollfd wait_fd[1];
1506 wait_fd[0].fd = fd;
1507 wait_fd[0].events = POLLIN;
1508 short revents;
1509 int ret;
1510
1511 ret = poll(wait_fd, 1, -1);
1512 revents = wait_fd[0].revents;
1513 if (revents & POLLIN) {
1514 int n = resNetworkResult(fd, rcode, buf, bufLen);
Luke Huang952d0942018-12-26 16:53:03 +08001515 // Verify that resNetworkResult() closed the fd
1516 char dummy;
1517 EXPECT_EQ(-1, read(fd, &dummy, sizeof dummy));
1518 EXPECT_EQ(EBADF, errno);
Luke Huangc68f1b92018-11-21 20:13:38 +08001519 return n;
1520 }
1521 return -1;
1522}
1523
1524std::string toString(u_char* buf, int bufLen, int ipType) {
1525 ns_msg handle;
1526 int ancount, n = 0;
1527 ns_rr rr;
1528
1529 if (ns_initparse((const uint8_t*) buf, bufLen, &handle) >= 0) {
1530 ancount = ns_msg_count(handle, ns_s_an);
1531 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1532 const u_char* rdata = ns_rr_rdata(rr);
1533 char buffer[INET6_ADDRSTRLEN];
1534 if (inet_ntop(ipType, (const char*) rdata, buffer, sizeof(buffer))) {
1535 return buffer;
1536 }
1537 }
1538 }
1539 return "";
1540}
1541
1542int dns_open_proxy() {
1543 int s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
1544 if (s == -1) {
1545 return -1;
1546 }
1547 const int one = 1;
1548 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
1549
1550 static const struct sockaddr_un proxy_addr = {
1551 .sun_family = AF_UNIX,
1552 .sun_path = "/dev/socket/dnsproxyd",
1553 };
1554
1555 if (TEMP_FAILURE_RETRY(connect(s, (const struct sockaddr*) &proxy_addr, sizeof(proxy_addr))) !=
1556 0) {
1557 close(s);
1558 return -1;
1559 }
1560
1561 return s;
1562}
1563
Luke Huang952d0942018-12-26 16:53:03 +08001564void expectAnswersValid(int fd, int ipType, const std::string& expectedAnswer) {
1565 int rcode = -1;
1566 uint8_t buf[MAXPACKET] = {};
1567
1568 int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
1569 EXPECT_GT(res, 0);
1570 EXPECT_EQ(expectedAnswer, toString(buf, res, ipType));
1571}
1572
1573void expectAnswersNotValid(int fd, int expectedErrno) {
1574 int rcode = -1;
1575 uint8_t buf[MAXPACKET] = {};
1576
1577 int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
1578 EXPECT_EQ(expectedErrno, res);
1579}
1580
Luke Huangc68f1b92018-11-21 20:13:38 +08001581} // namespace
1582
1583TEST_F(ResolverTest, Async_NormalQueryV4V6) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001584 constexpr char listen_addr[] = "127.0.0.4";
1585 constexpr char host_name[] = "howdy.example.com.";
1586 const std::vector<DnsRecord> records = {
1587 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1588 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1589 };
1590
1591 test::DNSResponder dns(listen_addr);
1592 StartDns(dns, records);
Luke Huangc68f1b92018-11-21 20:13:38 +08001593 std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09001594 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huangc68f1b92018-11-21 20:13:38 +08001595
Luke Huang952d0942018-12-26 16:53:03 +08001596 int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1597 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
Luke Huangc68f1b92018-11-21 20:13:38 +08001598 EXPECT_TRUE(fd1 != -1);
1599 EXPECT_TRUE(fd2 != -1);
1600
1601 u_char buf[MAXPACKET] = {};
1602 int rcode;
1603 int res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
1604 EXPECT_GT(res, 0);
1605 EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
1606
1607 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
1608 EXPECT_GT(res, 0);
1609 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
1610
1611 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
1612
1613 // Re-query verify cache works
Luke Huang952d0942018-12-26 16:53:03 +08001614 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1615 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
Luke Huangc68f1b92018-11-21 20:13:38 +08001616
1617 EXPECT_TRUE(fd1 != -1);
1618 EXPECT_TRUE(fd2 != -1);
1619
1620 res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
1621 EXPECT_GT(res, 0);
1622 EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
1623
1624 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
1625 EXPECT_GT(res, 0);
1626 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
1627
1628 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
1629}
1630
1631TEST_F(ResolverTest, Async_BadQuery) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001632 constexpr char listen_addr[] = "127.0.0.4";
1633 constexpr char host_name[] = "howdy.example.com.";
1634 const std::vector<DnsRecord> records = {
1635 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1636 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1637 };
1638
1639 test::DNSResponder dns(listen_addr);
1640 StartDns(dns, records);
Luke Huangc68f1b92018-11-21 20:13:38 +08001641 std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09001642 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huangc68f1b92018-11-21 20:13:38 +08001643
1644 static struct {
1645 int fd;
1646 const char* dname;
1647 const int queryType;
1648 const int expectRcode;
1649 } kTestData[] = {
Luke Huang952d0942018-12-26 16:53:03 +08001650 {-1, "", ns_t_aaaa, 0},
1651 {-1, "as65ass46", ns_t_aaaa, 0},
1652 {-1, "454564564564", ns_t_aaaa, 0},
1653 {-1, "h645235", ns_t_a, 0},
1654 {-1, "www.google.com", ns_t_a, 0},
Luke Huangc68f1b92018-11-21 20:13:38 +08001655 };
1656
1657 for (auto& td : kTestData) {
1658 SCOPED_TRACE(td.dname);
Luke Huang952d0942018-12-26 16:53:03 +08001659 td.fd = resNetworkQuery(TEST_NETID, td.dname, ns_c_in, td.queryType, 0);
Luke Huangc68f1b92018-11-21 20:13:38 +08001660 EXPECT_TRUE(td.fd != -1);
1661 }
1662
1663 // dns_responder return empty resp(packet only contains query part) with no error currently
1664 for (const auto& td : kTestData) {
1665 u_char buf[MAXPACKET] = {};
1666 int rcode;
1667 SCOPED_TRACE(td.dname);
1668 int res = getAsyncResponse(td.fd, &rcode, buf, MAXPACKET);
1669 EXPECT_GT(res, 0);
1670 EXPECT_EQ(rcode, td.expectRcode);
1671 }
1672}
1673
1674TEST_F(ResolverTest, Async_EmptyAnswer) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001675 constexpr char listen_addr[] = "127.0.0.4";
1676 constexpr char host_name[] = "howdy.example.com.";
1677 const std::vector<DnsRecord> records = {
1678 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1679 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1680 };
1681
1682 test::DNSResponder dns(listen_addr);
1683 StartDns(dns, records);
Luke Huangc68f1b92018-11-21 20:13:38 +08001684 std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09001685 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huangc68f1b92018-11-21 20:13:38 +08001686
Luke Huang26a0e2a2018-12-18 16:44:41 +08001687 // TODO: Disable retry to make this test explicit.
1688 auto& cv = dns.getCv();
1689 auto& cvMutex = dns.getCvMutex();
1690 int fd1;
1691 // Wait on the condition variable to ensure that the DNS server has handled our first query.
1692 {
1693 std::unique_lock lk(cvMutex);
Luke Huang952d0942018-12-26 16:53:03 +08001694 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
Luke Huang26a0e2a2018-12-18 16:44:41 +08001695 EXPECT_TRUE(fd1 != -1);
1696 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lk, std::chrono::seconds(1)));
1697 }
Luke Huangc68f1b92018-11-21 20:13:38 +08001698
Luke Huangc68f1b92018-11-21 20:13:38 +08001699 dns.setResponseProbability(0.0);
Luke Huangc68f1b92018-11-21 20:13:38 +08001700
Luke Huang952d0942018-12-26 16:53:03 +08001701 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
Luke Huangc68f1b92018-11-21 20:13:38 +08001702 EXPECT_TRUE(fd2 != -1);
1703
Luke Huang952d0942018-12-26 16:53:03 +08001704 int fd3 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
Luke Huangc68f1b92018-11-21 20:13:38 +08001705 EXPECT_TRUE(fd3 != -1);
1706
Luke Huang26a0e2a2018-12-18 16:44:41 +08001707 uint8_t buf[MAXPACKET] = {};
Luke Huangc68f1b92018-11-21 20:13:38 +08001708 int rcode;
1709
Luke Huang26a0e2a2018-12-18 16:44:41 +08001710 // expect no response
1711 int res = getAsyncResponse(fd3, &rcode, buf, MAXPACKET);
1712 EXPECT_EQ(-ETIMEDOUT, res);
Luke Huangc68f1b92018-11-21 20:13:38 +08001713
Luke Huang26a0e2a2018-12-18 16:44:41 +08001714 // expect no response
Luke Huangc68f1b92018-11-21 20:13:38 +08001715 memset(buf, 0, MAXPACKET);
Luke Huang26a0e2a2018-12-18 16:44:41 +08001716 res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
1717 EXPECT_EQ(-ETIMEDOUT, res);
Luke Huangc68f1b92018-11-21 20:13:38 +08001718
Luke Huangc68f1b92018-11-21 20:13:38 +08001719 dns.setResponseProbability(1.0);
Luke Huangc68f1b92018-11-21 20:13:38 +08001720
Luke Huang952d0942018-12-26 16:53:03 +08001721 int fd4 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
Luke Huangc68f1b92018-11-21 20:13:38 +08001722 EXPECT_TRUE(fd4 != -1);
1723
1724 memset(buf, 0, MAXPACKET);
1725 res = getAsyncResponse(fd4, &rcode, buf, MAXPACKET);
1726 EXPECT_GT(res, 0);
1727 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
1728
1729 memset(buf, 0, MAXPACKET);
1730 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
1731 EXPECT_GT(res, 0);
1732 EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
1733}
1734
1735TEST_F(ResolverTest, Async_MalformedQuery) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001736 constexpr char listen_addr[] = "127.0.0.4";
1737 constexpr char host_name[] = "howdy.example.com.";
1738 const std::vector<DnsRecord> records = {
1739 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1740 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1741 };
1742
1743 test::DNSResponder dns(listen_addr);
1744 StartDns(dns, records);
Luke Huangc68f1b92018-11-21 20:13:38 +08001745 std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09001746 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huangc68f1b92018-11-21 20:13:38 +08001747
1748 int fd = dns_open_proxy();
1749 EXPECT_TRUE(fd > 0);
1750
1751 const std::string badMsg = "16-52512#";
Xiao Ma7c75f452018-12-11 17:56:32 +09001752 static const struct {
Luke Huangc68f1b92018-11-21 20:13:38 +08001753 const std::string cmd;
1754 const int expectErr;
1755 } kTestData[] = {
Luke Huang952d0942018-12-26 16:53:03 +08001756 // Too few arguments
Luke Huangc68f1b92018-11-21 20:13:38 +08001757 {"resnsend " + badMsg + '\0', -EINVAL},
1758 // Bad netId
Luke Huang952d0942018-12-26 16:53:03 +08001759 {"resnsend badnetId 0 " + badMsg + '\0', -EINVAL},
Luke Huangc68f1b92018-11-21 20:13:38 +08001760 // Bad raw data
Luke Huang952d0942018-12-26 16:53:03 +08001761 {"resnsend " + std::to_string(TEST_NETID) + " 0 " + badMsg + '\0', -EILSEQ},
Luke Huangc68f1b92018-11-21 20:13:38 +08001762 };
1763
1764 for (unsigned int i = 0; i < std::size(kTestData); i++) {
1765 auto& td = kTestData[i];
1766 SCOPED_TRACE(td.cmd);
1767 ssize_t rc = TEMP_FAILURE_RETRY(write(fd, td.cmd.c_str(), td.cmd.size()));
1768 EXPECT_EQ(rc, static_cast<ssize_t>(td.cmd.size()));
1769
1770 int32_t tmp;
1771 rc = TEMP_FAILURE_RETRY(read(fd, &tmp, sizeof(tmp)));
1772 EXPECT_TRUE(rc > 0);
1773 EXPECT_EQ(static_cast<int>(ntohl(tmp)), td.expectErr);
1774 }
1775 // Normal query with answer buffer
1776 // This is raw data of query "howdy.example.com" type 1 class 1
1777 std::string query = "81sBAAABAAAAAAAABWhvd2R5B2V4YW1wbGUDY29tAAABAAE=";
Luke Huang952d0942018-12-26 16:53:03 +08001778 std::string cmd = "resnsend " + std::to_string(TEST_NETID) + " 0 " + query + '\0';
Luke Huangc68f1b92018-11-21 20:13:38 +08001779 ssize_t rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
1780 EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
1781
1782 u_char smallBuf[1] = {};
1783 int rcode;
1784 rc = getAsyncResponse(fd, &rcode, smallBuf, 1);
Luke Huang952d0942018-12-26 16:53:03 +08001785 EXPECT_EQ(-EMSGSIZE, rc);
Luke Huangc68f1b92018-11-21 20:13:38 +08001786
1787 // Do the normal test with large buffer again
1788 fd = dns_open_proxy();
1789 EXPECT_TRUE(fd > 0);
1790 rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
1791 EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
1792 u_char buf[MAXPACKET] = {};
1793 rc = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
1794 EXPECT_EQ("1.2.3.4", toString(buf, rc, AF_INET));
Mike Yu5b9ffb22018-12-02 17:54:29 +09001795}
1796
Luke Huang952d0942018-12-26 16:53:03 +08001797TEST_F(ResolverTest, Async_CacheFlags) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001798 constexpr char listen_addr[] = "127.0.0.4";
1799 constexpr char host_name[] = "howdy.example.com.";
1800 const std::vector<DnsRecord> records = {
1801 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1802 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1803 };
1804
1805 test::DNSResponder dns(listen_addr);
1806 StartDns(dns, records);
Luke Huang952d0942018-12-26 16:53:03 +08001807 std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09001808 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huang952d0942018-12-26 16:53:03 +08001809
1810 // ANDROID_RESOLV_NO_CACHE_STORE
1811 int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1812 ANDROID_RESOLV_NO_CACHE_STORE);
1813 EXPECT_TRUE(fd1 != -1);
1814 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1815 ANDROID_RESOLV_NO_CACHE_STORE);
1816 EXPECT_TRUE(fd2 != -1);
1817 int fd3 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1818 ANDROID_RESOLV_NO_CACHE_STORE);
1819 EXPECT_TRUE(fd3 != -1);
1820
1821 expectAnswersValid(fd3, AF_INET, "1.2.3.4");
1822 expectAnswersValid(fd2, AF_INET, "1.2.3.4");
1823 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
1824
1825 // No cache exists, expect 3 queries
1826 EXPECT_EQ(3U, GetNumQueries(dns, host_name));
1827
1828 // Re-query and cache
1829 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1830
1831 EXPECT_TRUE(fd1 != -1);
1832
1833 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
1834
1835 // Now we have cache, expect 4 queries
1836 EXPECT_EQ(4U, GetNumQueries(dns, host_name));
1837
1838 // ANDROID_RESOLV_NO_CACHE_LOOKUP
1839 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1840 ANDROID_RESOLV_NO_CACHE_LOOKUP);
1841 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1842 ANDROID_RESOLV_NO_CACHE_LOOKUP);
1843
1844 EXPECT_TRUE(fd1 != -1);
1845 EXPECT_TRUE(fd2 != -1);
1846
1847 expectAnswersValid(fd2, AF_INET, "1.2.3.4");
1848 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
1849
1850 // Skip cache, expect 6 queries
1851 EXPECT_EQ(6U, GetNumQueries(dns, host_name));
1852
1853 // Re-query verify cache works
1854 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1855 ANDROID_RESOLV_NO_CACHE_STORE);
1856 EXPECT_TRUE(fd1 != -1);
1857 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
1858
1859 // Cache hits, expect still 6 queries
1860 EXPECT_EQ(6U, GetNumQueries(dns, host_name));
1861}
1862
1863TEST_F(ResolverTest, Async_NoRetryFlag) {
Xiao Ma7c75f452018-12-11 17:56:32 +09001864 constexpr char listen_addr[] = "127.0.0.4";
1865 constexpr char host_name[] = "howdy.example.com.";
1866 const std::vector<DnsRecord> records = {
1867 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1868 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1869 };
1870
1871 test::DNSResponder dns(listen_addr);
1872 StartDns(dns, records);
Luke Huang952d0942018-12-26 16:53:03 +08001873 std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09001874 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huang952d0942018-12-26 16:53:03 +08001875
1876 dns.setResponseProbability(0.0);
1877
1878 int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1879 ANDROID_RESOLV_NO_RETRY);
1880 EXPECT_TRUE(fd1 != -1);
1881
1882 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa,
1883 ANDROID_RESOLV_NO_RETRY);
1884 EXPECT_TRUE(fd2 != -1);
1885
1886 // expect no response
1887 expectAnswersNotValid(fd1, -ETIMEDOUT);
1888 expectAnswersNotValid(fd2, -ETIMEDOUT);
1889
1890 // No retry case, expect 2 queries
1891 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
1892
1893 dns.clearQueries();
1894
1895 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1896 EXPECT_TRUE(fd1 != -1);
1897
1898 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
1899 EXPECT_TRUE(fd2 != -1);
1900
1901 // expect no response
1902 expectAnswersNotValid(fd1, -ETIMEDOUT);
1903 expectAnswersNotValid(fd2, -ETIMEDOUT);
1904
1905 // Retry case, expect 4 queries
1906 EXPECT_EQ(4U, GetNumQueries(dns, host_name));
1907}
1908
Mike Yu5b9ffb22018-12-02 17:54:29 +09001909// This test checks that the resolver should not generate the request containing OPT RR when using
Ken Chenbfd32022019-01-02 14:59:38 +08001910// cleartext DNS. If we query the DNS server not supporting EDNS0 and it reponds with
1911// FORMERR_ON_EDNS, we will fallback to no EDNS0 and try again. If the server does no response, we
1912// won't retry so that we get no answer.
Mike Yu5b9ffb22018-12-02 17:54:29 +09001913TEST_F(ResolverTest, BrokenEdns) {
1914 typedef test::DNSResponder::Edns Edns;
1915 enum ExpectResult { EXPECT_FAILURE, EXPECT_SUCCESS };
1916
1917 const char OFF[] = "off";
1918 const char OPPORTUNISTIC_UDP[] = "opportunistic_udp";
1919 const char OPPORTUNISTIC_TLS[] = "opportunistic_tls";
1920 const char STRICT[] = "strict";
1921 const char GETHOSTBYNAME[] = "gethostbyname";
1922 const char GETADDRINFO[] = "getaddrinfo";
1923 const std::vector<uint8_t> NOOP_FINGERPRINT(SHA256_SIZE, 0U);
1924 const char ADDR4[] = "192.0.2.1";
1925 const char CLEARTEXT_ADDR[] = "127.0.0.53";
1926 const char CLEARTEXT_PORT[] = "53";
1927 const char TLS_PORT[] = "853";
1928 const std::vector<std::string> servers = { CLEARTEXT_ADDR };
1929
1930 test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, 250, ns_rcode::ns_r_servfail);
1931 ASSERT_TRUE(dns.startServer());
1932
1933 test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
1934
1935 static const struct TestConfig {
1936 std::string mode;
1937 std::string method;
1938 Edns edns;
1939 ExpectResult expectResult;
1940
1941 std::string asHostName() const {
1942 const char* ednsString;
1943 switch (edns) {
1944 case Edns::ON:
1945 ednsString = "ednsOn";
1946 break;
Ken Chenbfd32022019-01-02 14:59:38 +08001947 case Edns::FORMERR_ON_EDNS:
Mike Yu5b9ffb22018-12-02 17:54:29 +09001948 ednsString = "ednsFormerr";
1949 break;
1950 case Edns::DROP:
1951 ednsString = "ednsDrop";
1952 break;
1953 default:
1954 ednsString = "";
1955 break;
1956 }
1957 return StringPrintf("%s.%s.%s.", mode.c_str(), method.c_str(), ednsString);
1958 }
1959 } testConfigs[] = {
1960 // In OPPORTUNISTIC_TLS, we get no answer if the DNS server supports TLS but not EDNS0.
1961 // Could such server exist? if so, we might need to fallback to query cleartext DNS.
1962 // Another thing is that {OPPORTUNISTIC_TLS, Edns::DROP} and {STRICT, Edns::DROP} are
1963 // commented out since TLS timeout is not configurable.
1964 // TODO: Uncomment them after TLS timeout is configurable.
1965 {OFF, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
1966 {OPPORTUNISTIC_UDP, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
1967 {OPPORTUNISTIC_TLS, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
1968 {STRICT, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
Ken Chenbfd32022019-01-02 14:59:38 +08001969 {OFF, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
1970 {OPPORTUNISTIC_UDP, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
1971 {OPPORTUNISTIC_TLS, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
1972 {STRICT, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
Mike Yu5b9ffb22018-12-02 17:54:29 +09001973 {OFF, GETHOSTBYNAME, Edns::DROP, EXPECT_SUCCESS},
1974 {OPPORTUNISTIC_UDP, GETHOSTBYNAME, Edns::DROP, EXPECT_SUCCESS},
1975 //{OPPORTUNISTIC_TLS, GETHOSTBYNAME, Edns::DROP, EXPECT_FAILURE},
1976 //{STRICT, GETHOSTBYNAME, Edns::DROP, EXPECT_FAILURE},
1977 {OFF, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
1978 {OPPORTUNISTIC_UDP, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
1979 {OPPORTUNISTIC_TLS, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
1980 {STRICT, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
Ken Chenbfd32022019-01-02 14:59:38 +08001981 {OFF, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
1982 {OPPORTUNISTIC_UDP, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
1983 {OPPORTUNISTIC_TLS, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
1984 {STRICT, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
Mike Yu5b9ffb22018-12-02 17:54:29 +09001985 {OFF, GETADDRINFO, Edns::DROP, EXPECT_SUCCESS},
1986 {OPPORTUNISTIC_UDP, GETADDRINFO, Edns::DROP, EXPECT_SUCCESS},
1987 //{OPPORTUNISTIC_TLS, GETADDRINFO, Edns::DROP, EXPECT_FAILURE},
1988 //{STRICT, GETADDRINFO, Edns::DROP, EXPECT_FAILURE},
1989 };
1990
1991 for (const auto& config : testConfigs) {
1992 const std::string testHostName = config.asHostName();
1993 SCOPED_TRACE(testHostName);
1994
1995 const char* host_name = testHostName.c_str();
1996 dns.addMapping(host_name, ns_type::ns_t_a, ADDR4);
1997 dns.setEdns(config.edns);
1998
1999 if (config.mode == OFF) {
Xiao Ma7c75f452018-12-11 17:56:32 +09002000 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Mike Yu5b9ffb22018-12-02 17:54:29 +09002001 } else if (config.mode == OPPORTUNISTIC_UDP) {
Xiao Ma7c75f452018-12-11 17:56:32 +09002002 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
2003 kDefaultParams, "", {}));
Mike Yu5b9ffb22018-12-02 17:54:29 +09002004 } else if (config.mode == OPPORTUNISTIC_TLS) {
2005 ASSERT_TRUE(tls.startServer());
Xiao Ma7c75f452018-12-11 17:56:32 +09002006 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
2007 kDefaultParams, "", {}));
Mike Yu5b9ffb22018-12-02 17:54:29 +09002008 // Wait for validation to complete.
2009 EXPECT_TRUE(tls.waitForQueries(1, 5000));
2010 } else if (config.mode == STRICT) {
2011 ASSERT_TRUE(tls.startServer());
Xiao Ma7c75f452018-12-11 17:56:32 +09002012 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
2013 kDefaultParams, "",
Bernie Innocenti3e411a32019-01-17 21:28:24 +09002014 {base64Encode(tls.fingerprint())}));
Mike Yu5b9ffb22018-12-02 17:54:29 +09002015 // Wait for validation to complete.
2016 EXPECT_TRUE(tls.waitForQueries(1, 5000));
2017 }
2018
2019 if (config.method == GETHOSTBYNAME) {
2020 const hostent* h_result = gethostbyname(host_name);
2021 if (config.expectResult == EXPECT_SUCCESS) {
2022 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2023 ASSERT_TRUE(h_result != nullptr);
2024 ASSERT_EQ(4, h_result->h_length);
2025 ASSERT_FALSE(h_result->h_addr_list[0] == nullptr);
2026 EXPECT_EQ(ADDR4, ToString(h_result));
2027 EXPECT_TRUE(h_result->h_addr_list[1] == nullptr);
2028 } else {
2029 EXPECT_EQ(0U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
2030 ASSERT_TRUE(h_result == nullptr);
2031 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2032 }
2033 } else if (config.method == GETADDRINFO) {
2034 ScopedAddrinfo ai_result;
2035 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2036 ai_result = safe_getaddrinfo(host_name, nullptr, &hints);
2037 if (config.expectResult == EXPECT_SUCCESS) {
2038 EXPECT_TRUE(ai_result != nullptr);
2039 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2040 const std::string result_str = ToString(ai_result);
2041 EXPECT_EQ(ADDR4, result_str);
2042 } else {
2043 EXPECT_TRUE(ai_result == nullptr);
2044 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
2045 }
2046 } else {
2047 FAIL() << "Unsupported query method: " << config.method;
2048 }
2049
2050 tls.stopServer();
2051 dns.clearQueries();
2052 }
2053
2054 dns.stopServer();
2055}
nuccachenf52f7a52018-07-17 18:07:23 +08002056
Ken Chenbfd32022019-01-02 14:59:38 +08002057// DNS-over-TLS validation success, but server does not respond to TLS query after a while.
2058// Resolver should have a reasonable number of retries instead of spinning forever. We don't have
2059// an efficient way to know if resolver is stuck in an infinite loop. However, test case will be
2060// failed due to timeout.
2061TEST_F(ResolverTest, UnstableTls) {
2062 const char CLEARTEXT_ADDR[] = "127.0.0.53";
2063 const char CLEARTEXT_PORT[] = "53";
2064 const char TLS_PORT[] = "853";
2065 const char* host_name1 = "nonexistent1.example.com.";
2066 const char* host_name2 = "nonexistent2.example.com.";
2067 const std::vector<std::string> servers = {CLEARTEXT_ADDR};
2068
2069 test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, 250, ns_rcode::ns_r_servfail);
2070 ASSERT_TRUE(dns.startServer());
2071 dns.setEdns(test::DNSResponder::Edns::FORMERR_ON_EDNS);
2072 test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2073 ASSERT_TRUE(tls.startServer());
Bernie Innocenti3e411a32019-01-17 21:28:24 +09002074 ASSERT_TRUE(
Xiao Ma7c75f452018-12-11 17:56:32 +09002075 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
Ken Chenbfd32022019-01-02 14:59:38 +08002076 // Wait for validation complete.
2077 EXPECT_TRUE(tls.waitForQueries(1, 5000));
2078 // Shutdown TLS server to get an error. It's similar to no response case but without waiting.
2079 tls.stopServer();
2080
2081 const hostent* h_result = gethostbyname(host_name1);
2082 EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
2083 ASSERT_TRUE(h_result == nullptr);
2084 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2085
2086 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2087 ScopedAddrinfo ai_result = safe_getaddrinfo(host_name2, nullptr, &hints);
2088 EXPECT_TRUE(ai_result == nullptr);
2089 EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
2090}
2091
2092// DNS-over-TLS validation success, but server does not respond to TLS query after a while.
2093// Moreover, server responds RCODE=FORMERR even on non-EDNS query.
2094TEST_F(ResolverTest, BogusDnsServer) {
2095 const char CLEARTEXT_ADDR[] = "127.0.0.53";
2096 const char CLEARTEXT_PORT[] = "53";
2097 const char TLS_PORT[] = "853";
2098 const char* host_name1 = "nonexistent1.example.com.";
2099 const char* host_name2 = "nonexistent2.example.com.";
2100 const std::vector<std::string> servers = {CLEARTEXT_ADDR};
2101
2102 test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, 250, ns_rcode::ns_r_servfail);
2103 ASSERT_TRUE(dns.startServer());
2104 test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2105 ASSERT_TRUE(tls.startServer());
Bernie Innocenti3e411a32019-01-17 21:28:24 +09002106 ASSERT_TRUE(
Xiao Ma7c75f452018-12-11 17:56:32 +09002107 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
Ken Chenbfd32022019-01-02 14:59:38 +08002108 // Wait for validation complete.
2109 EXPECT_TRUE(tls.waitForQueries(1, 5000));
2110 // Shutdown TLS server to get an error. It's similar to no response case but without waiting.
2111 tls.stopServer();
2112 dns.setEdns(test::DNSResponder::Edns::FORMERR_UNCOND);
2113
2114 const hostent* h_result = gethostbyname(host_name1);
2115 EXPECT_EQ(0U, GetNumQueries(dns, host_name1));
2116 ASSERT_TRUE(h_result == nullptr);
2117 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2118
2119 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2120 ScopedAddrinfo ai_result = safe_getaddrinfo(host_name2, nullptr, &hints);
2121 EXPECT_TRUE(ai_result == nullptr);
2122 EXPECT_EQ(0U, GetNumQueries(dns, host_name2));
2123}
2124
nuccachenf52f7a52018-07-17 18:07:23 +08002125TEST_F(ResolverTest, GetAddrInfo_Dns64Synthesize) {
2126 constexpr char listen_addr[] = "::1";
2127 constexpr char listen_addr2[] = "127.0.0.5";
nuccachenf52f7a52018-07-17 18:07:23 +08002128 constexpr char dns64_name[] = "ipv4only.arpa.";
2129 constexpr char host_name[] = "v4only.example.com.";
Xiao Ma7c75f452018-12-11 17:56:32 +09002130 const std::vector<DnsRecord> records = {
2131 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2132 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2133 };
nuccachenf52f7a52018-07-17 18:07:23 +08002134
Xiao Ma7c75f452018-12-11 17:56:32 +09002135 test::DNSResponder dns(listen_addr);
2136 test::DNSResponder dns2(listen_addr2);
2137 StartDns(dns, records);
2138 StartDns(dns2, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
nuccachenf52f7a52018-07-17 18:07:23 +08002139
2140 std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002141 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002142
2143 // Wait for detecting prefix to complete.
2144 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2145
2146 // hints are necessary in order to let netd know which type of addresses the caller is
2147 // interested in.
Xiao Ma7c75f452018-12-11 17:56:32 +09002148 const addrinfo hints = {.ai_family = AF_UNSPEC};
nuccachenf52f7a52018-07-17 18:07:23 +08002149 ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, &hints);
2150 EXPECT_TRUE(result != nullptr);
2151 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2152
2153 std::string result_str = ToString(result);
2154 EXPECT_EQ(result_str, "64:ff9b::102:304");
2155
2156 // Let's test the case when there's an IPv4 resolver.
2157 servers = {listen_addr, listen_addr2};
Xiao Ma7c75f452018-12-11 17:56:32 +09002158 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002159 dns.clearQueries();
2160 dns2.clearQueries();
2161
2162 // Netd doesn't detect prefix because there has an IPv4 resolver but all IPv6 resolvers.
2163 EXPECT_FALSE(WaitForPrefix64Detected(TEST_NETID, 1000));
2164
2165 result = safe_getaddrinfo("v4only", nullptr, &hints);
2166 EXPECT_TRUE(result != nullptr);
2167 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2168
2169 result_str = ToString(result);
2170 EXPECT_EQ(result_str, "1.2.3.4");
2171}
2172
nuccachenf52f7a52018-07-17 18:07:23 +08002173TEST_F(ResolverTest, GetAddrInfo_Dns64QuerySpecified) {
2174 constexpr char listen_addr[] = "::1";
nuccachenf52f7a52018-07-17 18:07:23 +08002175 constexpr char dns64_name[] = "ipv4only.arpa.";
2176 constexpr char host_name[] = "v4only.example.com.";
Xiao Ma7c75f452018-12-11 17:56:32 +09002177 const std::vector<DnsRecord> records = {
2178 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2179 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2180 };
nuccachenf52f7a52018-07-17 18:07:23 +08002181
Xiao Ma7c75f452018-12-11 17:56:32 +09002182 test::DNSResponder dns(listen_addr);
2183 StartDns(dns, records);
nuccachenf52f7a52018-07-17 18:07:23 +08002184 const std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002185 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002186
2187 // Wait for detecting prefix to complete.
2188 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2189
2190 // Ensure to synthesize AAAA if AF_INET6 is specified, and not to synthesize AAAA
2191 // in AF_INET case.
2192 addrinfo hints;
2193 memset(&hints, 0, sizeof(hints));
2194 hints.ai_family = AF_INET6;
2195 ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, &hints);
2196 EXPECT_TRUE(result != nullptr);
2197 std::string result_str = ToString(result);
2198 EXPECT_EQ(result_str, "64:ff9b::102:304");
2199
2200 hints.ai_family = AF_INET;
2201 result = safe_getaddrinfo("v4only", nullptr, &hints);
2202 EXPECT_TRUE(result != nullptr);
2203 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2204 result_str = ToString(result);
2205 EXPECT_EQ(result_str, "1.2.3.4");
2206}
nuccachenf52f7a52018-07-17 18:07:23 +08002207
2208TEST_F(ResolverTest, GetAddrInfo_Dns64QueryUnspecifiedV6) {
2209 constexpr char listen_addr[] = "::1";
nuccachenf52f7a52018-07-17 18:07:23 +08002210 constexpr char dns64_name[] = "ipv4only.arpa.";
2211 constexpr char host_name[] = "v4v6.example.com.";
Xiao Ma7c75f452018-12-11 17:56:32 +09002212 const std::vector<DnsRecord> records = {
2213 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2214 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2215 {host_name, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
2216 };
nuccachenf52f7a52018-07-17 18:07:23 +08002217
Xiao Ma7c75f452018-12-11 17:56:32 +09002218 test::DNSResponder dns(listen_addr);
2219 StartDns(dns, records);
nuccachenf52f7a52018-07-17 18:07:23 +08002220 const std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002221 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002222
2223 // Wait for detecting prefix to complete.
2224 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2225
Xiao Ma7c75f452018-12-11 17:56:32 +09002226 const addrinfo hints = {.ai_family = AF_UNSPEC};
nuccachenf52f7a52018-07-17 18:07:23 +08002227 ScopedAddrinfo result = safe_getaddrinfo("v4v6", nullptr, &hints);
2228 EXPECT_TRUE(result != nullptr);
2229 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2230
2231 // In AF_UNSPEC case, do not synthesize AAAA if there's at least one AAAA answer.
Xiao Ma7c75f452018-12-11 17:56:32 +09002232 const std::vector<std::string> result_strs = ToStrings(result);
nuccachenf52f7a52018-07-17 18:07:23 +08002233 for (const auto& str : result_strs) {
2234 EXPECT_TRUE(str == "1.2.3.4" || str == "2001:db8::102:304")
2235 << ", result_str='" << str << "'";
2236 }
2237}
2238
2239TEST_F(ResolverTest, GetAddrInfo_Dns64QueryUnspecifiedNoV6) {
2240 constexpr char listen_addr[] = "::1";
nuccachenf52f7a52018-07-17 18:07:23 +08002241 constexpr char dns64_name[] = "ipv4only.arpa.";
2242 constexpr char host_name[] = "v4v6.example.com.";
Xiao Ma7c75f452018-12-11 17:56:32 +09002243 const std::vector<DnsRecord> records = {
2244 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2245 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2246 };
nuccachenf52f7a52018-07-17 18:07:23 +08002247
Xiao Ma7c75f452018-12-11 17:56:32 +09002248 test::DNSResponder dns(listen_addr);
2249 StartDns(dns, records);
nuccachenf52f7a52018-07-17 18:07:23 +08002250 const std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002251 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002252
2253 // Wait for detecting prefix to complete.
2254 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2255
Xiao Ma7c75f452018-12-11 17:56:32 +09002256 const addrinfo hints = {.ai_family = AF_UNSPEC};
nuccachenf52f7a52018-07-17 18:07:23 +08002257 ScopedAddrinfo result = safe_getaddrinfo("v4v6", nullptr, &hints);
2258 EXPECT_TRUE(result != nullptr);
2259 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2260
2261 // In AF_UNSPEC case, synthesize AAAA if there's no AAAA answer.
2262 std::string result_str = ToString(result);
2263 EXPECT_EQ(result_str, "64:ff9b::102:304");
2264}
2265
2266TEST_F(ResolverTest, GetAddrInfo_Dns64QuerySpecialUseIPv4Addresses) {
2267 constexpr char THIS_NETWORK[] = "this_network";
2268 constexpr char LOOPBACK[] = "loopback";
2269 constexpr char LINK_LOCAL[] = "link_local";
2270 constexpr char MULTICAST[] = "multicast";
2271 constexpr char LIMITED_BROADCAST[] = "limited_broadcast";
2272
2273 constexpr char ADDR_THIS_NETWORK[] = "0.0.0.1";
2274 constexpr char ADDR_LOOPBACK[] = "127.0.0.1";
2275 constexpr char ADDR_LINK_LOCAL[] = "169.254.0.1";
2276 constexpr char ADDR_MULTICAST[] = "224.0.0.1";
2277 constexpr char ADDR_LIMITED_BROADCAST[] = "255.255.255.255";
2278
2279 constexpr char listen_addr[] = "::1";
nuccachenf52f7a52018-07-17 18:07:23 +08002280 constexpr char dns64_name[] = "ipv4only.arpa.";
2281
Xiao Ma7c75f452018-12-11 17:56:32 +09002282 test::DNSResponder dns(listen_addr);
2283 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
nuccachenf52f7a52018-07-17 18:07:23 +08002284 const std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002285 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002286
2287 // Wait for detecting prefix to complete.
2288 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2289
2290 static const struct TestConfig {
2291 std::string name;
2292 std::string addr;
2293
2294 std::string asHostName() const { return StringPrintf("%s.example.com.", name.c_str()); }
2295 } testConfigs[]{
2296 {THIS_NETWORK, ADDR_THIS_NETWORK},
2297 {LOOPBACK, ADDR_LOOPBACK},
2298 {LINK_LOCAL, ADDR_LINK_LOCAL},
2299 {MULTICAST, ADDR_MULTICAST},
2300 {LIMITED_BROADCAST, ADDR_LIMITED_BROADCAST}
2301 };
2302
2303 for (const auto& config : testConfigs) {
2304 const std::string testHostName = config.asHostName();
2305 SCOPED_TRACE(testHostName);
2306
2307 const char* host_name = testHostName.c_str();
2308 dns.addMapping(host_name, ns_type::ns_t_a, config.addr.c_str());
2309
2310 addrinfo hints;
2311 memset(&hints, 0, sizeof(hints));
2312 hints.ai_family = AF_INET6;
2313 ScopedAddrinfo result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
2314 // In AF_INET6 case, don't return IPv4 answers
2315 EXPECT_TRUE(result == nullptr);
2316 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2317 dns.clearQueries();
2318
2319 memset(&hints, 0, sizeof(hints));
2320 hints.ai_family = AF_UNSPEC;
2321 result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
2322 EXPECT_TRUE(result != nullptr);
2323 // Expect IPv6 query only. IPv4 answer has been cached in previous query.
2324 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2325 // In AF_UNSPEC case, don't synthesize special use IPv4 address.
2326 std::string result_str = ToString(result);
2327 EXPECT_EQ(result_str, config.addr.c_str());
2328 dns.clearQueries();
2329 }
2330}
2331
2332TEST_F(ResolverTest, GetAddrInfo_Dns64QueryWithNullArgumentHints) {
2333 constexpr char listen_addr[] = "::1";
nuccachenf52f7a52018-07-17 18:07:23 +08002334 constexpr char dns64_name[] = "ipv4only.arpa.";
2335 constexpr char host_name[] = "v4only.example.com.";
2336 constexpr char host_name2[] = "v4v6.example.com.";
Xiao Ma7c75f452018-12-11 17:56:32 +09002337 const std::vector<DnsRecord> records = {
2338 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2339 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2340 {host_name2, ns_type::ns_t_a, "1.2.3.4"},
2341 {host_name2, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
2342 };
nuccachenf52f7a52018-07-17 18:07:23 +08002343
Xiao Ma7c75f452018-12-11 17:56:32 +09002344 test::DNSResponder dns(listen_addr);
2345 StartDns(dns, records);
nuccachenf52f7a52018-07-17 18:07:23 +08002346 const std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002347 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002348
2349 // Wait for detecting prefix to complete.
2350 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2351
2352 // Assign argument hints of getaddrinfo() as null is equivalent to set ai_family AF_UNSPEC.
2353 // In AF_UNSPEC case, synthesize AAAA if there has A answer only.
2354 ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, nullptr);
2355 EXPECT_TRUE(result != nullptr);
2356 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2357 std::string result_str = ToString(result);
2358 EXPECT_EQ(result_str, "64:ff9b::102:304");
2359 dns.clearQueries();
2360
2361 // In AF_UNSPEC case, do not synthesize AAAA if there's at least one AAAA answer.
2362 result = safe_getaddrinfo("v4v6", nullptr, nullptr);
2363 EXPECT_TRUE(result != nullptr);
2364 EXPECT_LE(2U, GetNumQueries(dns, host_name2));
2365 std::vector<std::string> result_strs = ToStrings(result);
2366 for (const auto& str : result_strs) {
2367 EXPECT_TRUE(str == "1.2.3.4" || str == "2001:db8::102:304")
2368 << ", result_str='" << str << "'";
2369 }
2370}
2371
2372TEST_F(ResolverTest, GetAddrInfo_Dns64QueryNullArgumentNode) {
2373 constexpr char ADDR_ANYADDR_V4[] = "0.0.0.0";
2374 constexpr char ADDR_ANYADDR_V6[] = "::";
2375 constexpr char ADDR_LOCALHOST_V4[] = "127.0.0.1";
2376 constexpr char ADDR_LOCALHOST_V6[] = "::1";
2377
2378 constexpr char PORT_NAME_HTTP[] = "http";
2379 constexpr char PORT_NUMBER_HTTP[] = "80";
2380
2381 constexpr char listen_addr[] = "::1";
nuccachenf52f7a52018-07-17 18:07:23 +08002382 constexpr char dns64_name[] = "ipv4only.arpa.";
2383
Xiao Ma7c75f452018-12-11 17:56:32 +09002384 test::DNSResponder dns(listen_addr);
2385 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
nuccachenf52f7a52018-07-17 18:07:23 +08002386 const std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002387 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002388
2389 // Wait for detecting prefix to complete.
2390 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2391
2392 // If node is null, return address is listed by libc/getaddrinfo.c as follows.
2393 // - passive socket -> anyaddr (0.0.0.0 or ::)
2394 // - non-passive socket -> localhost (127.0.0.1 or ::1)
2395 static const struct TestConfig {
2396 int flag;
2397 std::string addr_v4;
2398 std::string addr_v6;
2399
2400 std::string asParameters() const {
2401 return StringPrintf("flag=%d, addr_v4=%s, addr_v6=%s", flag, addr_v4.c_str(),
2402 addr_v6.c_str());
2403 }
2404 } testConfigs[]{
2405 {0 /* non-passive */, ADDR_LOCALHOST_V4, ADDR_LOCALHOST_V6},
2406 {AI_PASSIVE, ADDR_ANYADDR_V4, ADDR_ANYADDR_V6}
2407 };
2408
2409 for (const auto& config : testConfigs) {
2410 SCOPED_TRACE(config.asParameters());
2411
Xiao Ma7c75f452018-12-11 17:56:32 +09002412 addrinfo hints = {
2413 .ai_family = AF_UNSPEC, // any address family
2414 .ai_socktype = 0, // any type
2415 .ai_protocol = 0, // any protocol
2416 .ai_flags = config.flag,
2417 };
nuccachenf52f7a52018-07-17 18:07:23 +08002418
2419 // Assign hostname as null and service as port name.
2420 ScopedAddrinfo result = safe_getaddrinfo(nullptr, PORT_NAME_HTTP, &hints);
2421 ASSERT_TRUE(result != nullptr);
2422
2423 // Can't be synthesized because it should not get into Netd.
2424 std::vector<std::string> result_strs = ToStrings(result);
2425 for (const auto& str : result_strs) {
2426 EXPECT_TRUE(str == config.addr_v4 || str == config.addr_v6)
2427 << ", result_str='" << str << "'";
2428 }
2429
2430 // Assign hostname as null and service as numeric port number.
2431 hints.ai_flags = config.flag | AI_NUMERICSERV;
2432 result = safe_getaddrinfo(nullptr, PORT_NUMBER_HTTP, &hints);
2433 ASSERT_TRUE(result != nullptr);
2434
2435 // Can't be synthesized because it should not get into Netd.
2436 result_strs = ToStrings(result);
2437 for (const auto& str : result_strs) {
2438 EXPECT_TRUE(str == config.addr_v4 || str == config.addr_v6)
2439 << ", result_str='" << str << "'";
2440 }
2441 }
2442}
2443
2444TEST_F(ResolverTest, GetHostByAddr_ReverseDnsQueryWithHavingNat64Prefix) {
2445 struct hostent* result = nullptr;
2446 struct in_addr v4addr;
2447 struct in6_addr v6addr;
2448
2449 constexpr char listen_addr[] = "::1";
nuccachenf52f7a52018-07-17 18:07:23 +08002450 constexpr char dns64_name[] = "ipv4only.arpa.";
2451 constexpr char ptr_name[] = "v4v6.example.com.";
2452 // PTR record for IPv4 address 1.2.3.4
2453 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2454 // PTR record for IPv6 address 2001:db8::102:304
2455 constexpr char ptr_addr_v6[] =
2456 "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.";
Xiao Ma7c75f452018-12-11 17:56:32 +09002457 const std::vector<DnsRecord> records = {
2458 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2459 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2460 {ptr_addr_v6, ns_type::ns_t_ptr, ptr_name},
2461 };
nuccachenf52f7a52018-07-17 18:07:23 +08002462
Xiao Ma7c75f452018-12-11 17:56:32 +09002463 test::DNSResponder dns(listen_addr);
2464 StartDns(dns, records);
nuccachenf52f7a52018-07-17 18:07:23 +08002465 const std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002466 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002467
2468 // Wait for detecting prefix to complete.
2469 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2470
2471 // Reverse IPv4 DNS query. Prefix should have no effect on it.
2472 inet_pton(AF_INET, "1.2.3.4", &v4addr);
2473 result = gethostbyaddr(&v4addr, sizeof(v4addr), AF_INET);
2474 ASSERT_TRUE(result != nullptr);
2475 std::string result_str = result->h_name ? result->h_name : "null";
2476 EXPECT_EQ(result_str, "v4v6.example.com");
2477
2478 // Reverse IPv6 DNS query. Prefix should have no effect on it.
2479 inet_pton(AF_INET6, "2001:db8::102:304", &v6addr);
2480 result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2481 ASSERT_TRUE(result != nullptr);
2482 result_str = result->h_name ? result->h_name : "null";
2483 EXPECT_EQ(result_str, "v4v6.example.com");
2484}
2485
2486TEST_F(ResolverTest, GetHostByAddr_ReverseDns64Query) {
2487 constexpr char listen_addr[] = "::1";
nuccachenf52f7a52018-07-17 18:07:23 +08002488 constexpr char dns64_name[] = "ipv4only.arpa.";
2489 constexpr char ptr_name[] = "v4only.example.com.";
2490 // PTR record for IPv4 address 1.2.3.4
2491 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2492 // PTR record for IPv6 address 64:ff9b::1.2.3.4
2493 constexpr char ptr_addr_v6_nomapping[] =
2494 "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.";
2495 constexpr char ptr_name_v6_synthesis[] = "v6synthesis.example.com.";
2496 // PTR record for IPv6 address 64:ff9b::5.6.7.8
2497 constexpr char ptr_addr_v6_synthesis[] =
2498 "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.";
Xiao Ma7c75f452018-12-11 17:56:32 +09002499 const std::vector<DnsRecord> records = {
2500 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2501 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2502 {ptr_addr_v6_synthesis, ns_type::ns_t_ptr, ptr_name_v6_synthesis},
2503 };
nuccachenf52f7a52018-07-17 18:07:23 +08002504
Xiao Ma7c75f452018-12-11 17:56:32 +09002505 test::DNSResponder dns(listen_addr);
2506 StartDns(dns, records);
nuccachenf52f7a52018-07-17 18:07:23 +08002507 // "ptr_addr_v6_nomapping" is not mapped in DNS server
nuccachenf52f7a52018-07-17 18:07:23 +08002508 const std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002509 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002510
2511 // Wait for detecting prefix to complete.
2512 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2513
2514 // Synthesized PTR record doesn't exist on DNS server
2515 // Reverse IPv6 DNS64 query while DNS server doesn't have an answer for synthesized address.
2516 // After querying synthesized address failed, expect that prefix is removed from IPv6
2517 // synthesized address and do reverse IPv4 query instead.
2518 struct in6_addr v6addr;
2519 inet_pton(AF_INET6, "64:ff9b::1.2.3.4", &v6addr);
2520 struct hostent* result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2521 ASSERT_TRUE(result != nullptr);
2522 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_nomapping)); // PTR record not exist
2523 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4)); // PTR record exist
2524 std::string result_str = result->h_name ? result->h_name : "null";
2525 EXPECT_EQ(result_str, "v4only.example.com");
2526 // Check that return address has been mapped from IPv4 to IPv6 address because Netd
2527 // removes NAT64 prefix and does IPv4 DNS reverse lookup in this case. Then, Netd
2528 // fakes the return IPv4 address as original queried IPv6 address.
2529 result_str = ToString(result);
2530 EXPECT_EQ(result_str, "64:ff9b::102:304");
2531 dns.clearQueries();
2532
2533 // Synthesized PTR record exists on DNS server
2534 // Reverse IPv6 DNS64 query while DNS server has an answer for synthesized address.
2535 // Expect to Netd pass through synthesized address for DNS queries.
2536 inet_pton(AF_INET6, "64:ff9b::5.6.7.8", &v6addr);
2537 result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2538 ASSERT_TRUE(result != nullptr);
2539 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_synthesis));
2540 result_str = result->h_name ? result->h_name : "null";
2541 EXPECT_EQ(result_str, "v6synthesis.example.com");
2542}
2543
2544TEST_F(ResolverTest, GetHostByAddr_ReverseDns64QueryFromHostFile) {
2545 constexpr char dns64_name[] = "ipv4only.arpa.";
2546 constexpr char host_name[] = "localhost";
2547 // The address is synthesized by prefix64:localhost.
2548 constexpr char host_addr[] = "64:ff9b::7f00:1";
nuccachenf52f7a52018-07-17 18:07:23 +08002549 constexpr char listen_addr[] = "::1";
Xiao Ma7c75f452018-12-11 17:56:32 +09002550
2551 test::DNSResponder dns(listen_addr);
2552 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
nuccachenf52f7a52018-07-17 18:07:23 +08002553 const std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002554 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002555
2556 // Wait for detecting prefix to complete.
2557 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2558
2559 // Using synthesized "localhost" address to be a trick for resolving host name
2560 // from host file /etc/hosts and "localhost" is the only name in /etc/hosts. Note that this is
2561 // not realistic: the code never synthesizes AAAA records for addresses in 127.0.0.0/8.
2562 struct in6_addr v6addr;
2563 inet_pton(AF_INET6, host_addr, &v6addr);
2564 struct hostent* result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2565 ASSERT_TRUE(result != nullptr);
2566 // Expect no DNS queries; localhost is resolved via /etc/hosts.
2567 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
2568
2569 ASSERT_EQ(sizeof(in6_addr), (unsigned) result->h_length);
2570 ASSERT_EQ(AF_INET6, result->h_addrtype);
2571 std::string result_str = ToString(result);
2572 EXPECT_EQ(result_str, host_addr);
2573 result_str = result->h_name ? result->h_name : "null";
2574 EXPECT_EQ(result_str, host_name);
2575}
2576
2577TEST_F(ResolverTest, GetNameInfo_ReverseDnsQueryWithHavingNat64Prefix) {
2578 constexpr char listen_addr[] = "::1";
nuccachenf52f7a52018-07-17 18:07:23 +08002579 constexpr char dns64_name[] = "ipv4only.arpa.";
2580 constexpr char ptr_name[] = "v4v6.example.com.";
2581 // PTR record for IPv4 address 1.2.3.4
2582 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2583 // PTR record for IPv6 address 2001:db8::102:304
2584 constexpr char ptr_addr_v6[] =
2585 "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.";
Xiao Ma7c75f452018-12-11 17:56:32 +09002586 const std::vector<DnsRecord> records = {
2587 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2588 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2589 {ptr_addr_v6, ns_type::ns_t_ptr, ptr_name},
2590 };
nuccachenf52f7a52018-07-17 18:07:23 +08002591
Xiao Ma7c75f452018-12-11 17:56:32 +09002592 test::DNSResponder dns(listen_addr);
2593 StartDns(dns, records);
nuccachenf52f7a52018-07-17 18:07:23 +08002594 const std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002595 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002596
2597 // Wait for detecting prefix to complete.
2598 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2599
2600 static const struct TestConfig {
2601 int flag;
2602 int family;
2603 std::string addr;
2604 std::string host;
2605
2606 std::string asParameters() const {
2607 return StringPrintf("flag=%d, family=%d, addr=%s, host=%s", flag, family, addr.c_str(),
2608 host.c_str());
2609 }
2610 } testConfigs[]{
2611 {NI_NAMEREQD, AF_INET, "1.2.3.4", "v4v6.example.com"},
2612 {NI_NUMERICHOST, AF_INET, "1.2.3.4", "1.2.3.4"},
2613 {0, AF_INET, "1.2.3.4", "v4v6.example.com"},
2614 {0, AF_INET, "5.6.7.8", "5.6.7.8"}, // unmapped
2615 {NI_NAMEREQD, AF_INET6, "2001:db8::102:304", "v4v6.example.com"},
2616 {NI_NUMERICHOST, AF_INET6, "2001:db8::102:304", "2001:db8::102:304"},
2617 {0, AF_INET6, "2001:db8::102:304", "v4v6.example.com"},
2618 {0, AF_INET6, "2001:db8::506:708", "2001:db8::506:708"}, // unmapped
2619 };
2620
2621 // Reverse IPv4/IPv6 DNS query. Prefix should have no effect on it.
2622 for (const auto& config : testConfigs) {
2623 SCOPED_TRACE(config.asParameters());
2624
2625 int rv;
2626 char host[NI_MAXHOST];
2627 struct sockaddr_in sin;
2628 struct sockaddr_in6 sin6;
2629 if (config.family == AF_INET) {
2630 memset(&sin, 0, sizeof(sin));
2631 sin.sin_family = AF_INET;
2632 inet_pton(AF_INET, config.addr.c_str(), &sin.sin_addr);
2633 rv = getnameinfo((const struct sockaddr*) &sin, sizeof(sin), host, sizeof(host),
2634 nullptr, 0, config.flag);
2635 if (config.flag == NI_NAMEREQD) EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4));
2636 } else if (config.family == AF_INET6) {
2637 memset(&sin6, 0, sizeof(sin6));
2638 sin6.sin6_family = AF_INET6;
2639 inet_pton(AF_INET6, config.addr.c_str(), &sin6.sin6_addr);
2640 rv = getnameinfo((const struct sockaddr*) &sin6, sizeof(sin6), host, sizeof(host),
2641 nullptr, 0, config.flag);
2642 if (config.flag == NI_NAMEREQD) EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6));
2643 }
2644 ASSERT_EQ(0, rv);
2645 std::string result_str = host;
2646 EXPECT_EQ(result_str, config.host);
2647 dns.clearQueries();
2648 }
2649}
2650
2651TEST_F(ResolverTest, GetNameInfo_ReverseDns64Query) {
2652 constexpr char listen_addr[] = "::1";
nuccachenf52f7a52018-07-17 18:07:23 +08002653 constexpr char dns64_name[] = "ipv4only.arpa.";
2654 constexpr char ptr_name[] = "v4only.example.com.";
2655 // PTR record for IPv4 address 1.2.3.4
2656 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2657 // PTR record for IPv6 address 64:ff9b::1.2.3.4
2658 constexpr char ptr_addr_v6_nomapping[] =
2659 "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.";
2660 constexpr char ptr_name_v6_synthesis[] = "v6synthesis.example.com.";
2661 // PTR record for IPv6 address 64:ff9b::5.6.7.8
2662 constexpr char ptr_addr_v6_synthesis[] =
2663 "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.";
Xiao Ma7c75f452018-12-11 17:56:32 +09002664 const std::vector<DnsRecord> records = {
2665 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2666 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2667 {ptr_addr_v6_synthesis, ns_type::ns_t_ptr, ptr_name_v6_synthesis},
2668 };
nuccachenf52f7a52018-07-17 18:07:23 +08002669
Xiao Ma7c75f452018-12-11 17:56:32 +09002670 test::DNSResponder dns(listen_addr);
2671 StartDns(dns, records);
nuccachenf52f7a52018-07-17 18:07:23 +08002672 const std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002673 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002674
2675 // Wait for detecting prefix to complete.
2676 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2677
2678 static const struct TestConfig {
2679 bool hasSynthesizedPtrRecord;
2680 int flag;
2681 std::string addr;
2682 std::string host;
2683
2684 std::string asParameters() const {
2685 return StringPrintf("hasSynthesizedPtrRecord=%d, flag=%d, addr=%s, host=%s",
2686 hasSynthesizedPtrRecord, flag, addr.c_str(), host.c_str());
2687 }
2688 } testConfigs[]{
2689 {false, NI_NAMEREQD, "64:ff9b::102:304", "v4only.example.com"},
2690 {false, NI_NUMERICHOST, "64:ff9b::102:304", "64:ff9b::102:304"},
2691 {false, 0, "64:ff9b::102:304", "v4only.example.com"},
2692 {true, NI_NAMEREQD, "64:ff9b::506:708", "v6synthesis.example.com"},
2693 {true, NI_NUMERICHOST, "64:ff9b::506:708", "64:ff9b::506:708"},
2694 {true, 0, "64:ff9b::506:708", "v6synthesis.example.com"}
2695 };
2696
2697 // hasSynthesizedPtrRecord = false
2698 // Synthesized PTR record doesn't exist on DNS server
2699 // Reverse IPv6 DNS64 query while DNS server doesn't have an answer for synthesized address.
2700 // After querying synthesized address failed, expect that prefix is removed from IPv6
2701 // synthesized address and do reverse IPv4 query instead.
2702 //
2703 // hasSynthesizedPtrRecord = true
2704 // Synthesized PTR record exists on DNS server
2705 // Reverse IPv6 DNS64 query while DNS server has an answer for synthesized address.
2706 // Expect to just pass through synthesized address for DNS queries.
2707 for (const auto& config : testConfigs) {
2708 SCOPED_TRACE(config.asParameters());
2709
2710 char host[NI_MAXHOST];
2711 struct sockaddr_in6 sin6;
2712 memset(&sin6, 0, sizeof(sin6));
2713 sin6.sin6_family = AF_INET6;
2714 inet_pton(AF_INET6, config.addr.c_str(), &sin6.sin6_addr);
2715 int rv = getnameinfo((const struct sockaddr*) &sin6, sizeof(sin6), host, sizeof(host),
2716 nullptr, 0, config.flag);
2717 ASSERT_EQ(0, rv);
2718 if (config.flag == NI_NAMEREQD) {
2719 if (config.hasSynthesizedPtrRecord) {
2720 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_synthesis));
2721 } else {
2722 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_nomapping)); // PTR record not exist.
2723 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4)); // PTR record exist.
2724 }
2725 }
2726 std::string result_str = host;
2727 EXPECT_EQ(result_str, config.host);
2728 dns.clearQueries();
2729 }
2730}
2731
2732TEST_F(ResolverTest, GetNameInfo_ReverseDns64QueryFromHostFile) {
2733 constexpr char dns64_name[] = "ipv4only.arpa.";
2734 constexpr char host_name[] = "localhost";
2735 // The address is synthesized by prefix64:localhost.
2736 constexpr char host_addr[] = "64:ff9b::7f00:1";
nuccachenf52f7a52018-07-17 18:07:23 +08002737 constexpr char listen_addr[] = "::1";
Xiao Ma7c75f452018-12-11 17:56:32 +09002738
2739 test::DNSResponder dns(listen_addr);
2740 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
nuccachenf52f7a52018-07-17 18:07:23 +08002741 const std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002742 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002743
2744 // Wait for detecting prefix to complete.
2745 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2746
2747 // Using synthesized "localhost" address to be a trick for resolving host name
2748 // from host file /etc/hosts and "localhost" is the only name in /etc/hosts. Note that this is
2749 // not realistic: the code never synthesizes AAAA records for addresses in 127.0.0.0/8.
2750 char host[NI_MAXHOST];
Xiao Ma7c75f452018-12-11 17:56:32 +09002751 struct sockaddr_in6 sin6 = {.sin6_family = AF_INET6};
nuccachenf52f7a52018-07-17 18:07:23 +08002752 inet_pton(AF_INET6, host_addr, &sin6.sin6_addr);
2753 int rv = getnameinfo((const struct sockaddr*) &sin6, sizeof(sin6), host, sizeof(host), nullptr,
2754 0, NI_NAMEREQD);
2755 ASSERT_EQ(0, rv);
2756 // Expect no DNS queries; localhost is resolved via /etc/hosts.
2757 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
2758
2759 std::string result_str = host;
2760 EXPECT_EQ(result_str, host_name);
2761}
2762
nuccachenf52f7a52018-07-17 18:07:23 +08002763TEST_F(ResolverTest, GetHostByName2_Dns64Synthesize) {
Xiao Ma7c75f452018-12-11 17:56:32 +09002764 constexpr char listen_addr[] = "::1";
nuccachenf52f7a52018-07-17 18:07:23 +08002765 constexpr char dns64_name[] = "ipv4only.arpa.";
2766 constexpr char host_name[] = "ipv4only.example.com.";
Xiao Ma7c75f452018-12-11 17:56:32 +09002767 const std::vector<DnsRecord> records = {
2768 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2769 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2770 };
nuccachenf52f7a52018-07-17 18:07:23 +08002771
Xiao Ma7c75f452018-12-11 17:56:32 +09002772 test::DNSResponder dns(listen_addr);
2773 StartDns(dns, records);
nuccachenf52f7a52018-07-17 18:07:23 +08002774 const std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002775 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002776
2777 // Wait for detecting prefix to complete.
2778 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2779
2780 // Query an IPv4-only hostname. Expect that gets a synthesized address.
2781 struct hostent* result = gethostbyname2("ipv4only", AF_INET6);
2782 ASSERT_TRUE(result != nullptr);
2783 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2784 std::string result_str = ToString(result);
2785 EXPECT_EQ(result_str, "64:ff9b::102:304");
2786}
nuccachenf52f7a52018-07-17 18:07:23 +08002787
2788TEST_F(ResolverTest, GetHostByName2_DnsQueryWithHavingNat64Prefix) {
2789 constexpr char dns64_name[] = "ipv4only.arpa.";
2790 constexpr char host_name[] = "v4v6.example.com.";
nuccachenf52f7a52018-07-17 18:07:23 +08002791 constexpr char listen_addr[] = "::1";
Xiao Ma7c75f452018-12-11 17:56:32 +09002792 const std::vector<DnsRecord> records = {
2793 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2794 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2795 {host_name, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
2796 };
2797
2798 test::DNSResponder dns(listen_addr);
2799 StartDns(dns, records);
nuccachenf52f7a52018-07-17 18:07:23 +08002800 const std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002801 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002802
2803 // Wait for detecting prefix to complete.
2804 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2805
2806 // IPv4 DNS query. Prefix should have no effect on it.
2807 struct hostent* result = gethostbyname2("v4v6", AF_INET);
2808 ASSERT_TRUE(result != nullptr);
2809 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2810 std::string result_str = ToString(result);
2811 EXPECT_EQ(result_str, "1.2.3.4");
2812 dns.clearQueries();
2813
2814 // IPv6 DNS query. Prefix should have no effect on it.
2815 result = gethostbyname2("v4v6", AF_INET6);
2816 ASSERT_TRUE(result != nullptr);
2817 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2818 result_str = ToString(result);
2819 EXPECT_EQ(result_str, "2001:db8::102:304");
2820}
2821
2822TEST_F(ResolverTest, GetHostByName2_Dns64QuerySpecialUseIPv4Addresses) {
2823 constexpr char THIS_NETWORK[] = "this_network";
2824 constexpr char LOOPBACK[] = "loopback";
2825 constexpr char LINK_LOCAL[] = "link_local";
2826 constexpr char MULTICAST[] = "multicast";
2827 constexpr char LIMITED_BROADCAST[] = "limited_broadcast";
2828
2829 constexpr char ADDR_THIS_NETWORK[] = "0.0.0.1";
2830 constexpr char ADDR_LOOPBACK[] = "127.0.0.1";
2831 constexpr char ADDR_LINK_LOCAL[] = "169.254.0.1";
2832 constexpr char ADDR_MULTICAST[] = "224.0.0.1";
2833 constexpr char ADDR_LIMITED_BROADCAST[] = "255.255.255.255";
2834
2835 constexpr char listen_addr[] = "::1";
nuccachenf52f7a52018-07-17 18:07:23 +08002836 constexpr char dns64_name[] = "ipv4only.arpa.";
2837
Xiao Ma7c75f452018-12-11 17:56:32 +09002838 test::DNSResponder dns(listen_addr);
2839 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
nuccachenf52f7a52018-07-17 18:07:23 +08002840 const std::vector<std::string> servers = {listen_addr};
Xiao Ma7c75f452018-12-11 17:56:32 +09002841 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachenf52f7a52018-07-17 18:07:23 +08002842
2843 // Wait for detecting prefix to complete.
2844 EXPECT_TRUE(WaitForPrefix64Detected(TEST_NETID, 1000));
2845
2846 static const struct TestConfig {
2847 std::string name;
2848 std::string addr;
2849
2850 std::string asHostName() const {
2851 return StringPrintf("%s.example.com.",
2852 name.c_str());
2853 }
2854 } testConfigs[]{
2855 {THIS_NETWORK, ADDR_THIS_NETWORK},
2856 {LOOPBACK, ADDR_LOOPBACK},
2857 {LINK_LOCAL, ADDR_LINK_LOCAL},
2858 {MULTICAST, ADDR_MULTICAST},
2859 {LIMITED_BROADCAST, ADDR_LIMITED_BROADCAST}
2860 };
2861
2862 for (const auto& config : testConfigs) {
2863 const std::string testHostName = config.asHostName();
2864 SCOPED_TRACE(testHostName);
2865
2866 const char* host_name = testHostName.c_str();
2867 dns.addMapping(host_name, ns_type::ns_t_a, config.addr.c_str());
2868
2869 struct hostent* result = gethostbyname2(config.name.c_str(), AF_INET6);
2870 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2871
2872 // In AF_INET6 case, don't synthesize special use IPv4 address.
2873 // Expect to have no answer
2874 EXPECT_EQ(nullptr, result);
2875
2876 dns.clearQueries();
2877 }
Bernie Innocenticd257642018-12-20 15:56:40 +09002878}