blob: db9ce51b196d60f4e6c9b9aceb7dee1128acae78 [file] [log] [blame]
Ken Chenb9fa2062018-11-13 21:51:13 +08001/*
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 Innocenti3952ccc2019-03-03 19:39:53 +090018#define LOG_TAG "resolv_integration_test"
Ken Chenb9fa2062018-11-13 21:51:13 +080019
Hungming Chen5bf09772019-04-25 11:16:13 +080020#include <android-base/logging.h>
Bernie Innocenti41b82c42019-06-05 22:38:25 +090021#include <android-base/parseint.h>
22#include <android-base/stringprintf.h>
23#include <android-base/unique_fd.h>
24#include <android/multinetwork.h> // ResNsendFlags
Ken Chenb9fa2062018-11-13 21:51:13 +080025#include <arpa/inet.h>
Luke Huang94b10b92018-11-21 20:13:38 +080026#include <arpa/nameser.h>
Hungming Chene8f970c2019-04-10 17:34:06 +080027#include <binder/ProcessState.h>
Bernie Innocenti41b82c42019-06-05 22:38:25 +090028#include <cutils/sockets.h>
29#include <gmock/gmock-matchers.h>
30#include <gtest/gtest.h>
Ken Chenb9fa2062018-11-13 21:51:13 +080031#include <netdb.h>
Luke Huang9d2d25b2019-06-14 00:34:05 +080032#include <netdutils/InternetAddresses.h>
Luke Huang579ddc72019-06-14 00:59:39 +080033#include <netdutils/NetworkConstants.h> // SHA256_SIZE
Luke Huang9d2d25b2019-06-14 00:34:05 +080034#include <netdutils/ResponseCode.h>
35#include <netdutils/SocketOption.h>
Luke Huang94b10b92018-11-21 20:13:38 +080036#include <netinet/in.h>
Bernie Innocenti41b82c42019-06-05 22:38:25 +090037#include <openssl/base64.h>
Luke Huang94b10b92018-11-21 20:13:38 +080038#include <poll.h> /* poll */
Bernie Innocenti41b82c42019-06-05 22:38:25 +090039#include <private/android_filesystem_config.h>
Luke Huang94b10b92018-11-21 20:13:38 +080040#include <resolv.h>
Ken Chenb9fa2062018-11-13 21:51:13 +080041#include <stdarg.h>
Ken Chenb9fa2062018-11-13 21:51:13 +080042#include <stdlib.h>
Luke Huang94b10b92018-11-21 20:13:38 +080043#include <sys/socket.h>
44#include <sys/un.h>
Ken Chenb9fa2062018-11-13 21:51:13 +080045#include <unistd.h>
46
47#include <algorithm>
48#include <chrono>
49#include <iterator>
50#include <numeric>
51#include <thread>
52
Bernie Innocenti41b82c42019-06-05 22:38:25 +090053#include "NetdClient.h"
Bernie Innocenti41b82c42019-06-05 22:38:25 +090054#include "ResolverStats.h"
55#include "android/net/IDnsResolver.h"
56#include "binder/IServiceManager.h"
Ken Chenb9fa2062018-11-13 21:51:13 +080057#include "dns_responder/dns_responder.h"
58#include "dns_responder/dns_responder_client.h"
59#include "dns_responder/dns_tls_frontend.h"
Bernie Innocenti41b82c42019-06-05 22:38:25 +090060#include "netd_resolv/params.h" // MAXNS
Bernie Innocenti41b82c42019-06-05 22:38:25 +090061#include "netid_client.h" // NETID_UNSET
Hungming Chene8f970c2019-04-10 17:34:06 +080062#include "tests/dns_metrics_listener/dns_metrics_listener.h"
Luke Huangfde82482019-06-04 01:04:53 +080063#include "tests/resolv_test_utils.h"
Ken Chenb9fa2062018-11-13 21:51:13 +080064
Luke Huang0d592bc2019-05-25 18:24:03 +080065// Valid VPN netId range is 100 ~ 65535
66constexpr int TEST_VPN_NETID = 65502;
Luke Huang94b10b92018-11-21 20:13:38 +080067constexpr int MAXPACKET = (8 * 1024);
Ken Chenb9fa2062018-11-13 21:51:13 +080068
69// Semi-public Bionic hook used by the NDK (frameworks/base/native/android/net.c)
70// Tested here for convenience.
71extern "C" int android_getaddrinfofornet(const char* hostname, const char* servname,
72 const addrinfo* hints, unsigned netid, unsigned mark,
73 struct addrinfo** result);
74
Luke Huang9807e6b2019-05-20 16:17:12 +080075using android::base::ParseInt;
Ken Chenb9fa2062018-11-13 21:51:13 +080076using android::base::StringPrintf;
Luke Huang9807e6b2019-05-20 16:17:12 +080077using android::base::unique_fd;
Ken Chenb9fa2062018-11-13 21:51:13 +080078using android::net::ResolverStats;
Hungming Chene8f970c2019-04-10 17:34:06 +080079using android::net::metrics::DnsMetricsListener;
Ken Chenb9fa2062018-11-13 21:51:13 +080080using android::netdutils::enableSockopt;
Luke Huang9807e6b2019-05-20 16:17:12 +080081using android::netdutils::ResponseCode;
Luke Huang9d2d25b2019-06-14 00:34:05 +080082using android::netdutils::ScopedAddrinfo;
Ken Chenb9fa2062018-11-13 21:51:13 +080083
84// TODO: move into libnetdutils?
85namespace {
Luke Huangfde82482019-06-04 01:04:53 +080086
Ken Chenb9fa2062018-11-13 21:51:13 +080087ScopedAddrinfo safe_getaddrinfo(const char* node, const char* service,
88 const struct addrinfo* hints) {
89 addrinfo* result = nullptr;
90 if (getaddrinfo(node, service, hints, &result) != 0) {
91 result = nullptr; // Should already be the case, but...
92 }
93 return ScopedAddrinfo(result);
94}
Luke Huangfde82482019-06-04 01:04:53 +080095
Ken Chenb9fa2062018-11-13 21:51:13 +080096} // namespace
97
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +090098class ResolverTest : public ::testing::Test {
Hungming Chene8f970c2019-04-10 17:34:06 +080099 public:
Hungming Chen5bf09772019-04-25 11:16:13 +0800100 static void SetUpTestCase() {
101 // Get binder service.
102 // Note that |mDnsClient| is not used for getting binder service in this static function.
103 // The reason is that wants to keep |mDnsClient| as a non-static data member. |mDnsClient|
104 // which sets up device network configuration could be independent from every test.
105 // TODO: Perhaps add a static function in class DnsResponderClient to get binder service.
106 auto resolvBinder =
107 android::defaultServiceManager()->getService(android::String16("dnsresolver"));
108 auto resolvService = android::interface_cast<android::net::IDnsResolver>(resolvBinder);
109 ASSERT_NE(nullptr, resolvService.get());
110
111 // Subscribe the death recipient to the service IDnsResolver for detecting Netd death.
112 sResolvDeathRecipient = new ResolvDeathRecipient();
113 ASSERT_EQ(android::NO_ERROR, resolvBinder->linkToDeath(sResolvDeathRecipient));
114
115 // Subscribe the DNS listener for verifying DNS metrics event contents.
116 sDnsMetricsListener = new DnsMetricsListener(TEST_NETID /*monitor specific network*/);
117 ASSERT_TRUE(resolvService->registerEventListener(sDnsMetricsListener).isOk());
118
119 // Start the binder thread pool for listening DNS metrics events and receiving death
120 // recipient.
121 android::ProcessState::self()->startThreadPool();
Hungming Chene8f970c2019-04-10 17:34:06 +0800122 }
123
Ken Chenb9fa2062018-11-13 21:51:13 +0800124 protected:
Xiao Ma09b71022018-12-11 17:56:32 +0900125 struct DnsRecord {
126 std::string host_name; // host name
127 ns_type type; // record type
128 std::string addr; // ipv4/v6 address
129 };
130
Hungming Chen5bf09772019-04-25 11:16:13 +0800131 class ResolvDeathRecipient : public android::IBinder::DeathRecipient {
132 public:
133 ~ResolvDeathRecipient() override = default;
Hungming Chene8f970c2019-04-10 17:34:06 +0800134
Hungming Chen5bf09772019-04-25 11:16:13 +0800135 // GTEST assertion macros are not invoked for generating a test failure in the death
136 // recipient because the macros can't indicate failed test if Netd died between tests.
137 // Moreover, continuing testing may have no meaningful after Netd death. Therefore, the
138 // death recipient aborts process by GTEST_LOG_(FATAL) once Netd died.
139 void binderDied(const android::wp<android::IBinder>& /*who*/) override {
140 constexpr char errorMessage[] = "Netd service died";
141 LOG(ERROR) << errorMessage;
142 GTEST_LOG_(FATAL) << errorMessage;
143 }
144 };
Hungming Chene8f970c2019-04-10 17:34:06 +0800145
Hungming Chen5bf09772019-04-25 11:16:13 +0800146 void SetUp() { mDnsClient.SetUp(); }
Hungming Chene8f970c2019-04-10 17:34:06 +0800147 void TearDown() { mDnsClient.TearDown(); }
nuccachena26cc2a2018-07-17 18:07:23 +0800148
Xiao Ma09b71022018-12-11 17:56:32 +0900149 void StartDns(test::DNSResponder& dns, const std::vector<DnsRecord>& records) {
150 for (const auto& r : records) {
151 dns.addMapping(r.host_name, r.type, r.addr);
152 }
153
154 ASSERT_TRUE(dns.startServer());
155 dns.clearQueries();
156 }
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900157
Hungming Chene8f970c2019-04-10 17:34:06 +0800158 bool WaitForNat64Prefix(ExpectNat64PrefixStatus status,
159 std::chrono::milliseconds timeout = std::chrono::milliseconds(1000)) {
Hungming Chen5bf09772019-04-25 11:16:13 +0800160 return sDnsMetricsListener->waitForNat64Prefix(status, timeout);
Hungming Chene8f970c2019-04-10 17:34:06 +0800161 }
162
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900163 DnsResponderClient mDnsClient;
Xiao Ma09b71022018-12-11 17:56:32 +0900164
165 static constexpr char kLocalHost[] = "localhost";
166 static constexpr char kLocalHostAddr[] = "127.0.0.1";
167 static constexpr char kIp6LocalHost[] = "ip6-localhost";
168 static constexpr char kIp6LocalHostAddr[] = "::1";
169 static constexpr char kHelloExampleCom[] = "hello.example.com.";
Hungming Chen5bf09772019-04-25 11:16:13 +0800170
171 // Use a shared static DNS listener for all tests to avoid registering lots of listeners
172 // which may be released late until process terminated. Currently, registered DNS listener
173 // is removed by binder death notification which is fired when the process hosting an
174 // IBinder has gone away. If every test in ResolverTest registers its DNS listener, Netd
175 // may temporarily hold lots of dead listeners until the unit test process terminates.
176 // TODO: Perhaps add an unregistering listener binder call or fork a listener process which
177 // could be terminated earlier.
178 static android::sp<DnsMetricsListener> sDnsMetricsListener; // Initialized in SetUpTestCase.
179
180 // Use a shared static death recipient to monitor the service death. The static death
181 // recipient could monitor the death not only during the test but also between tests.
182 static android::sp<ResolvDeathRecipient>
183 sResolvDeathRecipient; // Initialized in SetUpTestCase.
Ken Chenb9fa2062018-11-13 21:51:13 +0800184};
185
Hungming Chen5bf09772019-04-25 11:16:13 +0800186// Initialize static member of class.
187android::sp<DnsMetricsListener> ResolverTest::sDnsMetricsListener;
188android::sp<ResolverTest::ResolvDeathRecipient> ResolverTest::sResolvDeathRecipient;
189
Ken Chenb9fa2062018-11-13 21:51:13 +0800190TEST_F(ResolverTest, GetHostByName) {
Xiao Ma09b71022018-12-11 17:56:32 +0900191 constexpr char nonexistent_host_name[] = "nonexistent.example.com.";
192
193 test::DNSResponder dns;
194 StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.3"}});
195 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800196
197 const hostent* result;
Ken Chenb9fa2062018-11-13 21:51:13 +0800198 result = gethostbyname("nonexistent");
199 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, nonexistent_host_name));
200 ASSERT_TRUE(result == nullptr);
201 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
202
203 dns.clearQueries();
204 result = gethostbyname("hello");
Xiao Ma09b71022018-12-11 17:56:32 +0900205 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, kHelloExampleCom));
Ken Chenb9fa2062018-11-13 21:51:13 +0800206 ASSERT_FALSE(result == nullptr);
207 ASSERT_EQ(4, result->h_length);
208 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
209 EXPECT_EQ("1.2.3.3", ToString(result));
210 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800211}
212
lifr4e4a2e02019-01-29 16:53:51 +0800213TEST_F(ResolverTest, GetHostByName_cnames) {
214 constexpr char host_name[] = "host.example.com.";
215 size_t cnamecount = 0;
216 test::DNSResponder dns;
217
218 const std::vector<DnsRecord> records = {
219 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
220 {"a.example.com.", ns_type::ns_t_cname, "b.example.com."},
221 {"b.example.com.", ns_type::ns_t_cname, "c.example.com."},
222 {"c.example.com.", ns_type::ns_t_cname, "d.example.com."},
223 {"d.example.com.", ns_type::ns_t_cname, "e.example.com."},
224 {"e.example.com.", ns_type::ns_t_cname, host_name},
225 {host_name, ns_type::ns_t_a, "1.2.3.3"},
226 {host_name, ns_type::ns_t_aaaa, "2001:db8::42"},
227 };
228 StartDns(dns, records);
229 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
230
231 // using gethostbyname2() to resolve ipv4 hello.example.com. to 1.2.3.3
232 // Ensure the v4 address and cnames are correct
233 const hostent* result;
234 result = gethostbyname2("hello", AF_INET);
235 ASSERT_FALSE(result == nullptr);
236
237 for (int i = 0; result != nullptr && result->h_aliases[i] != nullptr; i++) {
238 std::string domain_name = records[i].host_name.substr(0, records[i].host_name.size() - 1);
239 EXPECT_EQ(result->h_aliases[i], domain_name);
240 cnamecount++;
241 }
242 // The size of "Non-cname type" record in DNS records is 2
243 ASSERT_EQ(cnamecount, records.size() - 2);
244 ASSERT_EQ(4, result->h_length);
245 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
246 EXPECT_EQ("1.2.3.3", ToString(result));
247 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
248 EXPECT_EQ(1U, dns.queries().size()) << dns.dumpQueries();
249
250 // using gethostbyname2() to resolve ipv6 hello.example.com. to 2001:db8::42
251 // Ensure the v6 address and cnames are correct
252 cnamecount = 0;
253 dns.clearQueries();
254 result = gethostbyname2("hello", AF_INET6);
255 for (unsigned i = 0; result != nullptr && result->h_aliases[i] != nullptr; i++) {
256 std::string domain_name = records[i].host_name.substr(0, records[i].host_name.size() - 1);
257 EXPECT_EQ(result->h_aliases[i], domain_name);
258 cnamecount++;
259 }
260 // The size of "Non-cname type" DNS record in records is 2
261 ASSERT_EQ(cnamecount, records.size() - 2);
262 ASSERT_FALSE(result == nullptr);
263 ASSERT_EQ(16, result->h_length);
264 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
265 EXPECT_EQ("2001:db8::42", ToString(result));
266 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
267}
268
269TEST_F(ResolverTest, GetHostByName_cnamesInfiniteLoop) {
270 test::DNSResponder dns;
271 const std::vector<DnsRecord> records = {
272 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
273 {"a.example.com.", ns_type::ns_t_cname, kHelloExampleCom},
274 };
275 StartDns(dns, records);
276 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
277
278 const hostent* result;
279 result = gethostbyname2("hello", AF_INET);
280 ASSERT_TRUE(result == nullptr);
281
282 dns.clearQueries();
283 result = gethostbyname2("hello", AF_INET6);
284 ASSERT_TRUE(result == nullptr);
285}
286
Ken Chenb9fa2062018-11-13 21:51:13 +0800287TEST_F(ResolverTest, GetHostByName_localhost) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800288 constexpr char name_camelcase[] = "LocalHost";
Ken Chenb9fa2062018-11-13 21:51:13 +0800289 constexpr char name_ip6_dot[] = "ip6-localhost.";
290 constexpr char name_ip6_fqdn[] = "ip6-localhost.example.com.";
291
292 // Add a dummy nameserver which shouldn't receive any queries
Xiao Ma09b71022018-12-11 17:56:32 +0900293 test::DNSResponder dns;
294 StartDns(dns, {});
295 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800296
297 // Expect no DNS queries; localhost is resolved via /etc/hosts
Xiao Ma09b71022018-12-11 17:56:32 +0900298 const hostent* result = gethostbyname(kLocalHost);
Ken Chenb9fa2062018-11-13 21:51:13 +0800299 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
300 ASSERT_FALSE(result == nullptr);
301 ASSERT_EQ(4, result->h_length);
302 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
Xiao Ma09b71022018-12-11 17:56:32 +0900303 EXPECT_EQ(kLocalHostAddr, ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +0800304 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
305
306 // Ensure the hosts file resolver ignores case of hostnames
307 result = gethostbyname(name_camelcase);
308 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
309 ASSERT_FALSE(result == nullptr);
310 ASSERT_EQ(4, result->h_length);
311 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
Xiao Ma09b71022018-12-11 17:56:32 +0900312 EXPECT_EQ(kLocalHostAddr, ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +0800313 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
314
315 // The hosts file also contains ip6-localhost, but gethostbyname() won't
chenbruce018fdb22019-06-12 18:08:04 +0800316 // return it. This would be easy to
Ken Chenb9fa2062018-11-13 21:51:13 +0800317 // change, but there's no point in changing the legacy behavior; new code
318 // should be calling getaddrinfo() anyway.
319 // So we check the legacy behavior, which results in amusing A-record
320 // lookups for ip6-localhost, with and without search domains appended.
321 dns.clearQueries();
Xiao Ma09b71022018-12-11 17:56:32 +0900322 result = gethostbyname(kIp6LocalHost);
Sehee Parkbbca0202018-11-16 10:53:16 +0900323 EXPECT_EQ(2U, dns.queries().size()) << dns.dumpQueries();
324 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, name_ip6_dot)) << dns.dumpQueries();
325 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, name_ip6_fqdn)) << dns.dumpQueries();
Ken Chenb9fa2062018-11-13 21:51:13 +0800326 ASSERT_TRUE(result == nullptr);
327
328 // Finally, use gethostbyname2() to resolve ip6-localhost to ::1 from
329 // the hosts file.
330 dns.clearQueries();
Xiao Ma09b71022018-12-11 17:56:32 +0900331 result = gethostbyname2(kIp6LocalHost, AF_INET6);
Ken Chenb9fa2062018-11-13 21:51:13 +0800332 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
333 ASSERT_FALSE(result == nullptr);
334 ASSERT_EQ(16, result->h_length);
335 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
Xiao Ma09b71022018-12-11 17:56:32 +0900336 EXPECT_EQ(kIp6LocalHostAddr, ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +0800337 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800338}
339
340TEST_F(ResolverTest, GetHostByName_numeric) {
341 // Add a dummy nameserver which shouldn't receive any queries
Xiao Ma09b71022018-12-11 17:56:32 +0900342 test::DNSResponder dns;
343 StartDns(dns, {});
344 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800345
346 // Numeric v4 address: expect no DNS queries
347 constexpr char numeric_v4[] = "192.168.0.1";
Ken Chenb9fa2062018-11-13 21:51:13 +0800348 const hostent* result = gethostbyname(numeric_v4);
Sehee Parkbbca0202018-11-16 10:53:16 +0900349 EXPECT_EQ(0U, dns.queries().size());
Ken Chenb9fa2062018-11-13 21:51:13 +0800350 ASSERT_FALSE(result == nullptr);
351 ASSERT_EQ(4, result->h_length); // v4
352 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
353 EXPECT_EQ(numeric_v4, ToString(result));
354 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
355
356 // gethostbyname() recognizes a v6 address, and fails with no DNS queries
357 constexpr char numeric_v6[] = "2001:db8::42";
358 dns.clearQueries();
359 result = gethostbyname(numeric_v6);
Sehee Parkbbca0202018-11-16 10:53:16 +0900360 EXPECT_EQ(0U, dns.queries().size());
Ken Chenb9fa2062018-11-13 21:51:13 +0800361 EXPECT_TRUE(result == nullptr);
362
363 // Numeric v6 address with gethostbyname2(): succeeds with no DNS queries
364 dns.clearQueries();
365 result = gethostbyname2(numeric_v6, AF_INET6);
Sehee Parkbbca0202018-11-16 10:53:16 +0900366 EXPECT_EQ(0U, dns.queries().size());
Ken Chenb9fa2062018-11-13 21:51:13 +0800367 ASSERT_FALSE(result == nullptr);
368 ASSERT_EQ(16, result->h_length); // v6
369 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
370 EXPECT_EQ(numeric_v6, ToString(result));
371 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
372
373 // Numeric v6 address with scope work with getaddrinfo(),
374 // but gethostbyname2() does not understand them; it issues two dns
375 // queries, then fails. This hardly ever happens, there's no point
376 // in fixing this. This test simply verifies the current (bogus)
377 // behavior to avoid further regressions (like crashes, or leaks).
378 constexpr char numeric_v6_scope[] = "fe80::1%lo";
379 dns.clearQueries();
380 result = gethostbyname2(numeric_v6_scope, AF_INET6);
Sehee Parkbbca0202018-11-16 10:53:16 +0900381 EXPECT_EQ(2U, dns.queries().size()); // OUCH!
Ken Chenb9fa2062018-11-13 21:51:13 +0800382 ASSERT_TRUE(result == nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800383}
384
385TEST_F(ResolverTest, BinderSerialization) {
Luke Huang5bd827c2019-03-14 16:10:04 +0800386 using android::net::IDnsResolver;
Ken Chenb9fa2062018-11-13 21:51:13 +0800387 std::vector<int> params_offsets = {
Luke Huang5bd827c2019-03-14 16:10:04 +0800388 IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY,
389 IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD,
390 IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES,
391 IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES,
392 IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC,
393 IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT,
Ken Chenb9fa2062018-11-13 21:51:13 +0800394 };
Bernie Innocentib102dd22018-12-04 14:57:48 +0900395 const int size = static_cast<int>(params_offsets.size());
Luke Huang5bd827c2019-03-14 16:10:04 +0800396 EXPECT_EQ(size, IDnsResolver::RESOLVER_PARAMS_COUNT);
Ken Chenb9fa2062018-11-13 21:51:13 +0800397 std::sort(params_offsets.begin(), params_offsets.end());
Bernie Innocentib102dd22018-12-04 14:57:48 +0900398 for (int i = 0; i < size; ++i) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800399 EXPECT_EQ(params_offsets[i], i);
400 }
401}
402
403TEST_F(ResolverTest, GetHostByName_Binder) {
Luke Huang5bd827c2019-03-14 16:10:04 +0800404 using android::net::IDnsResolver;
Ken Chenb9fa2062018-11-13 21:51:13 +0800405
406 std::vector<std::string> domains = { "example.com" };
407 std::vector<std::unique_ptr<test::DNSResponder>> dns;
408 std::vector<std::string> servers;
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900409 std::vector<DnsResponderClient::Mapping> mappings;
410 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(1, domains, &mappings));
411 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(4, mappings, &dns, &servers));
Ken Chenb9fa2062018-11-13 21:51:13 +0800412 ASSERT_EQ(1U, mappings.size());
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900413 const DnsResponderClient::Mapping& mapping = mappings[0];
Ken Chenb9fa2062018-11-13 21:51:13 +0800414
Xiao Ma09b71022018-12-11 17:56:32 +0900415 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains, kDefaultParams));
Ken Chenb9fa2062018-11-13 21:51:13 +0800416
417 const hostent* result = gethostbyname(mapping.host.c_str());
Bernie Innocentib102dd22018-12-04 14:57:48 +0900418 const size_t total_queries =
Luke Huangfde82482019-06-04 01:04:53 +0800419 std::accumulate(dns.begin(), dns.end(), 0, [&mapping](size_t total, auto& d) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800420 return total + GetNumQueriesForType(*d, ns_type::ns_t_a, mapping.entry.c_str());
421 });
422
423 EXPECT_LE(1U, total_queries);
424 ASSERT_FALSE(result == nullptr);
425 ASSERT_EQ(4, result->h_length);
426 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
427 EXPECT_EQ(mapping.ip4, ToString(result));
428 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
429
430 std::vector<std::string> res_servers;
431 std::vector<std::string> res_domains;
Mike Yu0a1c53d2018-11-26 13:26:21 +0900432 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +0900433 res_params res_params;
Ken Chenb9fa2062018-11-13 21:51:13 +0800434 std::vector<ResolverStats> res_stats;
Ken Chen92bed612018-12-22 21:46:55 +0800435 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +0800436 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
437 &res_tls_servers, &res_params, &res_stats,
438 &wait_for_pending_req_timeout_count));
Ken Chenb9fa2062018-11-13 21:51:13 +0800439 EXPECT_EQ(servers.size(), res_servers.size());
440 EXPECT_EQ(domains.size(), res_domains.size());
Mike Yu0a1c53d2018-11-26 13:26:21 +0900441 EXPECT_EQ(0U, res_tls_servers.size());
Luke Huang5bd827c2019-03-14 16:10:04 +0800442 ASSERT_EQ(static_cast<size_t>(IDnsResolver::RESOLVER_PARAMS_COUNT), kDefaultParams.size());
443 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY],
444 res_params.sample_validity);
445 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD],
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900446 res_params.success_threshold);
Luke Huang5bd827c2019-03-14 16:10:04 +0800447 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES], res_params.min_samples);
448 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES], res_params.max_samples);
449 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
Ken Chenb9fa2062018-11-13 21:51:13 +0800450 res_params.base_timeout_msec);
451 EXPECT_EQ(servers.size(), res_stats.size());
452
Bernie Innocenti0c067e42019-04-01 15:33:16 +0900453 EXPECT_THAT(res_servers, testing::UnorderedElementsAreArray(servers));
454 EXPECT_THAT(res_domains, testing::UnorderedElementsAreArray(domains));
Ken Chenb9fa2062018-11-13 21:51:13 +0800455}
456
457TEST_F(ResolverTest, GetAddrInfo) {
Xiao Ma09b71022018-12-11 17:56:32 +0900458 constexpr char listen_addr[] = "127.0.0.4";
459 constexpr char listen_addr2[] = "127.0.0.5";
460 constexpr char host_name[] = "howdy.example.com.";
Ken Chenb9fa2062018-11-13 21:51:13 +0800461
Xiao Ma09b71022018-12-11 17:56:32 +0900462 const std::vector<DnsRecord> records = {
463 {host_name, ns_type::ns_t_a, "1.2.3.4"},
464 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
465 };
466 test::DNSResponder dns(listen_addr);
467 test::DNSResponder dns2(listen_addr2);
468 StartDns(dns, records);
469 StartDns(dns2, records);
Ken Chenb9fa2062018-11-13 21:51:13 +0800470
Xiao Ma09b71022018-12-11 17:56:32 +0900471 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr}));
Ken Chenb9fa2062018-11-13 21:51:13 +0800472 dns.clearQueries();
473 dns2.clearQueries();
474
475 ScopedAddrinfo result = safe_getaddrinfo("howdy", nullptr, nullptr);
476 EXPECT_TRUE(result != nullptr);
477 size_t found = GetNumQueries(dns, host_name);
478 EXPECT_LE(1U, found);
479 // Could be A or AAAA
480 std::string result_str = ToString(result);
481 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
482 << ", result_str='" << result_str << "'";
483
484 // Verify that the name is cached.
485 size_t old_found = found;
486 result = safe_getaddrinfo("howdy", nullptr, nullptr);
487 EXPECT_TRUE(result != nullptr);
488 found = GetNumQueries(dns, host_name);
489 EXPECT_LE(1U, found);
490 EXPECT_EQ(old_found, found);
491 result_str = ToString(result);
492 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
493 << result_str;
494
495 // Change the DNS resolver, ensure that queries are still cached.
Xiao Ma09b71022018-12-11 17:56:32 +0900496 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr2}));
Ken Chenb9fa2062018-11-13 21:51:13 +0800497 dns.clearQueries();
498 dns2.clearQueries();
499
500 result = safe_getaddrinfo("howdy", nullptr, nullptr);
501 EXPECT_TRUE(result != nullptr);
502 found = GetNumQueries(dns, host_name);
503 size_t found2 = GetNumQueries(dns2, host_name);
504 EXPECT_EQ(0U, found);
505 EXPECT_LE(0U, found2);
506
507 // Could be A or AAAA
508 result_str = ToString(result);
509 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
510 << ", result_str='" << result_str << "'";
Ken Chenb9fa2062018-11-13 21:51:13 +0800511}
512
513TEST_F(ResolverTest, GetAddrInfoV4) {
Xiao Ma09b71022018-12-11 17:56:32 +0900514 test::DNSResponder dns;
515 StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.5"}});
516 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800517
Xiao Ma09b71022018-12-11 17:56:32 +0900518 const addrinfo hints = {.ai_family = AF_INET};
519 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
Ken Chenb9fa2062018-11-13 21:51:13 +0800520 EXPECT_TRUE(result != nullptr);
Xiao Ma09b71022018-12-11 17:56:32 +0900521 EXPECT_EQ(1U, GetNumQueries(dns, kHelloExampleCom));
Ken Chenb9fa2062018-11-13 21:51:13 +0800522 EXPECT_EQ("1.2.3.5", ToString(result));
523}
524
525TEST_F(ResolverTest, GetAddrInfo_localhost) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800526 // Add a dummy nameserver which shouldn't receive any queries
Xiao Ma09b71022018-12-11 17:56:32 +0900527 test::DNSResponder dns;
528 StartDns(dns, {});
529 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800530
Xiao Ma09b71022018-12-11 17:56:32 +0900531 ScopedAddrinfo result = safe_getaddrinfo(kLocalHost, nullptr, nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800532 EXPECT_TRUE(result != nullptr);
533 // Expect no DNS queries; localhost is resolved via /etc/hosts
534 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
Xiao Ma09b71022018-12-11 17:56:32 +0900535 EXPECT_EQ(kLocalHostAddr, ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +0800536
Xiao Ma09b71022018-12-11 17:56:32 +0900537 result = safe_getaddrinfo(kIp6LocalHost, nullptr, nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800538 EXPECT_TRUE(result != nullptr);
539 // Expect no DNS queries; ip6-localhost is resolved via /etc/hosts
540 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
Xiao Ma09b71022018-12-11 17:56:32 +0900541 EXPECT_EQ(kIp6LocalHostAddr, ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +0800542}
543
Ken Chen92bed612018-12-22 21:46:55 +0800544// Verify if the resolver correctly handle multiple queries simultaneously
545// step 1: set dns server#1 into deferred responding mode.
546// step 2: thread#1 query "hello.example.com." --> resolver send query to server#1.
547// step 3: thread#2 query "hello.example.com." --> resolver hold the request and wait for
548// response of previous pending query sent by thread#1.
549// step 4: thread#3 query "konbanha.example.com." --> resolver send query to server#3. Server
550// respond to resolver immediately.
551// step 5: check if server#1 get 1 query by thread#1, server#2 get 0 query, server#3 get 1 query.
552// step 6: resume dns server#1 to respond dns query in step#2.
553// step 7: thread#1 and #2 should get returned from DNS query after step#6. Also, check the
554// number of queries in server#2 is 0 to ensure thread#2 does not wake up unexpectedly
555// before signaled by thread#1.
556TEST_F(ResolverTest, GetAddrInfoV4_deferred_resp) {
557 const char* listen_addr1 = "127.0.0.9";
558 const char* listen_addr2 = "127.0.0.10";
559 const char* listen_addr3 = "127.0.0.11";
560 const char* listen_srv = "53";
561 const char* host_name_deferred = "hello.example.com.";
562 const char* host_name_normal = "konbanha.example.com.";
Mike Yufc125e42019-05-15 20:41:28 +0800563 test::DNSResponder dns1(listen_addr1, listen_srv, ns_rcode::ns_r_servfail);
564 test::DNSResponder dns2(listen_addr2, listen_srv, ns_rcode::ns_r_servfail);
565 test::DNSResponder dns3(listen_addr3, listen_srv, ns_rcode::ns_r_servfail);
Ken Chen92bed612018-12-22 21:46:55 +0800566 dns1.addMapping(host_name_deferred, ns_type::ns_t_a, "1.2.3.4");
567 dns2.addMapping(host_name_deferred, ns_type::ns_t_a, "1.2.3.4");
568 dns3.addMapping(host_name_normal, ns_type::ns_t_a, "1.2.3.5");
569 ASSERT_TRUE(dns1.startServer());
570 ASSERT_TRUE(dns2.startServer());
571 ASSERT_TRUE(dns3.startServer());
572 const std::vector<std::string> servers_for_t1 = {listen_addr1};
573 const std::vector<std::string> servers_for_t2 = {listen_addr2};
574 const std::vector<std::string> servers_for_t3 = {listen_addr3};
575 addrinfo hints = {.ai_family = AF_INET};
576 const std::vector<int> params = {300, 25, 8, 8, 5000};
577 bool t3_task_done = false;
578
579 dns1.setDeferredResp(true);
580 std::thread t1([&, this]() {
581 ASSERT_TRUE(
582 mDnsClient.SetResolversForNetwork(servers_for_t1, kDefaultSearchDomains, params));
583 ScopedAddrinfo result = safe_getaddrinfo(host_name_deferred, nullptr, &hints);
584 // t3's dns query should got returned first
585 EXPECT_TRUE(t3_task_done);
586 EXPECT_EQ(1U, GetNumQueries(dns1, host_name_deferred));
587 EXPECT_TRUE(result != nullptr);
588 EXPECT_EQ("1.2.3.4", ToString(result));
589 });
590
591 // ensuring t1 and t2 handler functions are processed in order
592 usleep(100 * 1000);
593 std::thread t2([&, this]() {
594 ASSERT_TRUE(
595 mDnsClient.SetResolversForNetwork(servers_for_t2, kDefaultSearchDomains, params));
596 ScopedAddrinfo result = safe_getaddrinfo(host_name_deferred, nullptr, &hints);
597 EXPECT_TRUE(t3_task_done);
598 EXPECT_EQ(0U, GetNumQueries(dns2, host_name_deferred));
599 EXPECT_TRUE(result != nullptr);
600 EXPECT_EQ("1.2.3.4", ToString(result));
601
602 std::vector<std::string> res_servers;
603 std::vector<std::string> res_domains;
604 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +0900605 res_params res_params;
Ken Chen92bed612018-12-22 21:46:55 +0800606 std::vector<ResolverStats> res_stats;
607 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +0800608 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers,
609 &res_domains, &res_tls_servers, &res_params, &res_stats,
610 &wait_for_pending_req_timeout_count));
Ken Chen92bed612018-12-22 21:46:55 +0800611 EXPECT_EQ(0, wait_for_pending_req_timeout_count);
612 });
613
614 // ensuring t2 and t3 handler functions are processed in order
615 usleep(100 * 1000);
616 std::thread t3([&, this]() {
617 ASSERT_TRUE(
618 mDnsClient.SetResolversForNetwork(servers_for_t3, kDefaultSearchDomains, params));
619 ScopedAddrinfo result = safe_getaddrinfo(host_name_normal, nullptr, &hints);
620 EXPECT_EQ(1U, GetNumQueries(dns1, host_name_deferred));
621 EXPECT_EQ(0U, GetNumQueries(dns2, host_name_deferred));
622 EXPECT_EQ(1U, GetNumQueries(dns3, host_name_normal));
623 EXPECT_TRUE(result != nullptr);
624 EXPECT_EQ("1.2.3.5", ToString(result));
625
626 t3_task_done = true;
627 dns1.setDeferredResp(false);
628 });
629 t3.join();
630 t1.join();
631 t2.join();
632}
633
lifr4e4a2e02019-01-29 16:53:51 +0800634TEST_F(ResolverTest, GetAddrInfo_cnames) {
635 constexpr char host_name[] = "host.example.com.";
636 test::DNSResponder dns;
637 const std::vector<DnsRecord> records = {
638 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
639 {"a.example.com.", ns_type::ns_t_cname, "b.example.com."},
640 {"b.example.com.", ns_type::ns_t_cname, "c.example.com."},
641 {"c.example.com.", ns_type::ns_t_cname, "d.example.com."},
642 {"d.example.com.", ns_type::ns_t_cname, "e.example.com."},
643 {"e.example.com.", ns_type::ns_t_cname, host_name},
644 {host_name, ns_type::ns_t_a, "1.2.3.3"},
645 {host_name, ns_type::ns_t_aaaa, "2001:db8::42"},
646 };
647 StartDns(dns, records);
648 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
649
650 addrinfo hints = {.ai_family = AF_INET};
651 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
652 EXPECT_TRUE(result != nullptr);
653 EXPECT_EQ("1.2.3.3", ToString(result));
654
655 dns.clearQueries();
656 hints = {.ai_family = AF_INET6};
657 result = safe_getaddrinfo("hello", nullptr, &hints);
658 EXPECT_TRUE(result != nullptr);
659 EXPECT_EQ("2001:db8::42", ToString(result));
660}
661
662TEST_F(ResolverTest, GetAddrInfo_cnamesNoIpAddress) {
663 test::DNSResponder dns;
664 const std::vector<DnsRecord> records = {
665 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
666 };
667 StartDns(dns, records);
668 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
669
670 addrinfo hints = {.ai_family = AF_INET};
671 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
672 EXPECT_TRUE(result == nullptr);
673
674 dns.clearQueries();
675 hints = {.ai_family = AF_INET6};
676 result = safe_getaddrinfo("hello", nullptr, &hints);
677 EXPECT_TRUE(result == nullptr);
678}
679
680TEST_F(ResolverTest, GetAddrInfo_cnamesIllegalRdata) {
681 test::DNSResponder dns;
682 const std::vector<DnsRecord> records = {
683 {kHelloExampleCom, ns_type::ns_t_cname, ".!#?"},
684 };
685 StartDns(dns, records);
686 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
687
688 addrinfo hints = {.ai_family = AF_INET};
689 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
690 EXPECT_TRUE(result == nullptr);
691
692 dns.clearQueries();
693 hints = {.ai_family = AF_INET6};
694 result = safe_getaddrinfo("hello", nullptr, &hints);
695 EXPECT_TRUE(result == nullptr);
696}
697
Ken Chenb9fa2062018-11-13 21:51:13 +0800698TEST_F(ResolverTest, MultidomainResolution) {
Xiao Ma09b71022018-12-11 17:56:32 +0900699 constexpr char host_name[] = "nihao.example2.com.";
Ken Chenb9fa2062018-11-13 21:51:13 +0800700 std::vector<std::string> searchDomains = { "example1.com", "example2.com", "example3.com" };
Ken Chenb9fa2062018-11-13 21:51:13 +0800701
Xiao Ma09b71022018-12-11 17:56:32 +0900702 test::DNSResponder dns("127.0.0.6");
703 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.3"}});
704 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({"127.0.0.6"}, searchDomains));
705
Ken Chenb9fa2062018-11-13 21:51:13 +0800706 const hostent* result = gethostbyname("nihao");
Xiao Ma09b71022018-12-11 17:56:32 +0900707
Ken Chenb9fa2062018-11-13 21:51:13 +0800708 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
709 ASSERT_FALSE(result == nullptr);
710 ASSERT_EQ(4, result->h_length);
711 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
712 EXPECT_EQ("1.2.3.3", ToString(result));
713 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800714}
715
716TEST_F(ResolverTest, GetAddrInfoV6_numeric) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800717 constexpr char host_name[] = "ohayou.example.com.";
718 constexpr char numeric_addr[] = "fe80::1%lo";
719
Xiao Ma09b71022018-12-11 17:56:32 +0900720 test::DNSResponder dns;
Ken Chenb9fa2062018-11-13 21:51:13 +0800721 dns.setResponseProbability(0.0);
Xiao Ma09b71022018-12-11 17:56:32 +0900722 StartDns(dns, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
723 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800724
725 addrinfo hints = {.ai_family = AF_INET6};
726 ScopedAddrinfo result = safe_getaddrinfo(numeric_addr, nullptr, &hints);
727 EXPECT_TRUE(result != nullptr);
728 EXPECT_EQ(numeric_addr, ToString(result));
729 EXPECT_TRUE(dns.queries().empty()); // Ensure no DNS queries were sent out
730
731 // Now try a non-numeric hostname query with the AI_NUMERICHOST flag set.
732 // We should fail without sending out a DNS query.
733 hints.ai_flags |= AI_NUMERICHOST;
734 result = safe_getaddrinfo(host_name, nullptr, &hints);
735 EXPECT_TRUE(result == nullptr);
736 EXPECT_TRUE(dns.queries().empty()); // Ensure no DNS queries were sent out
737}
738
739TEST_F(ResolverTest, GetAddrInfoV6_failing) {
Xiao Ma09b71022018-12-11 17:56:32 +0900740 constexpr char listen_addr0[] = "127.0.0.7";
741 constexpr char listen_addr1[] = "127.0.0.8";
Ken Chenb9fa2062018-11-13 21:51:13 +0800742 const char* host_name = "ohayou.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +0900743
744 test::DNSResponder dns0(listen_addr0);
745 test::DNSResponder dns1(listen_addr1);
Ken Chenb9fa2062018-11-13 21:51:13 +0800746 dns0.setResponseProbability(0.0);
Xiao Ma09b71022018-12-11 17:56:32 +0900747 StartDns(dns0, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
748 StartDns(dns1, {{host_name, ns_type::ns_t_aaaa, "2001:db8::6"}});
749
Ken Chenb9fa2062018-11-13 21:51:13 +0800750 std::vector<std::string> servers = { listen_addr0, listen_addr1 };
751 // <sample validity in s> <success threshold in percent> <min samples> <max samples>
752 int sample_count = 8;
753 const std::vector<int> params = { 300, 25, sample_count, sample_count };
Xiao Ma09b71022018-12-11 17:56:32 +0900754 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, kDefaultSearchDomains, params));
Ken Chenb9fa2062018-11-13 21:51:13 +0800755
756 // Repeatedly perform resolutions for non-existing domains until MAXNSSAMPLES resolutions have
757 // reached the dns0, which is set to fail. No more requests should then arrive at that server
758 // for the next sample_lifetime seconds.
759 // TODO: This approach is implementation-dependent, change once metrics reporting is available.
Xiao Ma09b71022018-12-11 17:56:32 +0900760 const addrinfo hints = {.ai_family = AF_INET6};
Bernie Innocentib102dd22018-12-04 14:57:48 +0900761 for (int i = 0; i < sample_count; ++i) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800762 std::string domain = StringPrintf("nonexistent%d", i);
763 ScopedAddrinfo result = safe_getaddrinfo(domain.c_str(), nullptr, &hints);
764 }
765 // Due to 100% errors for all possible samples, the server should be ignored from now on and
766 // only the second one used for all following queries, until NSSAMPLE_VALIDITY is reached.
767 dns0.clearQueries();
768 dns1.clearQueries();
769 ScopedAddrinfo result = safe_getaddrinfo("ohayou", nullptr, &hints);
770 EXPECT_TRUE(result != nullptr);
771 EXPECT_EQ(0U, GetNumQueries(dns0, host_name));
772 EXPECT_EQ(1U, GetNumQueries(dns1, host_name));
773}
774
775TEST_F(ResolverTest, GetAddrInfoV6_nonresponsive) {
Xiao Ma09b71022018-12-11 17:56:32 +0900776 constexpr char listen_addr0[] = "127.0.0.7";
777 constexpr char listen_addr1[] = "127.0.0.8";
778 constexpr char listen_srv[] = "53";
779 constexpr char host_name1[] = "ohayou.example.com.";
780 constexpr char host_name2[] = "ciao.example.com.";
Luke Huang483cf332019-06-03 17:24:51 +0800781 const std::vector<std::string> defaultSearchDomain = {"example.com"};
782 // The minimal timeout is 1000ms, so we can't decrease timeout
783 // So reduce retry count.
784 const std::vector<int> reduceRetryParams = {
785 300, // sample validity in seconds
786 25, // success threshod in percent
787 8, 8, // {MIN,MAX}_SAMPLES
788 1000, // BASE_TIMEOUT_MSEC
789 1, // retry count
790 };
Xiao Ma09b71022018-12-11 17:56:32 +0900791 const std::vector<DnsRecord> records0 = {
792 {host_name1, ns_type::ns_t_aaaa, "2001:db8::5"},
793 {host_name2, ns_type::ns_t_aaaa, "2001:db8::5"},
794 };
795 const std::vector<DnsRecord> records1 = {
796 {host_name1, ns_type::ns_t_aaaa, "2001:db8::6"},
797 {host_name2, ns_type::ns_t_aaaa, "2001:db8::6"},
798 };
Ken Chenb9fa2062018-11-13 21:51:13 +0800799
800 // dns0 does not respond with 100% probability, while
801 // dns1 responds normally, at least initially.
Mike Yufc125e42019-05-15 20:41:28 +0800802 test::DNSResponder dns0(listen_addr0, listen_srv, static_cast<ns_rcode>(-1));
803 test::DNSResponder dns1(listen_addr1, listen_srv, static_cast<ns_rcode>(-1));
Ken Chenb9fa2062018-11-13 21:51:13 +0800804 dns0.setResponseProbability(0.0);
Xiao Ma09b71022018-12-11 17:56:32 +0900805 StartDns(dns0, records0);
806 StartDns(dns1, records1);
Luke Huang483cf332019-06-03 17:24:51 +0800807 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr0, listen_addr1}, defaultSearchDomain,
808 reduceRetryParams));
Ken Chenb9fa2062018-11-13 21:51:13 +0800809
Luke Huang483cf332019-06-03 17:24:51 +0800810 // Specify ai_socktype to make getaddrinfo will only query 1 time
811 const addrinfo hints = {.ai_family = AF_INET6, .ai_socktype = SOCK_STREAM};
Ken Chenb9fa2062018-11-13 21:51:13 +0800812
813 // dns0 will ignore the request, and we'll fallback to dns1 after the first
814 // retry.
815 ScopedAddrinfo result = safe_getaddrinfo(host_name1, nullptr, &hints);
816 EXPECT_TRUE(result != nullptr);
817 EXPECT_EQ(1U, GetNumQueries(dns0, host_name1));
818 EXPECT_EQ(1U, GetNumQueries(dns1, host_name1));
819
820 // Now make dns1 also ignore 100% requests... The resolve should alternate
Luke Huang483cf332019-06-03 17:24:51 +0800821 // queries between the nameservers and fail
Ken Chenb9fa2062018-11-13 21:51:13 +0800822 dns1.setResponseProbability(0.0);
823 addrinfo* result2 = nullptr;
824 EXPECT_EQ(EAI_NODATA, getaddrinfo(host_name2, nullptr, &hints, &result2));
825 EXPECT_EQ(nullptr, result2);
Luke Huang483cf332019-06-03 17:24:51 +0800826 EXPECT_EQ(1U, GetNumQueries(dns0, host_name2));
827 EXPECT_EQ(1U, GetNumQueries(dns1, host_name2));
Ken Chenb9fa2062018-11-13 21:51:13 +0800828}
829
830TEST_F(ResolverTest, GetAddrInfoV6_concurrent) {
Xiao Ma09b71022018-12-11 17:56:32 +0900831 constexpr char listen_addr0[] = "127.0.0.9";
832 constexpr char listen_addr1[] = "127.0.0.10";
833 constexpr char listen_addr2[] = "127.0.0.11";
834 constexpr char host_name[] = "konbanha.example.com.";
835
836 test::DNSResponder dns0(listen_addr0);
837 test::DNSResponder dns1(listen_addr1);
838 test::DNSResponder dns2(listen_addr2);
839 StartDns(dns0, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
840 StartDns(dns1, {{host_name, ns_type::ns_t_aaaa, "2001:db8::6"}});
841 StartDns(dns2, {{host_name, ns_type::ns_t_aaaa, "2001:db8::7"}});
842
Ken Chenb9fa2062018-11-13 21:51:13 +0800843 const std::vector<std::string> servers = { listen_addr0, listen_addr1, listen_addr2 };
844 std::vector<std::thread> threads(10);
845 for (std::thread& thread : threads) {
846 thread = std::thread([this, &servers]() {
847 unsigned delay = arc4random_uniform(1*1000*1000); // <= 1s
848 usleep(delay);
849 std::vector<std::string> serverSubset;
850 for (const auto& server : servers) {
851 if (arc4random_uniform(2)) {
852 serverSubset.push_back(server);
853 }
854 }
855 if (serverSubset.empty()) serverSubset = servers;
Xiao Ma09b71022018-12-11 17:56:32 +0900856 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(serverSubset));
857 const addrinfo hints = {.ai_family = AF_INET6};
Ken Chenb9fa2062018-11-13 21:51:13 +0800858 addrinfo* result = nullptr;
859 int rv = getaddrinfo("konbanha", nullptr, &hints, &result);
860 EXPECT_EQ(0, rv) << "error [" << rv << "] " << gai_strerror(rv);
861 if (result) {
862 freeaddrinfo(result);
863 result = nullptr;
864 }
865 });
866 }
867 for (std::thread& thread : threads) {
868 thread.join();
869 }
Ken Chen92bed612018-12-22 21:46:55 +0800870
871 std::vector<std::string> res_servers;
872 std::vector<std::string> res_domains;
873 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +0900874 res_params res_params;
Ken Chen92bed612018-12-22 21:46:55 +0800875 std::vector<ResolverStats> res_stats;
876 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +0800877 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
878 &res_tls_servers, &res_params, &res_stats,
879 &wait_for_pending_req_timeout_count));
Ken Chen92bed612018-12-22 21:46:55 +0800880 EXPECT_EQ(0, wait_for_pending_req_timeout_count);
Ken Chenb9fa2062018-11-13 21:51:13 +0800881}
882
Ken Chenb9fa2062018-11-13 21:51:13 +0800883TEST_F(ResolverTest, EmptySetup) {
Luke Huang5bd827c2019-03-14 16:10:04 +0800884 using android::net::IDnsResolver;
Ken Chenb9fa2062018-11-13 21:51:13 +0800885 std::vector<std::string> servers;
886 std::vector<std::string> domains;
Xiao Ma09b71022018-12-11 17:56:32 +0900887 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
Ken Chenb9fa2062018-11-13 21:51:13 +0800888 std::vector<std::string> res_servers;
889 std::vector<std::string> res_domains;
Mike Yu0a1c53d2018-11-26 13:26:21 +0900890 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +0900891 res_params res_params;
Ken Chenb9fa2062018-11-13 21:51:13 +0800892 std::vector<ResolverStats> res_stats;
Ken Chen92bed612018-12-22 21:46:55 +0800893 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +0800894 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
895 &res_tls_servers, &res_params, &res_stats,
896 &wait_for_pending_req_timeout_count));
Ken Chenb9fa2062018-11-13 21:51:13 +0800897 EXPECT_EQ(0U, res_servers.size());
898 EXPECT_EQ(0U, res_domains.size());
Mike Yu0a1c53d2018-11-26 13:26:21 +0900899 EXPECT_EQ(0U, res_tls_servers.size());
Luke Huang5bd827c2019-03-14 16:10:04 +0800900 ASSERT_EQ(static_cast<size_t>(IDnsResolver::RESOLVER_PARAMS_COUNT), kDefaultParams.size());
901 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY],
902 res_params.sample_validity);
903 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD],
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900904 res_params.success_threshold);
Luke Huang5bd827c2019-03-14 16:10:04 +0800905 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES], res_params.min_samples);
906 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES], res_params.max_samples);
907 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
Ken Chenb9fa2062018-11-13 21:51:13 +0800908 res_params.base_timeout_msec);
Luke Huang5bd827c2019-03-14 16:10:04 +0800909 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT], res_params.retry_count);
Ken Chenb9fa2062018-11-13 21:51:13 +0800910}
911
912TEST_F(ResolverTest, SearchPathChange) {
Xiao Ma09b71022018-12-11 17:56:32 +0900913 constexpr char listen_addr[] = "127.0.0.13";
914 constexpr char host_name1[] = "test13.domain1.org.";
915 constexpr char host_name2[] = "test13.domain2.org.";
Ken Chenb9fa2062018-11-13 21:51:13 +0800916 std::vector<std::string> servers = { listen_addr };
917 std::vector<std::string> domains = { "domain1.org" };
Xiao Ma09b71022018-12-11 17:56:32 +0900918
919 const std::vector<DnsRecord> records = {
920 {host_name1, ns_type::ns_t_aaaa, "2001:db8::13"},
921 {host_name2, ns_type::ns_t_aaaa, "2001:db8::1:13"},
922 };
923 test::DNSResponder dns(listen_addr);
924 StartDns(dns, records);
925 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
Ken Chenb9fa2062018-11-13 21:51:13 +0800926
927 const addrinfo hints = {.ai_family = AF_INET6};
928 ScopedAddrinfo result = safe_getaddrinfo("test13", nullptr, &hints);
929 EXPECT_TRUE(result != nullptr);
930 EXPECT_EQ(1U, dns.queries().size());
931 EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
932 EXPECT_EQ("2001:db8::13", ToString(result));
933
934 // Test that changing the domain search path on its own works.
935 domains = { "domain2.org" };
Xiao Ma09b71022018-12-11 17:56:32 +0900936 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
Ken Chenb9fa2062018-11-13 21:51:13 +0800937 dns.clearQueries();
938
939 result = safe_getaddrinfo("test13", nullptr, &hints);
940 EXPECT_TRUE(result != nullptr);
941 EXPECT_EQ(1U, dns.queries().size());
942 EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
943 EXPECT_EQ("2001:db8::1:13", ToString(result));
944}
945
Ken Chenb9fa2062018-11-13 21:51:13 +0800946static std::string base64Encode(const std::vector<uint8_t>& input) {
947 size_t out_len;
948 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
949 // out_len includes the trailing NULL.
950 uint8_t output_bytes[out_len];
951 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
952 return std::string(reinterpret_cast<char*>(output_bytes));
953}
954
Mike Yu0a1c53d2018-11-26 13:26:21 +0900955// If we move this function to dns_responder_client, it will complicate the dependency need of
956// dns_tls_frontend.h.
957static void setupTlsServers(const std::vector<std::string>& servers,
958 std::vector<std::unique_ptr<test::DnsTlsFrontend>>* tls,
959 std::vector<std::string>* fingerprints) {
Xiao Ma09b71022018-12-11 17:56:32 +0900960 constexpr char listen_udp[] = "53";
961 constexpr char listen_tls[] = "853";
Mike Yu0a1c53d2018-11-26 13:26:21 +0900962
963 for (const auto& server : servers) {
964 auto t = std::make_unique<test::DnsTlsFrontend>(server, listen_tls, server, listen_udp);
965 t = std::make_unique<test::DnsTlsFrontend>(server, listen_tls, server, listen_udp);
966 t->startServer();
967 fingerprints->push_back(base64Encode(t->fingerprint()));
968 tls->push_back(std::move(t));
969 }
970}
971
Mike Yu0a1c53d2018-11-26 13:26:21 +0900972TEST_F(ResolverTest, MaxServerPrune_Binder) {
Mike Yu0a1c53d2018-11-26 13:26:21 +0900973 std::vector<std::string> domains;
974 std::vector<std::unique_ptr<test::DNSResponder>> dns;
975 std::vector<std::unique_ptr<test::DnsTlsFrontend>> tls;
976 std::vector<std::string> servers;
977 std::vector<std::string> fingerprints;
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900978 std::vector<DnsResponderClient::Mapping> mappings;
Mike Yu0a1c53d2018-11-26 13:26:21 +0900979
980 for (unsigned i = 0; i < MAXDNSRCH + 1; i++) {
981 domains.push_back(StringPrintf("example%u.com", i));
982 }
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900983 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(1, domains, &mappings));
984 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(MAXNS + 1, mappings, &dns, &servers));
Mike Yu0a1c53d2018-11-26 13:26:21 +0900985 ASSERT_NO_FATAL_FAILURE(setupTlsServers(servers, &tls, &fingerprints));
986
Xiao Ma09b71022018-12-11 17:56:32 +0900987 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, domains, kDefaultParams, "", fingerprints));
Mike Yu0a1c53d2018-11-26 13:26:21 +0900988
Mike Yu383855b2019-01-15 17:53:27 +0800989 // If the private DNS validation hasn't completed yet before backend DNS servers stop,
990 // TLS servers will get stuck in handleOneRequest(), which causes this test stuck in
991 // ~DnsTlsFrontend() because the TLS server loop threads can't be terminated.
992 // So, wait for private DNS validation done before stopping backend DNS servers.
993 for (int i = 0; i < MAXNS; i++) {
chenbruceaff85842019-05-31 15:46:42 +0800994 LOG(INFO) << "Waiting for private DNS validation on " << tls[i]->listen_address() << ".";
Mike Yu383855b2019-01-15 17:53:27 +0800995 EXPECT_TRUE(tls[i]->waitForQueries(1, 5000));
chenbruceaff85842019-05-31 15:46:42 +0800996 LOG(INFO) << "private DNS validation on " << tls[i]->listen_address() << " done.";
Mike Yu383855b2019-01-15 17:53:27 +0800997 }
998
Mike Yu0a1c53d2018-11-26 13:26:21 +0900999 std::vector<std::string> res_servers;
1000 std::vector<std::string> res_domains;
1001 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +09001002 res_params res_params;
Mike Yu0a1c53d2018-11-26 13:26:21 +09001003 std::vector<ResolverStats> res_stats;
Ken Chen92bed612018-12-22 21:46:55 +08001004 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +08001005 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
1006 &res_tls_servers, &res_params, &res_stats,
1007 &wait_for_pending_req_timeout_count));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001008
1009 // Check the size of the stats and its contents.
1010 EXPECT_EQ(static_cast<size_t>(MAXNS), res_servers.size());
1011 EXPECT_EQ(static_cast<size_t>(MAXNS), res_tls_servers.size());
1012 EXPECT_EQ(static_cast<size_t>(MAXDNSRCH), res_domains.size());
1013 EXPECT_TRUE(std::equal(servers.begin(), servers.begin() + MAXNS, res_servers.begin()));
1014 EXPECT_TRUE(std::equal(servers.begin(), servers.begin() + MAXNS, res_tls_servers.begin()));
1015 EXPECT_TRUE(std::equal(domains.begin(), domains.begin() + MAXDNSRCH, res_domains.begin()));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001016}
1017
1018TEST_F(ResolverTest, ResolverStats) {
Xiao Ma09b71022018-12-11 17:56:32 +09001019 constexpr char listen_addr1[] = "127.0.0.4";
1020 constexpr char listen_addr2[] = "127.0.0.5";
1021 constexpr char listen_addr3[] = "127.0.0.6";
Mike Yu0a1c53d2018-11-26 13:26:21 +09001022
1023 // Set server 1 timeout.
Mike Yufc125e42019-05-15 20:41:28 +08001024 test::DNSResponder dns1(listen_addr1, "53", static_cast<ns_rcode>(-1));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001025 dns1.setResponseProbability(0.0);
1026 ASSERT_TRUE(dns1.startServer());
1027
1028 // Set server 2 responding server failure.
Xiao Ma09b71022018-12-11 17:56:32 +09001029 test::DNSResponder dns2(listen_addr2);
Mike Yu0a1c53d2018-11-26 13:26:21 +09001030 dns2.setResponseProbability(0.0);
1031 ASSERT_TRUE(dns2.startServer());
1032
1033 // Set server 3 workable.
Xiao Ma09b71022018-12-11 17:56:32 +09001034 test::DNSResponder dns3(listen_addr3);
1035 dns3.addMapping(kHelloExampleCom, ns_type::ns_t_a, "1.2.3.4");
Mike Yu0a1c53d2018-11-26 13:26:21 +09001036 ASSERT_TRUE(dns3.startServer());
1037
1038 std::vector<std::string> servers = {listen_addr1, listen_addr2, listen_addr3};
Xiao Ma09b71022018-12-11 17:56:32 +09001039 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001040
1041 dns3.clearQueries();
Xiao Ma09b71022018-12-11 17:56:32 +09001042 const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
Mike Yu0a1c53d2018-11-26 13:26:21 +09001043 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
Xiao Ma09b71022018-12-11 17:56:32 +09001044 size_t found = GetNumQueries(dns3, kHelloExampleCom);
Mike Yu0a1c53d2018-11-26 13:26:21 +09001045 EXPECT_LE(1U, found);
1046 std::string result_str = ToString(result);
1047 EXPECT_TRUE(result_str == "1.2.3.4") << ", result_str='" << result_str << "'";
1048
1049 std::vector<std::string> res_servers;
1050 std::vector<std::string> res_domains;
1051 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +09001052 res_params res_params;
Mike Yu0a1c53d2018-11-26 13:26:21 +09001053 std::vector<ResolverStats> res_stats;
Ken Chen92bed612018-12-22 21:46:55 +08001054 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +08001055 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
1056 &res_tls_servers, &res_params, &res_stats,
1057 &wait_for_pending_req_timeout_count));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001058
1059 EXPECT_EQ(1, res_stats[0].timeouts);
1060 EXPECT_EQ(1, res_stats[1].errors);
1061 EXPECT_EQ(1, res_stats[2].successes);
Mike Yu0a1c53d2018-11-26 13:26:21 +09001062}
1063
Ken Chenb9fa2062018-11-13 21:51:13 +08001064// Test what happens if the specified TLS server is nonexistent.
1065TEST_F(ResolverTest, GetHostByName_TlsMissing) {
Xiao Ma09b71022018-12-11 17:56:32 +09001066 constexpr char listen_addr[] = "127.0.0.3";
1067 constexpr char host_name[] = "tlsmissing.example.com.";
1068
1069 test::DNSResponder dns;
1070 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.3"}});
Ken Chenb9fa2062018-11-13 21:51:13 +08001071 std::vector<std::string> servers = { listen_addr };
1072
1073 // There's nothing listening on this address, so validation will either fail or
1074 /// hang. Either way, queries will continue to flow to the DNSResponder.
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001075 ASSERT_TRUE(
Xiao Ma09b71022018-12-11 17:56:32 +09001076 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
Ken Chenb9fa2062018-11-13 21:51:13 +08001077
1078 const hostent* result;
1079
1080 result = gethostbyname("tlsmissing");
1081 ASSERT_FALSE(result == nullptr);
1082 EXPECT_EQ("1.2.3.3", ToString(result));
1083
1084 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001085 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001086}
1087
1088// Test what happens if the specified TLS server replies with garbage.
1089TEST_F(ResolverTest, GetHostByName_TlsBroken) {
Xiao Ma09b71022018-12-11 17:56:32 +09001090 constexpr char listen_addr[] = "127.0.0.3";
1091 constexpr char host_name1[] = "tlsbroken1.example.com.";
1092 constexpr char host_name2[] = "tlsbroken2.example.com.";
1093 const std::vector<DnsRecord> records = {
1094 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1095 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1096 };
1097
1098 test::DNSResponder dns;
1099 StartDns(dns, records);
Ken Chenb9fa2062018-11-13 21:51:13 +08001100 std::vector<std::string> servers = { listen_addr };
1101
1102 // Bind the specified private DNS socket but don't respond to any client sockets yet.
1103 int s = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP);
1104 ASSERT_TRUE(s >= 0);
1105 struct sockaddr_in tlsServer = {
1106 .sin_family = AF_INET,
1107 .sin_port = htons(853),
1108 };
1109 ASSERT_TRUE(inet_pton(AF_INET, listen_addr, &tlsServer.sin_addr));
1110 ASSERT_TRUE(enableSockopt(s, SOL_SOCKET, SO_REUSEPORT).ok());
1111 ASSERT_TRUE(enableSockopt(s, SOL_SOCKET, SO_REUSEADDR).ok());
1112 ASSERT_FALSE(bind(s, reinterpret_cast<struct sockaddr*>(&tlsServer), sizeof(tlsServer)));
1113 ASSERT_FALSE(listen(s, 1));
1114
1115 // Trigger TLS validation.
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001116 ASSERT_TRUE(
Xiao Ma09b71022018-12-11 17:56:32 +09001117 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
Ken Chenb9fa2062018-11-13 21:51:13 +08001118
1119 struct sockaddr_storage cliaddr;
1120 socklen_t sin_size = sizeof(cliaddr);
1121 int new_fd = accept4(s, reinterpret_cast<struct sockaddr *>(&cliaddr), &sin_size, SOCK_CLOEXEC);
1122 ASSERT_TRUE(new_fd > 0);
1123
1124 // We've received the new file descriptor but not written to it or closed, so the
1125 // validation is still pending. Queries should still flow correctly because the
1126 // server is not used until validation succeeds.
1127 const hostent* result;
1128 result = gethostbyname("tlsbroken1");
1129 ASSERT_FALSE(result == nullptr);
1130 EXPECT_EQ("1.2.3.1", ToString(result));
1131
1132 // Now we cause the validation to fail.
1133 std::string garbage = "definitely not a valid TLS ServerHello";
1134 write(new_fd, garbage.data(), garbage.size());
1135 close(new_fd);
1136
1137 // Validation failure shouldn't interfere with lookups, because lookups won't be sent
1138 // to the TLS server unless validation succeeds.
1139 result = gethostbyname("tlsbroken2");
1140 ASSERT_FALSE(result == nullptr);
1141 EXPECT_EQ("1.2.3.2", ToString(result));
1142
1143 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001144 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001145 close(s);
1146}
1147
1148TEST_F(ResolverTest, GetHostByName_Tls) {
Xiao Ma09b71022018-12-11 17:56:32 +09001149 constexpr char listen_addr[] = "127.0.0.3";
1150 constexpr char listen_udp[] = "53";
1151 constexpr char listen_tls[] = "853";
1152 constexpr char host_name1[] = "tls1.example.com.";
1153 constexpr char host_name2[] = "tls2.example.com.";
1154 constexpr char host_name3[] = "tls3.example.com.";
1155 const std::vector<DnsRecord> records = {
1156 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1157 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1158 {host_name3, ns_type::ns_t_a, "1.2.3.3"},
1159 };
1160
1161 test::DNSResponder dns;
1162 StartDns(dns, records);
Ken Chenb9fa2062018-11-13 21:51:13 +08001163 std::vector<std::string> servers = { listen_addr };
1164
1165 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1166 ASSERT_TRUE(tls.startServer());
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001167 ASSERT_TRUE(
Xiao Ma09b71022018-12-11 17:56:32 +09001168 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
Ken Chenb9fa2062018-11-13 21:51:13 +08001169
1170 const hostent* result;
1171
1172 // Wait for validation to complete.
1173 EXPECT_TRUE(tls.waitForQueries(1, 5000));
1174
1175 result = gethostbyname("tls1");
1176 ASSERT_FALSE(result == nullptr);
1177 EXPECT_EQ("1.2.3.1", ToString(result));
1178
1179 // Wait for query to get counted.
1180 EXPECT_TRUE(tls.waitForQueries(2, 5000));
1181
1182 // Stop the TLS server. Since we're in opportunistic mode, queries will
1183 // fall back to the locally-assigned (clear text) nameservers.
1184 tls.stopServer();
1185
1186 dns.clearQueries();
1187 result = gethostbyname("tls2");
1188 EXPECT_FALSE(result == nullptr);
1189 EXPECT_EQ("1.2.3.2", ToString(result));
1190 const auto queries = dns.queries();
1191 EXPECT_EQ(1U, queries.size());
1192 EXPECT_EQ("tls2.example.com.", queries[0].first);
1193 EXPECT_EQ(ns_t_a, queries[0].second);
1194
1195 // Reset the resolvers without enabling TLS. Queries should still be routed
1196 // to the UDP endpoint.
Xiao Ma09b71022018-12-11 17:56:32 +09001197 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001198
1199 result = gethostbyname("tls3");
1200 ASSERT_FALSE(result == nullptr);
1201 EXPECT_EQ("1.2.3.3", ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +08001202}
1203
1204TEST_F(ResolverTest, GetHostByName_TlsFingerprint) {
Xiao Ma09b71022018-12-11 17:56:32 +09001205 constexpr char listen_addr[] = "127.0.0.3";
1206 constexpr char listen_udp[] = "53";
1207 constexpr char listen_tls[] = "853";
1208 test::DNSResponder dns;
Ken Chenb9fa2062018-11-13 21:51:13 +08001209 ASSERT_TRUE(dns.startServer());
1210 for (int chain_length = 1; chain_length <= 3; ++chain_length) {
1211 std::string host_name = StringPrintf("tlsfingerprint%d.example.com.", chain_length);
1212 dns.addMapping(host_name, ns_type::ns_t_a, "1.2.3.1");
1213 std::vector<std::string> servers = { listen_addr };
1214
1215 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1216 tls.set_chain_length(chain_length);
1217 ASSERT_TRUE(tls.startServer());
Xiao Ma09b71022018-12-11 17:56:32 +09001218 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001219 "", {base64Encode(tls.fingerprint())}));
Ken Chenb9fa2062018-11-13 21:51:13 +08001220
1221 const hostent* result;
1222
1223 // Wait for validation to complete.
1224 EXPECT_TRUE(tls.waitForQueries(1, 5000));
1225
1226 result = gethostbyname(StringPrintf("tlsfingerprint%d", chain_length).c_str());
1227 EXPECT_FALSE(result == nullptr);
1228 if (result) {
1229 EXPECT_EQ("1.2.3.1", ToString(result));
1230
1231 // Wait for query to get counted.
1232 EXPECT_TRUE(tls.waitForQueries(2, 5000));
1233 }
1234
1235 // Clear TLS bit to ensure revalidation.
Xiao Ma09b71022018-12-11 17:56:32 +09001236 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001237 tls.stopServer();
1238 }
Ken Chenb9fa2062018-11-13 21:51:13 +08001239}
1240
1241TEST_F(ResolverTest, GetHostByName_BadTlsFingerprint) {
Xiao Ma09b71022018-12-11 17:56:32 +09001242 constexpr char listen_addr[] = "127.0.0.3";
1243 constexpr char listen_udp[] = "53";
1244 constexpr char listen_tls[] = "853";
1245 constexpr char host_name[] = "badtlsfingerprint.example.com.";
1246
1247 test::DNSResponder dns;
1248 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.1"}});
Ken Chenb9fa2062018-11-13 21:51:13 +08001249 std::vector<std::string> servers = { listen_addr };
1250
1251 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1252 ASSERT_TRUE(tls.startServer());
1253 std::vector<uint8_t> bad_fingerprint = tls.fingerprint();
1254 bad_fingerprint[5] += 1; // Corrupt the fingerprint.
Xiao Ma09b71022018-12-11 17:56:32 +09001255 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "",
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001256 {base64Encode(bad_fingerprint)}));
Ken Chenb9fa2062018-11-13 21:51:13 +08001257
1258 // The initial validation should fail at the fingerprint check before
1259 // issuing a query.
1260 EXPECT_FALSE(tls.waitForQueries(1, 500));
1261
1262 // A fingerprint was provided and failed to match, so the query should fail.
1263 EXPECT_EQ(nullptr, gethostbyname("badtlsfingerprint"));
1264
1265 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001266 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001267}
1268
1269// Test that we can pass two different fingerprints, and connection succeeds as long as
1270// at least one of them matches the server.
1271TEST_F(ResolverTest, GetHostByName_TwoTlsFingerprints) {
Xiao Ma09b71022018-12-11 17:56:32 +09001272 constexpr char listen_addr[] = "127.0.0.3";
1273 constexpr char listen_udp[] = "53";
1274 constexpr char listen_tls[] = "853";
1275 constexpr char host_name[] = "twotlsfingerprints.example.com.";
1276
1277 test::DNSResponder dns;
1278 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.1"}});
Ken Chenb9fa2062018-11-13 21:51:13 +08001279 std::vector<std::string> servers = { listen_addr };
1280
1281 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1282 ASSERT_TRUE(tls.startServer());
1283 std::vector<uint8_t> bad_fingerprint = tls.fingerprint();
1284 bad_fingerprint[5] += 1; // Corrupt the fingerprint.
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001285 ASSERT_TRUE(mDnsClient.SetResolversWithTls(
Xiao Ma09b71022018-12-11 17:56:32 +09001286 servers, kDefaultSearchDomains, kDefaultParams, "",
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001287 {base64Encode(bad_fingerprint), base64Encode(tls.fingerprint())}));
Ken Chenb9fa2062018-11-13 21:51:13 +08001288
1289 const hostent* result;
1290
1291 // Wait for validation to complete.
1292 EXPECT_TRUE(tls.waitForQueries(1, 5000));
1293
1294 result = gethostbyname("twotlsfingerprints");
1295 ASSERT_FALSE(result == nullptr);
1296 EXPECT_EQ("1.2.3.1", ToString(result));
1297
1298 // Wait for query to get counted.
1299 EXPECT_TRUE(tls.waitForQueries(2, 5000));
1300
1301 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001302 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001303}
1304
1305TEST_F(ResolverTest, GetHostByName_TlsFingerprintGoesBad) {
Xiao Ma09b71022018-12-11 17:56:32 +09001306 constexpr char listen_addr[] = "127.0.0.3";
1307 constexpr char listen_udp[] = "53";
1308 constexpr char listen_tls[] = "853";
1309 constexpr char host_name1[] = "tlsfingerprintgoesbad1.example.com.";
1310 constexpr char host_name2[] = "tlsfingerprintgoesbad2.example.com.";
1311 const std::vector<DnsRecord> records = {
1312 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1313 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1314 };
1315
1316 test::DNSResponder dns;
1317 StartDns(dns, records);
Ken Chenb9fa2062018-11-13 21:51:13 +08001318 std::vector<std::string> servers = { listen_addr };
1319
1320 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1321 ASSERT_TRUE(tls.startServer());
Xiao Ma09b71022018-12-11 17:56:32 +09001322 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "",
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001323 {base64Encode(tls.fingerprint())}));
Ken Chenb9fa2062018-11-13 21:51:13 +08001324
1325 const hostent* result;
1326
1327 // Wait for validation to complete.
1328 EXPECT_TRUE(tls.waitForQueries(1, 5000));
1329
1330 result = gethostbyname("tlsfingerprintgoesbad1");
1331 ASSERT_FALSE(result == nullptr);
1332 EXPECT_EQ("1.2.3.1", ToString(result));
1333
1334 // Wait for query to get counted.
1335 EXPECT_TRUE(tls.waitForQueries(2, 5000));
1336
1337 // Restart the TLS server. This will generate a new certificate whose fingerprint
1338 // no longer matches the stored fingerprint.
1339 tls.stopServer();
1340 tls.startServer();
1341
1342 result = gethostbyname("tlsfingerprintgoesbad2");
1343 ASSERT_TRUE(result == nullptr);
1344 EXPECT_EQ(HOST_NOT_FOUND, h_errno);
1345
1346 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001347 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001348}
1349
1350TEST_F(ResolverTest, GetHostByName_TlsFailover) {
Xiao Ma09b71022018-12-11 17:56:32 +09001351 constexpr char listen_addr1[] = "127.0.0.3";
1352 constexpr char listen_addr2[] = "127.0.0.4";
1353 constexpr char listen_udp[] = "53";
1354 constexpr char listen_tls[] = "853";
1355 constexpr char host_name1[] = "tlsfailover1.example.com.";
1356 constexpr char host_name2[] = "tlsfailover2.example.com.";
1357 const std::vector<DnsRecord> records1 = {
1358 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1359 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1360 };
1361 const std::vector<DnsRecord> records2 = {
1362 {host_name1, ns_type::ns_t_a, "1.2.3.3"},
1363 {host_name2, ns_type::ns_t_a, "1.2.3.4"},
1364 };
1365
1366 test::DNSResponder dns1(listen_addr1);
1367 test::DNSResponder dns2(listen_addr2);
1368 StartDns(dns1, records1);
1369 StartDns(dns2, records2);
1370
Ken Chenb9fa2062018-11-13 21:51:13 +08001371 std::vector<std::string> servers = { listen_addr1, listen_addr2 };
1372
1373 test::DnsTlsFrontend tls1(listen_addr1, listen_tls, listen_addr1, listen_udp);
1374 test::DnsTlsFrontend tls2(listen_addr2, listen_tls, listen_addr2, listen_udp);
1375 ASSERT_TRUE(tls1.startServer());
1376 ASSERT_TRUE(tls2.startServer());
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001377 ASSERT_TRUE(mDnsClient.SetResolversWithTls(
Xiao Ma09b71022018-12-11 17:56:32 +09001378 servers, kDefaultSearchDomains, kDefaultParams, "",
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001379 {base64Encode(tls1.fingerprint()), base64Encode(tls2.fingerprint())}));
Ken Chenb9fa2062018-11-13 21:51:13 +08001380
1381 const hostent* result;
1382
1383 // Wait for validation to complete.
1384 EXPECT_TRUE(tls1.waitForQueries(1, 5000));
1385 EXPECT_TRUE(tls2.waitForQueries(1, 5000));
1386
1387 result = gethostbyname("tlsfailover1");
1388 ASSERT_FALSE(result == nullptr);
1389 EXPECT_EQ("1.2.3.1", ToString(result));
1390
1391 // Wait for query to get counted.
1392 EXPECT_TRUE(tls1.waitForQueries(2, 5000));
1393 // No new queries should have reached tls2.
1394 EXPECT_EQ(1, tls2.queries());
1395
1396 // Stop tls1. Subsequent queries should attempt to reach tls1, fail, and retry to tls2.
1397 tls1.stopServer();
1398
1399 result = gethostbyname("tlsfailover2");
1400 EXPECT_EQ("1.2.3.4", ToString(result));
1401
1402 // Wait for query to get counted.
1403 EXPECT_TRUE(tls2.waitForQueries(2, 5000));
1404
1405 // No additional queries should have reached the insecure servers.
1406 EXPECT_EQ(2U, dns1.queries().size());
1407 EXPECT_EQ(2U, dns2.queries().size());
1408
1409 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001410 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Ken Chenb9fa2062018-11-13 21:51:13 +08001411}
1412
1413TEST_F(ResolverTest, GetHostByName_BadTlsName) {
Xiao Ma09b71022018-12-11 17:56:32 +09001414 constexpr char listen_addr[] = "127.0.0.3";
1415 constexpr char listen_udp[] = "53";
1416 constexpr char listen_tls[] = "853";
1417 constexpr char host_name[] = "badtlsname.example.com.";
1418
1419 test::DNSResponder dns;
1420 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.1"}});
Ken Chenb9fa2062018-11-13 21:51:13 +08001421 std::vector<std::string> servers = { listen_addr };
1422
1423 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1424 ASSERT_TRUE(tls.startServer());
Xiao Ma09b71022018-12-11 17:56:32 +09001425 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001426 "www.example.com", {}));
Ken Chenb9fa2062018-11-13 21:51:13 +08001427
1428 // The TLS server's certificate doesn't chain to a known CA, and a nonempty name was specified,
1429 // so the client should fail the TLS handshake before ever issuing a query.
1430 EXPECT_FALSE(tls.waitForQueries(1, 500));
1431
1432 // The query should fail hard, because a name was specified.
1433 EXPECT_EQ(nullptr, gethostbyname("badtlsname"));
1434
1435 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001436 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001437}
1438
1439TEST_F(ResolverTest, GetAddrInfo_Tls) {
Xiao Ma09b71022018-12-11 17:56:32 +09001440 constexpr char listen_addr[] = "127.0.0.3";
1441 constexpr char listen_udp[] = "53";
1442 constexpr char listen_tls[] = "853";
1443 constexpr char host_name[] = "addrinfotls.example.com.";
1444 const std::vector<DnsRecord> records = {
1445 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1446 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1447 };
1448
1449 test::DNSResponder dns;
1450 StartDns(dns, records);
Ken Chenb9fa2062018-11-13 21:51:13 +08001451 std::vector<std::string> servers = { listen_addr };
1452
1453 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1454 ASSERT_TRUE(tls.startServer());
Xiao Ma09b71022018-12-11 17:56:32 +09001455 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "",
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001456 {base64Encode(tls.fingerprint())}));
Ken Chenb9fa2062018-11-13 21:51:13 +08001457
1458 // Wait for validation to complete.
1459 EXPECT_TRUE(tls.waitForQueries(1, 5000));
1460
1461 dns.clearQueries();
1462 ScopedAddrinfo result = safe_getaddrinfo("addrinfotls", nullptr, nullptr);
1463 EXPECT_TRUE(result != nullptr);
1464 size_t found = GetNumQueries(dns, host_name);
1465 EXPECT_LE(1U, found);
1466 // Could be A or AAAA
1467 std::string result_str = ToString(result);
1468 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
1469 << ", result_str='" << result_str << "'";
1470 // Wait for both A and AAAA queries to get counted.
1471 EXPECT_TRUE(tls.waitForQueries(3, 5000));
1472
1473 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001474 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001475}
1476
1477TEST_F(ResolverTest, TlsBypass) {
1478 const char OFF[] = "off";
1479 const char OPPORTUNISTIC[] = "opportunistic";
1480 const char STRICT[] = "strict";
1481
1482 const char GETHOSTBYNAME[] = "gethostbyname";
1483 const char GETADDRINFO[] = "getaddrinfo";
1484 const char GETADDRINFOFORNET[] = "getaddrinfofornet";
1485
1486 const unsigned BYPASS_NETID = NETID_USE_LOCAL_NAMESERVERS | TEST_NETID;
1487
Luke Huang579ddc72019-06-14 00:59:39 +08001488 const std::vector<uint8_t> NOOP_FINGERPRINT(android::netdutils::SHA256_SIZE, 0U);
Ken Chenb9fa2062018-11-13 21:51:13 +08001489
1490 const char ADDR4[] = "192.0.2.1";
1491 const char ADDR6[] = "2001:db8::1";
1492
1493 const char cleartext_addr[] = "127.0.0.53";
1494 const char cleartext_port[] = "53";
1495 const char tls_port[] = "853";
1496 const std::vector<std::string> servers = { cleartext_addr };
1497
Xiao Ma09b71022018-12-11 17:56:32 +09001498 test::DNSResponder dns(cleartext_addr);
Ken Chenb9fa2062018-11-13 21:51:13 +08001499 ASSERT_TRUE(dns.startServer());
1500
1501 test::DnsTlsFrontend tls(cleartext_addr, tls_port, cleartext_addr, cleartext_port);
Mike Yudd4ac2d2019-05-31 16:52:11 +08001502 ASSERT_TRUE(tls.startServer());
Ken Chenb9fa2062018-11-13 21:51:13 +08001503
1504 struct TestConfig {
1505 const std::string mode;
1506 const bool withWorkingTLS;
1507 const std::string method;
1508
1509 std::string asHostName() const {
1510 return StringPrintf("%s.%s.%s.",
1511 mode.c_str(),
1512 withWorkingTLS ? "tlsOn" : "tlsOff",
1513 method.c_str());
1514 }
1515 } testConfigs[]{
Ken Chenb9fa2062018-11-13 21:51:13 +08001516 {OFF, true, GETHOSTBYNAME},
1517 {OPPORTUNISTIC, true, GETHOSTBYNAME},
1518 {STRICT, true, GETHOSTBYNAME},
Ken Chenb9fa2062018-11-13 21:51:13 +08001519 {OFF, true, GETADDRINFO},
1520 {OPPORTUNISTIC, true, GETADDRINFO},
1521 {STRICT, true, GETADDRINFO},
Ken Chenb9fa2062018-11-13 21:51:13 +08001522 {OFF, true, GETADDRINFOFORNET},
1523 {OPPORTUNISTIC, true, GETADDRINFOFORNET},
1524 {STRICT, true, GETADDRINFOFORNET},
Mike Yudd4ac2d2019-05-31 16:52:11 +08001525 {OFF, false, GETHOSTBYNAME},
1526 {OPPORTUNISTIC, false, GETHOSTBYNAME},
1527 {STRICT, false, GETHOSTBYNAME},
1528 {OFF, false, GETADDRINFO},
1529 {OPPORTUNISTIC, false, GETADDRINFO},
1530 {STRICT, false, GETADDRINFO},
1531 {OFF, false, GETADDRINFOFORNET},
1532 {OPPORTUNISTIC, false, GETADDRINFOFORNET},
1533 {STRICT, false, GETADDRINFOFORNET},
Ken Chenb9fa2062018-11-13 21:51:13 +08001534 };
1535
1536 for (const auto& config : testConfigs) {
1537 const std::string testHostName = config.asHostName();
1538 SCOPED_TRACE(testHostName);
1539
1540 // Don't tempt test bugs due to caching.
1541 const char* host_name = testHostName.c_str();
1542 dns.addMapping(host_name, ns_type::ns_t_a, ADDR4);
1543 dns.addMapping(host_name, ns_type::ns_t_aaaa, ADDR6);
1544
Mike Yudd4ac2d2019-05-31 16:52:11 +08001545 if (config.withWorkingTLS) {
1546 if (!tls.running()) {
1547 ASSERT_TRUE(tls.startServer());
1548 }
1549 } else {
1550 if (tls.running()) {
1551 ASSERT_TRUE(tls.stopServer());
1552 }
1553 }
Ken Chenb9fa2062018-11-13 21:51:13 +08001554
1555 if (config.mode == OFF) {
Xiao Ma09b71022018-12-11 17:56:32 +09001556 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, kDefaultSearchDomains,
1557 kDefaultParams));
Ken Chenb9fa2062018-11-13 21:51:13 +08001558 } else if (config.mode == OPPORTUNISTIC) {
Xiao Ma09b71022018-12-11 17:56:32 +09001559 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
1560 kDefaultParams, "", {}));
Ken Chenb9fa2062018-11-13 21:51:13 +08001561 // Wait for validation to complete.
1562 if (config.withWorkingTLS) EXPECT_TRUE(tls.waitForQueries(1, 5000));
1563 } else if (config.mode == STRICT) {
1564 // We use the existence of fingerprints to trigger strict mode,
1565 // rather than hostname validation.
1566 const auto& fingerprint =
1567 (config.withWorkingTLS) ? tls.fingerprint() : NOOP_FINGERPRINT;
Xiao Ma09b71022018-12-11 17:56:32 +09001568 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
1569 kDefaultParams, "",
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001570 {base64Encode(fingerprint)}));
Ken Chenb9fa2062018-11-13 21:51:13 +08001571 // Wait for validation to complete.
1572 if (config.withWorkingTLS) EXPECT_TRUE(tls.waitForQueries(1, 5000));
Ken Chenb9fa2062018-11-13 21:51:13 +08001573 }
Mike Yudd4ac2d2019-05-31 16:52:11 +08001574 tls.clearQueries();
Ken Chenb9fa2062018-11-13 21:51:13 +08001575
1576 const hostent* h_result = nullptr;
1577 ScopedAddrinfo ai_result;
1578
1579 if (config.method == GETHOSTBYNAME) {
1580 ASSERT_EQ(0, setNetworkForResolv(BYPASS_NETID));
1581 h_result = gethostbyname(host_name);
1582
1583 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
1584 ASSERT_FALSE(h_result == nullptr);
1585 ASSERT_EQ(4, h_result->h_length);
1586 ASSERT_FALSE(h_result->h_addr_list[0] == nullptr);
1587 EXPECT_EQ(ADDR4, ToString(h_result));
1588 EXPECT_TRUE(h_result->h_addr_list[1] == nullptr);
1589 } else if (config.method == GETADDRINFO) {
1590 ASSERT_EQ(0, setNetworkForResolv(BYPASS_NETID));
1591 ai_result = safe_getaddrinfo(host_name, nullptr, nullptr);
1592 EXPECT_TRUE(ai_result != nullptr);
1593
1594 EXPECT_LE(1U, GetNumQueries(dns, host_name));
1595 // Could be A or AAAA
1596 const std::string result_str = ToString(ai_result);
1597 EXPECT_TRUE(result_str == ADDR4 || result_str == ADDR6)
1598 << ", result_str='" << result_str << "'";
1599 } else if (config.method == GETADDRINFOFORNET) {
1600 addrinfo* raw_ai_result = nullptr;
1601 EXPECT_EQ(0, android_getaddrinfofornet(host_name, /*servname=*/nullptr,
1602 /*hints=*/nullptr, BYPASS_NETID, MARK_UNSET,
1603 &raw_ai_result));
1604 ai_result.reset(raw_ai_result);
1605
1606 EXPECT_LE(1U, GetNumQueries(dns, host_name));
1607 // Could be A or AAAA
1608 const std::string result_str = ToString(ai_result);
1609 EXPECT_TRUE(result_str == ADDR4 || result_str == ADDR6)
1610 << ", result_str='" << result_str << "'";
Ken Chenb9fa2062018-11-13 21:51:13 +08001611 }
1612
Mike Yudd4ac2d2019-05-31 16:52:11 +08001613 EXPECT_EQ(0, tls.queries());
Ken Chenb9fa2062018-11-13 21:51:13 +08001614
1615 // Clear per-process resolv netid.
1616 ASSERT_EQ(0, setNetworkForResolv(NETID_UNSET));
Ken Chenb9fa2062018-11-13 21:51:13 +08001617 dns.clearQueries();
1618 }
Ken Chenb9fa2062018-11-13 21:51:13 +08001619}
1620
1621TEST_F(ResolverTest, StrictMode_NoTlsServers) {
Luke Huang579ddc72019-06-14 00:59:39 +08001622 const std::vector<uint8_t> NOOP_FINGERPRINT(android::netdutils::SHA256_SIZE, 0U);
Xiao Ma09b71022018-12-11 17:56:32 +09001623 constexpr char cleartext_addr[] = "127.0.0.53";
Ken Chenb9fa2062018-11-13 21:51:13 +08001624 const std::vector<std::string> servers = { cleartext_addr };
Xiao Ma09b71022018-12-11 17:56:32 +09001625 constexpr char host_name[] = "strictmode.notlsips.example.com.";
1626 const std::vector<DnsRecord> records = {
1627 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1628 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1629 };
Ken Chenb9fa2062018-11-13 21:51:13 +08001630
Xiao Ma09b71022018-12-11 17:56:32 +09001631 test::DNSResponder dns(cleartext_addr);
1632 StartDns(dns, records);
Ken Chenb9fa2062018-11-13 21:51:13 +08001633
Xiao Ma09b71022018-12-11 17:56:32 +09001634 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, {},
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001635 "", {base64Encode(NOOP_FINGERPRINT)}));
Ken Chenb9fa2062018-11-13 21:51:13 +08001636
1637 addrinfo* ai_result = nullptr;
1638 EXPECT_NE(0, getaddrinfo(host_name, nullptr, nullptr, &ai_result));
1639 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
1640}
Luke Huang94b10b92018-11-21 20:13:38 +08001641
1642namespace {
1643
Luke Huang70931aa2019-01-31 11:57:41 +08001644int getAsyncResponse(int fd, int* rcode, uint8_t* buf, int bufLen) {
Luke Huang94b10b92018-11-21 20:13:38 +08001645 struct pollfd wait_fd[1];
1646 wait_fd[0].fd = fd;
1647 wait_fd[0].events = POLLIN;
1648 short revents;
1649 int ret;
1650
1651 ret = poll(wait_fd, 1, -1);
1652 revents = wait_fd[0].revents;
1653 if (revents & POLLIN) {
1654 int n = resNetworkResult(fd, rcode, buf, bufLen);
Luke Huangba7bef92018-12-26 16:53:03 +08001655 // Verify that resNetworkResult() closed the fd
1656 char dummy;
1657 EXPECT_EQ(-1, read(fd, &dummy, sizeof dummy));
1658 EXPECT_EQ(EBADF, errno);
Luke Huang94b10b92018-11-21 20:13:38 +08001659 return n;
1660 }
1661 return -1;
1662}
1663
Luke Huang70931aa2019-01-31 11:57:41 +08001664std::string toString(uint8_t* buf, int bufLen, int ipType) {
Luke Huang94b10b92018-11-21 20:13:38 +08001665 ns_msg handle;
1666 int ancount, n = 0;
1667 ns_rr rr;
1668
1669 if (ns_initparse((const uint8_t*) buf, bufLen, &handle) >= 0) {
1670 ancount = ns_msg_count(handle, ns_s_an);
1671 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
Luke Huang70931aa2019-01-31 11:57:41 +08001672 const uint8_t* rdata = ns_rr_rdata(rr);
Luke Huang94b10b92018-11-21 20:13:38 +08001673 char buffer[INET6_ADDRSTRLEN];
1674 if (inet_ntop(ipType, (const char*) rdata, buffer, sizeof(buffer))) {
1675 return buffer;
1676 }
1677 }
1678 }
1679 return "";
1680}
1681
1682int dns_open_proxy() {
1683 int s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
1684 if (s == -1) {
1685 return -1;
1686 }
1687 const int one = 1;
1688 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
1689
1690 static const struct sockaddr_un proxy_addr = {
1691 .sun_family = AF_UNIX,
1692 .sun_path = "/dev/socket/dnsproxyd",
1693 };
1694
1695 if (TEMP_FAILURE_RETRY(connect(s, (const struct sockaddr*) &proxy_addr, sizeof(proxy_addr))) !=
1696 0) {
1697 close(s);
1698 return -1;
1699 }
1700
1701 return s;
1702}
1703
Luke Huangba7bef92018-12-26 16:53:03 +08001704void expectAnswersValid(int fd, int ipType, const std::string& expectedAnswer) {
1705 int rcode = -1;
1706 uint8_t buf[MAXPACKET] = {};
1707
1708 int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
1709 EXPECT_GT(res, 0);
1710 EXPECT_EQ(expectedAnswer, toString(buf, res, ipType));
1711}
1712
1713void expectAnswersNotValid(int fd, int expectedErrno) {
1714 int rcode = -1;
1715 uint8_t buf[MAXPACKET] = {};
1716
1717 int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
1718 EXPECT_EQ(expectedErrno, res);
1719}
1720
Luke Huang94b10b92018-11-21 20:13:38 +08001721} // namespace
1722
1723TEST_F(ResolverTest, Async_NormalQueryV4V6) {
Xiao Ma09b71022018-12-11 17:56:32 +09001724 constexpr char listen_addr[] = "127.0.0.4";
1725 constexpr char host_name[] = "howdy.example.com.";
1726 const std::vector<DnsRecord> records = {
1727 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1728 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1729 };
1730
1731 test::DNSResponder dns(listen_addr);
1732 StartDns(dns, records);
Luke Huang94b10b92018-11-21 20:13:38 +08001733 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09001734 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huang94b10b92018-11-21 20:13:38 +08001735
Luke Huangba7bef92018-12-26 16:53:03 +08001736 int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1737 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001738 EXPECT_TRUE(fd1 != -1);
1739 EXPECT_TRUE(fd2 != -1);
1740
Luke Huang70931aa2019-01-31 11:57:41 +08001741 uint8_t buf[MAXPACKET] = {};
Luke Huang94b10b92018-11-21 20:13:38 +08001742 int rcode;
1743 int res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
1744 EXPECT_GT(res, 0);
1745 EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
1746
1747 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
1748 EXPECT_GT(res, 0);
1749 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
1750
1751 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
1752
1753 // Re-query verify cache works
Luke Huangba7bef92018-12-26 16:53:03 +08001754 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1755 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001756
1757 EXPECT_TRUE(fd1 != -1);
1758 EXPECT_TRUE(fd2 != -1);
1759
1760 res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
1761 EXPECT_GT(res, 0);
1762 EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
1763
1764 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
1765 EXPECT_GT(res, 0);
1766 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
1767
1768 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
1769}
1770
1771TEST_F(ResolverTest, Async_BadQuery) {
Xiao Ma09b71022018-12-11 17:56:32 +09001772 constexpr char listen_addr[] = "127.0.0.4";
1773 constexpr char host_name[] = "howdy.example.com.";
1774 const std::vector<DnsRecord> records = {
1775 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1776 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1777 };
1778
1779 test::DNSResponder dns(listen_addr);
1780 StartDns(dns, records);
Luke Huang94b10b92018-11-21 20:13:38 +08001781 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09001782 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huang94b10b92018-11-21 20:13:38 +08001783
1784 static struct {
1785 int fd;
1786 const char* dname;
1787 const int queryType;
1788 const int expectRcode;
1789 } kTestData[] = {
Luke Huangba7bef92018-12-26 16:53:03 +08001790 {-1, "", ns_t_aaaa, 0},
1791 {-1, "as65ass46", ns_t_aaaa, 0},
1792 {-1, "454564564564", ns_t_aaaa, 0},
1793 {-1, "h645235", ns_t_a, 0},
1794 {-1, "www.google.com", ns_t_a, 0},
Luke Huang94b10b92018-11-21 20:13:38 +08001795 };
1796
1797 for (auto& td : kTestData) {
1798 SCOPED_TRACE(td.dname);
Luke Huangba7bef92018-12-26 16:53:03 +08001799 td.fd = resNetworkQuery(TEST_NETID, td.dname, ns_c_in, td.queryType, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001800 EXPECT_TRUE(td.fd != -1);
1801 }
1802
1803 // dns_responder return empty resp(packet only contains query part) with no error currently
1804 for (const auto& td : kTestData) {
Luke Huang70931aa2019-01-31 11:57:41 +08001805 uint8_t buf[MAXPACKET] = {};
Luke Huang94b10b92018-11-21 20:13:38 +08001806 int rcode;
1807 SCOPED_TRACE(td.dname);
1808 int res = getAsyncResponse(td.fd, &rcode, buf, MAXPACKET);
1809 EXPECT_GT(res, 0);
1810 EXPECT_EQ(rcode, td.expectRcode);
1811 }
1812}
1813
1814TEST_F(ResolverTest, Async_EmptyAnswer) {
Xiao Ma09b71022018-12-11 17:56:32 +09001815 constexpr char listen_addr[] = "127.0.0.4";
1816 constexpr char host_name[] = "howdy.example.com.";
1817 const std::vector<DnsRecord> records = {
1818 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1819 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1820 };
1821
1822 test::DNSResponder dns(listen_addr);
1823 StartDns(dns, records);
Luke Huang94b10b92018-11-21 20:13:38 +08001824 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09001825 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huang94b10b92018-11-21 20:13:38 +08001826
Luke Huang9c264bb2018-12-18 16:44:41 +08001827 // TODO: Disable retry to make this test explicit.
1828 auto& cv = dns.getCv();
1829 auto& cvMutex = dns.getCvMutex();
1830 int fd1;
1831 // Wait on the condition variable to ensure that the DNS server has handled our first query.
1832 {
1833 std::unique_lock lk(cvMutex);
Luke Huangba7bef92018-12-26 16:53:03 +08001834 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
Luke Huang9c264bb2018-12-18 16:44:41 +08001835 EXPECT_TRUE(fd1 != -1);
1836 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lk, std::chrono::seconds(1)));
1837 }
Luke Huang94b10b92018-11-21 20:13:38 +08001838
Luke Huang94b10b92018-11-21 20:13:38 +08001839 dns.setResponseProbability(0.0);
Luke Huang94b10b92018-11-21 20:13:38 +08001840
Luke Huangba7bef92018-12-26 16:53:03 +08001841 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001842 EXPECT_TRUE(fd2 != -1);
1843
Luke Huangba7bef92018-12-26 16:53:03 +08001844 int fd3 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001845 EXPECT_TRUE(fd3 != -1);
1846
Luke Huang9c264bb2018-12-18 16:44:41 +08001847 uint8_t buf[MAXPACKET] = {};
Luke Huang94b10b92018-11-21 20:13:38 +08001848 int rcode;
1849
Luke Huang9c264bb2018-12-18 16:44:41 +08001850 // expect no response
1851 int res = getAsyncResponse(fd3, &rcode, buf, MAXPACKET);
1852 EXPECT_EQ(-ETIMEDOUT, res);
Luke Huang94b10b92018-11-21 20:13:38 +08001853
Luke Huang9c264bb2018-12-18 16:44:41 +08001854 // expect no response
Luke Huang94b10b92018-11-21 20:13:38 +08001855 memset(buf, 0, MAXPACKET);
Luke Huang9c264bb2018-12-18 16:44:41 +08001856 res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
1857 EXPECT_EQ(-ETIMEDOUT, res);
Luke Huang94b10b92018-11-21 20:13:38 +08001858
Luke Huang94b10b92018-11-21 20:13:38 +08001859 dns.setResponseProbability(1.0);
Luke Huang94b10b92018-11-21 20:13:38 +08001860
Luke Huangba7bef92018-12-26 16:53:03 +08001861 int fd4 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001862 EXPECT_TRUE(fd4 != -1);
1863
1864 memset(buf, 0, MAXPACKET);
1865 res = getAsyncResponse(fd4, &rcode, buf, MAXPACKET);
1866 EXPECT_GT(res, 0);
1867 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
1868
1869 memset(buf, 0, MAXPACKET);
1870 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
1871 EXPECT_GT(res, 0);
1872 EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
1873}
1874
1875TEST_F(ResolverTest, Async_MalformedQuery) {
Xiao Ma09b71022018-12-11 17:56:32 +09001876 constexpr char listen_addr[] = "127.0.0.4";
1877 constexpr char host_name[] = "howdy.example.com.";
1878 const std::vector<DnsRecord> records = {
1879 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1880 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1881 };
1882
1883 test::DNSResponder dns(listen_addr);
1884 StartDns(dns, records);
Luke Huang94b10b92018-11-21 20:13:38 +08001885 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09001886 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huang94b10b92018-11-21 20:13:38 +08001887
1888 int fd = dns_open_proxy();
1889 EXPECT_TRUE(fd > 0);
1890
1891 const std::string badMsg = "16-52512#";
Xiao Ma09b71022018-12-11 17:56:32 +09001892 static const struct {
Luke Huang94b10b92018-11-21 20:13:38 +08001893 const std::string cmd;
1894 const int expectErr;
1895 } kTestData[] = {
Luke Huangba7bef92018-12-26 16:53:03 +08001896 // Too few arguments
Luke Huang94b10b92018-11-21 20:13:38 +08001897 {"resnsend " + badMsg + '\0', -EINVAL},
1898 // Bad netId
Luke Huangba7bef92018-12-26 16:53:03 +08001899 {"resnsend badnetId 0 " + badMsg + '\0', -EINVAL},
Luke Huang94b10b92018-11-21 20:13:38 +08001900 // Bad raw data
Luke Huangba7bef92018-12-26 16:53:03 +08001901 {"resnsend " + std::to_string(TEST_NETID) + " 0 " + badMsg + '\0', -EILSEQ},
Luke Huang94b10b92018-11-21 20:13:38 +08001902 };
1903
1904 for (unsigned int i = 0; i < std::size(kTestData); i++) {
1905 auto& td = kTestData[i];
1906 SCOPED_TRACE(td.cmd);
1907 ssize_t rc = TEMP_FAILURE_RETRY(write(fd, td.cmd.c_str(), td.cmd.size()));
1908 EXPECT_EQ(rc, static_cast<ssize_t>(td.cmd.size()));
1909
1910 int32_t tmp;
1911 rc = TEMP_FAILURE_RETRY(read(fd, &tmp, sizeof(tmp)));
1912 EXPECT_TRUE(rc > 0);
1913 EXPECT_EQ(static_cast<int>(ntohl(tmp)), td.expectErr);
1914 }
1915 // Normal query with answer buffer
1916 // This is raw data of query "howdy.example.com" type 1 class 1
1917 std::string query = "81sBAAABAAAAAAAABWhvd2R5B2V4YW1wbGUDY29tAAABAAE=";
Luke Huangba7bef92018-12-26 16:53:03 +08001918 std::string cmd = "resnsend " + std::to_string(TEST_NETID) + " 0 " + query + '\0';
Luke Huang94b10b92018-11-21 20:13:38 +08001919 ssize_t rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
1920 EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
1921
Luke Huang70931aa2019-01-31 11:57:41 +08001922 uint8_t smallBuf[1] = {};
Luke Huang94b10b92018-11-21 20:13:38 +08001923 int rcode;
1924 rc = getAsyncResponse(fd, &rcode, smallBuf, 1);
Luke Huangba7bef92018-12-26 16:53:03 +08001925 EXPECT_EQ(-EMSGSIZE, rc);
Luke Huang94b10b92018-11-21 20:13:38 +08001926
1927 // Do the normal test with large buffer again
1928 fd = dns_open_proxy();
1929 EXPECT_TRUE(fd > 0);
1930 rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
1931 EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
Luke Huang70931aa2019-01-31 11:57:41 +08001932 uint8_t buf[MAXPACKET] = {};
Luke Huang94b10b92018-11-21 20:13:38 +08001933 rc = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
1934 EXPECT_EQ("1.2.3.4", toString(buf, rc, AF_INET));
Mike Yu4f3747b2018-12-02 17:54:29 +09001935}
1936
Luke Huangba7bef92018-12-26 16:53:03 +08001937TEST_F(ResolverTest, Async_CacheFlags) {
Xiao Ma09b71022018-12-11 17:56:32 +09001938 constexpr char listen_addr[] = "127.0.0.4";
1939 constexpr char host_name[] = "howdy.example.com.";
Luke Huang40f5f492019-05-09 19:37:35 +08001940 constexpr char another_host_name[] = "howdy.example2.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09001941 const std::vector<DnsRecord> records = {
1942 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1943 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
Luke Huang40f5f492019-05-09 19:37:35 +08001944 {another_host_name, ns_type::ns_t_a, "1.2.3.5"},
1945 {another_host_name, ns_type::ns_t_aaaa, "::1.2.3.5"},
Xiao Ma09b71022018-12-11 17:56:32 +09001946 };
1947
1948 test::DNSResponder dns(listen_addr);
1949 StartDns(dns, records);
Luke Huangba7bef92018-12-26 16:53:03 +08001950 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09001951 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huangba7bef92018-12-26 16:53:03 +08001952
1953 // ANDROID_RESOLV_NO_CACHE_STORE
1954 int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1955 ANDROID_RESOLV_NO_CACHE_STORE);
1956 EXPECT_TRUE(fd1 != -1);
1957 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1958 ANDROID_RESOLV_NO_CACHE_STORE);
1959 EXPECT_TRUE(fd2 != -1);
1960 int fd3 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1961 ANDROID_RESOLV_NO_CACHE_STORE);
1962 EXPECT_TRUE(fd3 != -1);
1963
1964 expectAnswersValid(fd3, AF_INET, "1.2.3.4");
1965 expectAnswersValid(fd2, AF_INET, "1.2.3.4");
1966 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
1967
1968 // No cache exists, expect 3 queries
1969 EXPECT_EQ(3U, GetNumQueries(dns, host_name));
1970
1971 // Re-query and cache
1972 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1973
1974 EXPECT_TRUE(fd1 != -1);
1975
1976 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
1977
1978 // Now we have cache, expect 4 queries
1979 EXPECT_EQ(4U, GetNumQueries(dns, host_name));
1980
1981 // ANDROID_RESOLV_NO_CACHE_LOOKUP
1982 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1983 ANDROID_RESOLV_NO_CACHE_LOOKUP);
1984 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1985 ANDROID_RESOLV_NO_CACHE_LOOKUP);
1986
1987 EXPECT_TRUE(fd1 != -1);
1988 EXPECT_TRUE(fd2 != -1);
1989
1990 expectAnswersValid(fd2, AF_INET, "1.2.3.4");
1991 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
1992
1993 // Skip cache, expect 6 queries
1994 EXPECT_EQ(6U, GetNumQueries(dns, host_name));
1995
1996 // Re-query verify cache works
1997 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1998 ANDROID_RESOLV_NO_CACHE_STORE);
1999 EXPECT_TRUE(fd1 != -1);
2000 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
2001
2002 // Cache hits, expect still 6 queries
2003 EXPECT_EQ(6U, GetNumQueries(dns, host_name));
Luke Huanga1d74182019-03-19 17:30:36 +08002004
2005 // Start to verify if ANDROID_RESOLV_NO_CACHE_LOOKUP does write response into cache
2006 dns.clearQueries();
2007
2008 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa,
2009 ANDROID_RESOLV_NO_CACHE_LOOKUP);
2010 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa,
2011 ANDROID_RESOLV_NO_CACHE_LOOKUP);
2012
2013 EXPECT_TRUE(fd1 != -1);
2014 EXPECT_TRUE(fd2 != -1);
2015
2016 expectAnswersValid(fd2, AF_INET6, "::1.2.3.4");
2017 expectAnswersValid(fd1, AF_INET6, "::1.2.3.4");
2018
2019 // Skip cache, expect 2 queries
2020 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
2021
2022 // Re-query without flags
2023 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2024 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2025
2026 EXPECT_TRUE(fd1 != -1);
2027 EXPECT_TRUE(fd2 != -1);
2028
2029 expectAnswersValid(fd2, AF_INET6, "::1.2.3.4");
2030 expectAnswersValid(fd1, AF_INET6, "::1.2.3.4");
2031
2032 // Cache hits, expect still 2 queries
2033 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
Luke Huang40f5f492019-05-09 19:37:35 +08002034
2035 // Test both ANDROID_RESOLV_NO_CACHE_STORE and ANDROID_RESOLV_NO_CACHE_LOOKUP are set
2036 dns.clearQueries();
2037
2038 // Make sure that the cache of "howdy.example2.com" exists.
2039 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa, 0);
2040 EXPECT_TRUE(fd1 != -1);
2041 expectAnswersValid(fd1, AF_INET6, "::1.2.3.5");
2042 EXPECT_EQ(1U, GetNumQueries(dns, another_host_name));
2043
2044 // Re-query with testFlags
2045 const int testFlag = ANDROID_RESOLV_NO_CACHE_STORE | ANDROID_RESOLV_NO_CACHE_LOOKUP;
2046 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa, testFlag);
2047 EXPECT_TRUE(fd1 != -1);
2048 expectAnswersValid(fd1, AF_INET6, "::1.2.3.5");
2049 // Expect cache lookup is skipped.
2050 EXPECT_EQ(2U, GetNumQueries(dns, another_host_name));
2051
2052 // Do another query with testFlags
2053 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_a, testFlag);
2054 EXPECT_TRUE(fd1 != -1);
2055 expectAnswersValid(fd1, AF_INET, "1.2.3.5");
2056 // Expect cache lookup is skipped.
2057 EXPECT_EQ(3U, GetNumQueries(dns, another_host_name));
2058
2059 // Re-query with no flags
2060 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_a, 0);
2061 EXPECT_TRUE(fd1 != -1);
2062 expectAnswersValid(fd1, AF_INET, "1.2.3.5");
2063 // Expect no cache hit because cache storing is also skipped in previous query.
2064 EXPECT_EQ(4U, GetNumQueries(dns, another_host_name));
Luke Huangba7bef92018-12-26 16:53:03 +08002065}
2066
2067TEST_F(ResolverTest, Async_NoRetryFlag) {
Luke Huang70931aa2019-01-31 11:57:41 +08002068 constexpr char listen_addr0[] = "127.0.0.4";
2069 constexpr char listen_addr1[] = "127.0.0.6";
Xiao Ma09b71022018-12-11 17:56:32 +09002070 constexpr char host_name[] = "howdy.example.com.";
2071 const std::vector<DnsRecord> records = {
2072 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2073 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2074 };
2075
Luke Huang70931aa2019-01-31 11:57:41 +08002076 test::DNSResponder dns0(listen_addr0);
2077 test::DNSResponder dns1(listen_addr1);
2078 StartDns(dns0, records);
2079 StartDns(dns1, records);
2080 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr0, listen_addr1}));
Luke Huangba7bef92018-12-26 16:53:03 +08002081
Luke Huang70931aa2019-01-31 11:57:41 +08002082 dns0.clearQueries();
2083 dns1.clearQueries();
2084
2085 dns0.setResponseProbability(0.0);
2086 dns1.setResponseProbability(0.0);
Luke Huangba7bef92018-12-26 16:53:03 +08002087
2088 int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2089 ANDROID_RESOLV_NO_RETRY);
2090 EXPECT_TRUE(fd1 != -1);
2091
2092 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa,
2093 ANDROID_RESOLV_NO_RETRY);
2094 EXPECT_TRUE(fd2 != -1);
2095
2096 // expect no response
2097 expectAnswersNotValid(fd1, -ETIMEDOUT);
2098 expectAnswersNotValid(fd2, -ETIMEDOUT);
2099
Luke Huang70931aa2019-01-31 11:57:41 +08002100 // No retry case, expect total 2 queries. The server is selected randomly.
2101 EXPECT_EQ(2U, GetNumQueries(dns0, host_name) + GetNumQueries(dns1, host_name));
Luke Huangba7bef92018-12-26 16:53:03 +08002102
Luke Huang70931aa2019-01-31 11:57:41 +08002103 dns0.clearQueries();
2104 dns1.clearQueries();
Luke Huangba7bef92018-12-26 16:53:03 +08002105
2106 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2107 EXPECT_TRUE(fd1 != -1);
2108
2109 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2110 EXPECT_TRUE(fd2 != -1);
2111
2112 // expect no response
2113 expectAnswersNotValid(fd1, -ETIMEDOUT);
2114 expectAnswersNotValid(fd2, -ETIMEDOUT);
2115
2116 // Retry case, expect 4 queries
Luke Huang70931aa2019-01-31 11:57:41 +08002117 EXPECT_EQ(4U, GetNumQueries(dns0, host_name));
2118 EXPECT_EQ(4U, GetNumQueries(dns1, host_name));
2119}
2120
2121TEST_F(ResolverTest, Async_VerifyQueryID) {
2122 constexpr char listen_addr[] = "127.0.0.4";
2123 constexpr char host_name[] = "howdy.example.com.";
2124 const std::vector<DnsRecord> records = {
2125 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2126 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2127 };
2128
2129 test::DNSResponder dns(listen_addr);
2130 StartDns(dns, records);
2131 std::vector<std::string> servers = {listen_addr};
2132 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2133
2134 const uint8_t queryBuf1[] = {
2135 /* Header */
2136 0x55, 0x66, /* Transaction ID */
2137 0x01, 0x00, /* Flags */
2138 0x00, 0x01, /* Questions */
2139 0x00, 0x00, /* Answer RRs */
2140 0x00, 0x00, /* Authority RRs */
2141 0x00, 0x00, /* Additional RRs */
2142 /* Queries */
2143 0x05, 0x68, 0x6f, 0x77, 0x64, 0x79, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
2144 0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */
2145 0x00, 0x01, /* Type */
2146 0x00, 0x01 /* Class */
2147 };
2148
2149 int fd = resNetworkSend(TEST_NETID, queryBuf1, sizeof(queryBuf1), 0);
2150 EXPECT_TRUE(fd != -1);
2151
2152 uint8_t buf[MAXPACKET] = {};
2153 int rcode;
2154
2155 int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2156 EXPECT_GT(res, 0);
2157 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2158
2159 auto hp = reinterpret_cast<HEADER*>(buf);
2160 EXPECT_EQ(21862U, htons(hp->id));
2161
2162 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2163
2164 const uint8_t queryBuf2[] = {
2165 /* Header */
2166 0x00, 0x53, /* Transaction ID */
2167 0x01, 0x00, /* Flags */
2168 0x00, 0x01, /* Questions */
2169 0x00, 0x00, /* Answer RRs */
2170 0x00, 0x00, /* Authority RRs */
2171 0x00, 0x00, /* Additional RRs */
2172 /* Queries */
2173 0x05, 0x68, 0x6f, 0x77, 0x64, 0x79, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
2174 0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */
2175 0x00, 0x01, /* Type */
2176 0x00, 0x01 /* Class */
2177 };
2178
2179 // Re-query verify cache works and query id is correct
2180 fd = resNetworkSend(TEST_NETID, queryBuf2, sizeof(queryBuf2), 0);
2181
2182 EXPECT_TRUE(fd != -1);
2183
2184 res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2185 EXPECT_GT(res, 0);
2186 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2187
2188 EXPECT_EQ(0x0053U, htons(hp->id));
2189
2190 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
Luke Huangba7bef92018-12-26 16:53:03 +08002191}
2192
Mike Yu4f3747b2018-12-02 17:54:29 +09002193// This test checks that the resolver should not generate the request containing OPT RR when using
Ken Chen0a015532019-01-02 14:59:38 +08002194// cleartext DNS. If we query the DNS server not supporting EDNS0 and it reponds with
2195// FORMERR_ON_EDNS, we will fallback to no EDNS0 and try again. If the server does no response, we
2196// won't retry so that we get no answer.
Mike Yu4f3747b2018-12-02 17:54:29 +09002197TEST_F(ResolverTest, BrokenEdns) {
2198 typedef test::DNSResponder::Edns Edns;
2199 enum ExpectResult { EXPECT_FAILURE, EXPECT_SUCCESS };
2200
2201 const char OFF[] = "off";
2202 const char OPPORTUNISTIC_UDP[] = "opportunistic_udp";
2203 const char OPPORTUNISTIC_TLS[] = "opportunistic_tls";
2204 const char STRICT[] = "strict";
2205 const char GETHOSTBYNAME[] = "gethostbyname";
2206 const char GETADDRINFO[] = "getaddrinfo";
Luke Huang579ddc72019-06-14 00:59:39 +08002207 const std::vector<uint8_t> NOOP_FINGERPRINT(android::netdutils::SHA256_SIZE, 0U);
Mike Yu4f3747b2018-12-02 17:54:29 +09002208 const char ADDR4[] = "192.0.2.1";
2209 const char CLEARTEXT_ADDR[] = "127.0.0.53";
2210 const char CLEARTEXT_PORT[] = "53";
2211 const char TLS_PORT[] = "853";
2212 const std::vector<std::string> servers = { CLEARTEXT_ADDR };
2213
Mike Yufc125e42019-05-15 20:41:28 +08002214 test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, ns_rcode::ns_r_servfail);
Mike Yu4f3747b2018-12-02 17:54:29 +09002215 ASSERT_TRUE(dns.startServer());
2216
2217 test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2218
2219 static const struct TestConfig {
2220 std::string mode;
2221 std::string method;
2222 Edns edns;
2223 ExpectResult expectResult;
2224
2225 std::string asHostName() const {
2226 const char* ednsString;
2227 switch (edns) {
2228 case Edns::ON:
2229 ednsString = "ednsOn";
2230 break;
Ken Chen0a015532019-01-02 14:59:38 +08002231 case Edns::FORMERR_ON_EDNS:
Mike Yu4f3747b2018-12-02 17:54:29 +09002232 ednsString = "ednsFormerr";
2233 break;
2234 case Edns::DROP:
2235 ednsString = "ednsDrop";
2236 break;
2237 default:
2238 ednsString = "";
2239 break;
2240 }
2241 return StringPrintf("%s.%s.%s.", mode.c_str(), method.c_str(), ednsString);
2242 }
2243 } testConfigs[] = {
2244 // In OPPORTUNISTIC_TLS, we get no answer if the DNS server supports TLS but not EDNS0.
2245 // Could such server exist? if so, we might need to fallback to query cleartext DNS.
2246 // Another thing is that {OPPORTUNISTIC_TLS, Edns::DROP} and {STRICT, Edns::DROP} are
2247 // commented out since TLS timeout is not configurable.
2248 // TODO: Uncomment them after TLS timeout is configurable.
2249 {OFF, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
2250 {OPPORTUNISTIC_UDP, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
2251 {OPPORTUNISTIC_TLS, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
2252 {STRICT, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
Ken Chen0a015532019-01-02 14:59:38 +08002253 {OFF, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2254 {OPPORTUNISTIC_UDP, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2255 {OPPORTUNISTIC_TLS, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
2256 {STRICT, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
Mike Yu4f3747b2018-12-02 17:54:29 +09002257 {OFF, GETHOSTBYNAME, Edns::DROP, EXPECT_SUCCESS},
2258 {OPPORTUNISTIC_UDP, GETHOSTBYNAME, Edns::DROP, EXPECT_SUCCESS},
2259 //{OPPORTUNISTIC_TLS, GETHOSTBYNAME, Edns::DROP, EXPECT_FAILURE},
2260 //{STRICT, GETHOSTBYNAME, Edns::DROP, EXPECT_FAILURE},
2261 {OFF, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
2262 {OPPORTUNISTIC_UDP, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
2263 {OPPORTUNISTIC_TLS, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
2264 {STRICT, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
Ken Chen0a015532019-01-02 14:59:38 +08002265 {OFF, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2266 {OPPORTUNISTIC_UDP, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2267 {OPPORTUNISTIC_TLS, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
2268 {STRICT, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
Mike Yu4f3747b2018-12-02 17:54:29 +09002269 {OFF, GETADDRINFO, Edns::DROP, EXPECT_SUCCESS},
2270 {OPPORTUNISTIC_UDP, GETADDRINFO, Edns::DROP, EXPECT_SUCCESS},
2271 //{OPPORTUNISTIC_TLS, GETADDRINFO, Edns::DROP, EXPECT_FAILURE},
2272 //{STRICT, GETADDRINFO, Edns::DROP, EXPECT_FAILURE},
2273 };
2274
2275 for (const auto& config : testConfigs) {
2276 const std::string testHostName = config.asHostName();
2277 SCOPED_TRACE(testHostName);
2278
2279 const char* host_name = testHostName.c_str();
2280 dns.addMapping(host_name, ns_type::ns_t_a, ADDR4);
2281 dns.setEdns(config.edns);
2282
2283 if (config.mode == OFF) {
Mike Yu0f20cdd2019-06-11 11:52:37 +08002284 if (tls.running()) {
2285 ASSERT_TRUE(tls.stopServer());
2286 }
Xiao Ma09b71022018-12-11 17:56:32 +09002287 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Mike Yu4f3747b2018-12-02 17:54:29 +09002288 } else if (config.mode == OPPORTUNISTIC_UDP) {
Mike Yu0f20cdd2019-06-11 11:52:37 +08002289 if (tls.running()) {
2290 ASSERT_TRUE(tls.stopServer());
2291 }
Xiao Ma09b71022018-12-11 17:56:32 +09002292 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
2293 kDefaultParams, "", {}));
Mike Yu4f3747b2018-12-02 17:54:29 +09002294 } else if (config.mode == OPPORTUNISTIC_TLS) {
Mike Yu0f20cdd2019-06-11 11:52:37 +08002295 if (!tls.running()) {
2296 ASSERT_TRUE(tls.startServer());
2297 }
Xiao Ma09b71022018-12-11 17:56:32 +09002298 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
2299 kDefaultParams, "", {}));
Mike Yu4f3747b2018-12-02 17:54:29 +09002300 // Wait for validation to complete.
2301 EXPECT_TRUE(tls.waitForQueries(1, 5000));
2302 } else if (config.mode == STRICT) {
Mike Yu0f20cdd2019-06-11 11:52:37 +08002303 if (!tls.running()) {
2304 ASSERT_TRUE(tls.startServer());
2305 }
Xiao Ma09b71022018-12-11 17:56:32 +09002306 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
2307 kDefaultParams, "",
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09002308 {base64Encode(tls.fingerprint())}));
Mike Yu4f3747b2018-12-02 17:54:29 +09002309 // Wait for validation to complete.
2310 EXPECT_TRUE(tls.waitForQueries(1, 5000));
2311 }
2312
2313 if (config.method == GETHOSTBYNAME) {
2314 const hostent* h_result = gethostbyname(host_name);
2315 if (config.expectResult == EXPECT_SUCCESS) {
2316 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2317 ASSERT_TRUE(h_result != nullptr);
2318 ASSERT_EQ(4, h_result->h_length);
2319 ASSERT_FALSE(h_result->h_addr_list[0] == nullptr);
2320 EXPECT_EQ(ADDR4, ToString(h_result));
2321 EXPECT_TRUE(h_result->h_addr_list[1] == nullptr);
2322 } else {
2323 EXPECT_EQ(0U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
2324 ASSERT_TRUE(h_result == nullptr);
2325 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2326 }
2327 } else if (config.method == GETADDRINFO) {
2328 ScopedAddrinfo ai_result;
2329 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2330 ai_result = safe_getaddrinfo(host_name, nullptr, &hints);
2331 if (config.expectResult == EXPECT_SUCCESS) {
2332 EXPECT_TRUE(ai_result != nullptr);
2333 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2334 const std::string result_str = ToString(ai_result);
2335 EXPECT_EQ(ADDR4, result_str);
2336 } else {
2337 EXPECT_TRUE(ai_result == nullptr);
2338 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
2339 }
2340 } else {
2341 FAIL() << "Unsupported query method: " << config.method;
2342 }
2343
Mike Yudd4ac2d2019-05-31 16:52:11 +08002344 tls.clearQueries();
Mike Yu4f3747b2018-12-02 17:54:29 +09002345 dns.clearQueries();
2346 }
Mike Yu4f3747b2018-12-02 17:54:29 +09002347}
nuccachena26cc2a2018-07-17 18:07:23 +08002348
Ken Chen0a015532019-01-02 14:59:38 +08002349// DNS-over-TLS validation success, but server does not respond to TLS query after a while.
2350// Resolver should have a reasonable number of retries instead of spinning forever. We don't have
2351// an efficient way to know if resolver is stuck in an infinite loop. However, test case will be
2352// failed due to timeout.
2353TEST_F(ResolverTest, UnstableTls) {
2354 const char CLEARTEXT_ADDR[] = "127.0.0.53";
2355 const char CLEARTEXT_PORT[] = "53";
2356 const char TLS_PORT[] = "853";
2357 const char* host_name1 = "nonexistent1.example.com.";
2358 const char* host_name2 = "nonexistent2.example.com.";
2359 const std::vector<std::string> servers = {CLEARTEXT_ADDR};
2360
Mike Yufc125e42019-05-15 20:41:28 +08002361 test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, ns_rcode::ns_r_servfail);
Ken Chen0a015532019-01-02 14:59:38 +08002362 ASSERT_TRUE(dns.startServer());
2363 dns.setEdns(test::DNSResponder::Edns::FORMERR_ON_EDNS);
2364 test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2365 ASSERT_TRUE(tls.startServer());
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09002366 ASSERT_TRUE(
Xiao Ma09b71022018-12-11 17:56:32 +09002367 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
Ken Chen0a015532019-01-02 14:59:38 +08002368 // Wait for validation complete.
2369 EXPECT_TRUE(tls.waitForQueries(1, 5000));
2370 // Shutdown TLS server to get an error. It's similar to no response case but without waiting.
2371 tls.stopServer();
2372
2373 const hostent* h_result = gethostbyname(host_name1);
2374 EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
2375 ASSERT_TRUE(h_result == nullptr);
2376 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2377
2378 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2379 ScopedAddrinfo ai_result = safe_getaddrinfo(host_name2, nullptr, &hints);
2380 EXPECT_TRUE(ai_result == nullptr);
2381 EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
2382}
2383
2384// DNS-over-TLS validation success, but server does not respond to TLS query after a while.
2385// Moreover, server responds RCODE=FORMERR even on non-EDNS query.
2386TEST_F(ResolverTest, BogusDnsServer) {
2387 const char CLEARTEXT_ADDR[] = "127.0.0.53";
2388 const char CLEARTEXT_PORT[] = "53";
2389 const char TLS_PORT[] = "853";
2390 const char* host_name1 = "nonexistent1.example.com.";
2391 const char* host_name2 = "nonexistent2.example.com.";
2392 const std::vector<std::string> servers = {CLEARTEXT_ADDR};
2393
Mike Yufc125e42019-05-15 20:41:28 +08002394 test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, ns_rcode::ns_r_servfail);
Ken Chen0a015532019-01-02 14:59:38 +08002395 ASSERT_TRUE(dns.startServer());
2396 test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2397 ASSERT_TRUE(tls.startServer());
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09002398 ASSERT_TRUE(
Xiao Ma09b71022018-12-11 17:56:32 +09002399 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
Ken Chen0a015532019-01-02 14:59:38 +08002400 // Wait for validation complete.
2401 EXPECT_TRUE(tls.waitForQueries(1, 5000));
2402 // Shutdown TLS server to get an error. It's similar to no response case but without waiting.
2403 tls.stopServer();
2404 dns.setEdns(test::DNSResponder::Edns::FORMERR_UNCOND);
2405
2406 const hostent* h_result = gethostbyname(host_name1);
2407 EXPECT_EQ(0U, GetNumQueries(dns, host_name1));
2408 ASSERT_TRUE(h_result == nullptr);
2409 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2410
2411 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2412 ScopedAddrinfo ai_result = safe_getaddrinfo(host_name2, nullptr, &hints);
2413 EXPECT_TRUE(ai_result == nullptr);
2414 EXPECT_EQ(0U, GetNumQueries(dns, host_name2));
2415}
2416
nuccachena26cc2a2018-07-17 18:07:23 +08002417TEST_F(ResolverTest, GetAddrInfo_Dns64Synthesize) {
2418 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002419 constexpr char dns64_name[] = "ipv4only.arpa.";
2420 constexpr char host_name[] = "v4only.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09002421 const std::vector<DnsRecord> records = {
2422 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2423 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2424 };
nuccachena26cc2a2018-07-17 18:07:23 +08002425
Xiao Ma09b71022018-12-11 17:56:32 +09002426 test::DNSResponder dns(listen_addr);
Xiao Ma09b71022018-12-11 17:56:32 +09002427 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002428
2429 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002430 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002431
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002432 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002433 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002434 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002435
2436 // hints are necessary in order to let netd know which type of addresses the caller is
2437 // interested in.
Xiao Ma09b71022018-12-11 17:56:32 +09002438 const addrinfo hints = {.ai_family = AF_UNSPEC};
nuccachena26cc2a2018-07-17 18:07:23 +08002439 ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, &hints);
2440 EXPECT_TRUE(result != nullptr);
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002441 // TODO: BUG: there should only be two queries, one AAAA (which returns no records) and one A
2442 // (which returns 1.2.3.4). But there is an extra AAAA.
2443 EXPECT_EQ(3U, GetNumQueries(dns, host_name));
nuccachena26cc2a2018-07-17 18:07:23 +08002444
2445 std::string result_str = ToString(result);
2446 EXPECT_EQ(result_str, "64:ff9b::102:304");
2447
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002448 // Stopping NAT64 prefix discovery disables synthesis.
Luke Huang5bd827c2019-03-14 16:10:04 +08002449 EXPECT_TRUE(mDnsClient.resolvService()->stopPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002450 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_NOT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002451
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002452 dns.clearQueries();
nuccachena26cc2a2018-07-17 18:07:23 +08002453
2454 result = safe_getaddrinfo("v4only", nullptr, &hints);
2455 EXPECT_TRUE(result != nullptr);
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002456 // TODO: BUG: there should only be one query, an AAAA (which returns no records), because the
2457 // A is already cached. But there is an extra AAAA.
2458 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
nuccachena26cc2a2018-07-17 18:07:23 +08002459
2460 result_str = ToString(result);
2461 EXPECT_EQ(result_str, "1.2.3.4");
2462}
2463
nuccachena26cc2a2018-07-17 18:07:23 +08002464TEST_F(ResolverTest, GetAddrInfo_Dns64QuerySpecified) {
2465 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002466 constexpr char dns64_name[] = "ipv4only.arpa.";
2467 constexpr char host_name[] = "v4only.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09002468 const std::vector<DnsRecord> records = {
2469 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2470 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2471 };
nuccachena26cc2a2018-07-17 18:07:23 +08002472
Xiao Ma09b71022018-12-11 17:56:32 +09002473 test::DNSResponder dns(listen_addr);
2474 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002475 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002476 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002477
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002478 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002479 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002480 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002481
2482 // Ensure to synthesize AAAA if AF_INET6 is specified, and not to synthesize AAAA
2483 // in AF_INET case.
2484 addrinfo hints;
2485 memset(&hints, 0, sizeof(hints));
2486 hints.ai_family = AF_INET6;
2487 ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, &hints);
2488 EXPECT_TRUE(result != nullptr);
2489 std::string result_str = ToString(result);
2490 EXPECT_EQ(result_str, "64:ff9b::102:304");
2491
2492 hints.ai_family = AF_INET;
2493 result = safe_getaddrinfo("v4only", nullptr, &hints);
2494 EXPECT_TRUE(result != nullptr);
2495 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2496 result_str = ToString(result);
2497 EXPECT_EQ(result_str, "1.2.3.4");
2498}
nuccachena26cc2a2018-07-17 18:07:23 +08002499
2500TEST_F(ResolverTest, GetAddrInfo_Dns64QueryUnspecifiedV6) {
2501 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002502 constexpr char dns64_name[] = "ipv4only.arpa.";
2503 constexpr char host_name[] = "v4v6.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09002504 const std::vector<DnsRecord> records = {
2505 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2506 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2507 {host_name, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
2508 };
nuccachena26cc2a2018-07-17 18:07:23 +08002509
Xiao Ma09b71022018-12-11 17:56:32 +09002510 test::DNSResponder dns(listen_addr);
2511 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002512 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002513 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002514
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002515 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002516 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002517 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002518
Xiao Ma09b71022018-12-11 17:56:32 +09002519 const addrinfo hints = {.ai_family = AF_UNSPEC};
nuccachena26cc2a2018-07-17 18:07:23 +08002520 ScopedAddrinfo result = safe_getaddrinfo("v4v6", nullptr, &hints);
2521 EXPECT_TRUE(result != nullptr);
2522 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2523
2524 // In AF_UNSPEC case, do not synthesize AAAA if there's at least one AAAA answer.
Xiao Ma09b71022018-12-11 17:56:32 +09002525 const std::vector<std::string> result_strs = ToStrings(result);
nuccachena26cc2a2018-07-17 18:07:23 +08002526 for (const auto& str : result_strs) {
2527 EXPECT_TRUE(str == "1.2.3.4" || str == "2001:db8::102:304")
2528 << ", result_str='" << str << "'";
2529 }
2530}
2531
2532TEST_F(ResolverTest, GetAddrInfo_Dns64QueryUnspecifiedNoV6) {
2533 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002534 constexpr char dns64_name[] = "ipv4only.arpa.";
2535 constexpr char host_name[] = "v4v6.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09002536 const std::vector<DnsRecord> records = {
2537 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2538 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2539 };
nuccachena26cc2a2018-07-17 18:07:23 +08002540
Xiao Ma09b71022018-12-11 17:56:32 +09002541 test::DNSResponder dns(listen_addr);
2542 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002543 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002544 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002545
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002546 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002547 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002548 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002549
Xiao Ma09b71022018-12-11 17:56:32 +09002550 const addrinfo hints = {.ai_family = AF_UNSPEC};
nuccachena26cc2a2018-07-17 18:07:23 +08002551 ScopedAddrinfo result = safe_getaddrinfo("v4v6", nullptr, &hints);
2552 EXPECT_TRUE(result != nullptr);
2553 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2554
2555 // In AF_UNSPEC case, synthesize AAAA if there's no AAAA answer.
2556 std::string result_str = ToString(result);
2557 EXPECT_EQ(result_str, "64:ff9b::102:304");
2558}
2559
2560TEST_F(ResolverTest, GetAddrInfo_Dns64QuerySpecialUseIPv4Addresses) {
2561 constexpr char THIS_NETWORK[] = "this_network";
2562 constexpr char LOOPBACK[] = "loopback";
2563 constexpr char LINK_LOCAL[] = "link_local";
2564 constexpr char MULTICAST[] = "multicast";
2565 constexpr char LIMITED_BROADCAST[] = "limited_broadcast";
2566
2567 constexpr char ADDR_THIS_NETWORK[] = "0.0.0.1";
2568 constexpr char ADDR_LOOPBACK[] = "127.0.0.1";
2569 constexpr char ADDR_LINK_LOCAL[] = "169.254.0.1";
2570 constexpr char ADDR_MULTICAST[] = "224.0.0.1";
2571 constexpr char ADDR_LIMITED_BROADCAST[] = "255.255.255.255";
2572
2573 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002574 constexpr char dns64_name[] = "ipv4only.arpa.";
2575
Xiao Ma09b71022018-12-11 17:56:32 +09002576 test::DNSResponder dns(listen_addr);
2577 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
nuccachena26cc2a2018-07-17 18:07:23 +08002578 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002579 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002580
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002581 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002582 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002583 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002584
2585 static const struct TestConfig {
2586 std::string name;
2587 std::string addr;
2588
2589 std::string asHostName() const { return StringPrintf("%s.example.com.", name.c_str()); }
2590 } testConfigs[]{
2591 {THIS_NETWORK, ADDR_THIS_NETWORK},
2592 {LOOPBACK, ADDR_LOOPBACK},
2593 {LINK_LOCAL, ADDR_LINK_LOCAL},
2594 {MULTICAST, ADDR_MULTICAST},
2595 {LIMITED_BROADCAST, ADDR_LIMITED_BROADCAST}
2596 };
2597
2598 for (const auto& config : testConfigs) {
2599 const std::string testHostName = config.asHostName();
2600 SCOPED_TRACE(testHostName);
2601
2602 const char* host_name = testHostName.c_str();
2603 dns.addMapping(host_name, ns_type::ns_t_a, config.addr.c_str());
2604
2605 addrinfo hints;
2606 memset(&hints, 0, sizeof(hints));
2607 hints.ai_family = AF_INET6;
2608 ScopedAddrinfo result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
2609 // In AF_INET6 case, don't return IPv4 answers
2610 EXPECT_TRUE(result == nullptr);
2611 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2612 dns.clearQueries();
2613
2614 memset(&hints, 0, sizeof(hints));
2615 hints.ai_family = AF_UNSPEC;
2616 result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
2617 EXPECT_TRUE(result != nullptr);
2618 // Expect IPv6 query only. IPv4 answer has been cached in previous query.
2619 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2620 // In AF_UNSPEC case, don't synthesize special use IPv4 address.
2621 std::string result_str = ToString(result);
2622 EXPECT_EQ(result_str, config.addr.c_str());
2623 dns.clearQueries();
2624 }
2625}
2626
2627TEST_F(ResolverTest, GetAddrInfo_Dns64QueryWithNullArgumentHints) {
2628 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002629 constexpr char dns64_name[] = "ipv4only.arpa.";
2630 constexpr char host_name[] = "v4only.example.com.";
2631 constexpr char host_name2[] = "v4v6.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09002632 const std::vector<DnsRecord> records = {
2633 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2634 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2635 {host_name2, ns_type::ns_t_a, "1.2.3.4"},
2636 {host_name2, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
2637 };
nuccachena26cc2a2018-07-17 18:07:23 +08002638
Xiao Ma09b71022018-12-11 17:56:32 +09002639 test::DNSResponder dns(listen_addr);
2640 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002641 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002642 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002643
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002644 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002645 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002646 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002647
2648 // Assign argument hints of getaddrinfo() as null is equivalent to set ai_family AF_UNSPEC.
2649 // In AF_UNSPEC case, synthesize AAAA if there has A answer only.
2650 ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, nullptr);
2651 EXPECT_TRUE(result != nullptr);
2652 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2653 std::string result_str = ToString(result);
2654 EXPECT_EQ(result_str, "64:ff9b::102:304");
2655 dns.clearQueries();
2656
2657 // In AF_UNSPEC case, do not synthesize AAAA if there's at least one AAAA answer.
2658 result = safe_getaddrinfo("v4v6", nullptr, nullptr);
2659 EXPECT_TRUE(result != nullptr);
2660 EXPECT_LE(2U, GetNumQueries(dns, host_name2));
2661 std::vector<std::string> result_strs = ToStrings(result);
2662 for (const auto& str : result_strs) {
2663 EXPECT_TRUE(str == "1.2.3.4" || str == "2001:db8::102:304")
2664 << ", result_str='" << str << "'";
2665 }
2666}
2667
2668TEST_F(ResolverTest, GetAddrInfo_Dns64QueryNullArgumentNode) {
2669 constexpr char ADDR_ANYADDR_V4[] = "0.0.0.0";
2670 constexpr char ADDR_ANYADDR_V6[] = "::";
2671 constexpr char ADDR_LOCALHOST_V4[] = "127.0.0.1";
2672 constexpr char ADDR_LOCALHOST_V6[] = "::1";
2673
2674 constexpr char PORT_NAME_HTTP[] = "http";
2675 constexpr char PORT_NUMBER_HTTP[] = "80";
2676
2677 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002678 constexpr char dns64_name[] = "ipv4only.arpa.";
2679
Xiao Ma09b71022018-12-11 17:56:32 +09002680 test::DNSResponder dns(listen_addr);
2681 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
nuccachena26cc2a2018-07-17 18:07:23 +08002682 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002683 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002684
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002685 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002686 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002687 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002688
2689 // If node is null, return address is listed by libc/getaddrinfo.c as follows.
2690 // - passive socket -> anyaddr (0.0.0.0 or ::)
2691 // - non-passive socket -> localhost (127.0.0.1 or ::1)
2692 static const struct TestConfig {
2693 int flag;
2694 std::string addr_v4;
2695 std::string addr_v6;
2696
2697 std::string asParameters() const {
2698 return StringPrintf("flag=%d, addr_v4=%s, addr_v6=%s", flag, addr_v4.c_str(),
2699 addr_v6.c_str());
2700 }
2701 } testConfigs[]{
2702 {0 /* non-passive */, ADDR_LOCALHOST_V4, ADDR_LOCALHOST_V6},
2703 {AI_PASSIVE, ADDR_ANYADDR_V4, ADDR_ANYADDR_V6}
2704 };
2705
2706 for (const auto& config : testConfigs) {
2707 SCOPED_TRACE(config.asParameters());
2708
Xiao Ma09b71022018-12-11 17:56:32 +09002709 addrinfo hints = {
2710 .ai_family = AF_UNSPEC, // any address family
2711 .ai_socktype = 0, // any type
2712 .ai_protocol = 0, // any protocol
2713 .ai_flags = config.flag,
2714 };
nuccachena26cc2a2018-07-17 18:07:23 +08002715
2716 // Assign hostname as null and service as port name.
2717 ScopedAddrinfo result = safe_getaddrinfo(nullptr, PORT_NAME_HTTP, &hints);
2718 ASSERT_TRUE(result != nullptr);
2719
2720 // Can't be synthesized because it should not get into Netd.
2721 std::vector<std::string> result_strs = ToStrings(result);
2722 for (const auto& str : result_strs) {
2723 EXPECT_TRUE(str == config.addr_v4 || str == config.addr_v6)
2724 << ", result_str='" << str << "'";
2725 }
2726
2727 // Assign hostname as null and service as numeric port number.
2728 hints.ai_flags = config.flag | AI_NUMERICSERV;
2729 result = safe_getaddrinfo(nullptr, PORT_NUMBER_HTTP, &hints);
2730 ASSERT_TRUE(result != nullptr);
2731
2732 // Can't be synthesized because it should not get into Netd.
2733 result_strs = ToStrings(result);
2734 for (const auto& str : result_strs) {
2735 EXPECT_TRUE(str == config.addr_v4 || str == config.addr_v6)
2736 << ", result_str='" << str << "'";
2737 }
2738 }
2739}
2740
2741TEST_F(ResolverTest, GetHostByAddr_ReverseDnsQueryWithHavingNat64Prefix) {
2742 struct hostent* result = nullptr;
2743 struct in_addr v4addr;
2744 struct in6_addr v6addr;
2745
2746 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002747 constexpr char dns64_name[] = "ipv4only.arpa.";
2748 constexpr char ptr_name[] = "v4v6.example.com.";
2749 // PTR record for IPv4 address 1.2.3.4
2750 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2751 // PTR record for IPv6 address 2001:db8::102:304
2752 constexpr char ptr_addr_v6[] =
2753 "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 Ma09b71022018-12-11 17:56:32 +09002754 const std::vector<DnsRecord> records = {
2755 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2756 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2757 {ptr_addr_v6, ns_type::ns_t_ptr, ptr_name},
2758 };
nuccachena26cc2a2018-07-17 18:07:23 +08002759
Xiao Ma09b71022018-12-11 17:56:32 +09002760 test::DNSResponder dns(listen_addr);
2761 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002762 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002763 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002764
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002765 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002766 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002767 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002768
2769 // Reverse IPv4 DNS query. Prefix should have no effect on it.
2770 inet_pton(AF_INET, "1.2.3.4", &v4addr);
2771 result = gethostbyaddr(&v4addr, sizeof(v4addr), AF_INET);
2772 ASSERT_TRUE(result != nullptr);
2773 std::string result_str = result->h_name ? result->h_name : "null";
2774 EXPECT_EQ(result_str, "v4v6.example.com");
2775
2776 // Reverse IPv6 DNS query. Prefix should have no effect on it.
2777 inet_pton(AF_INET6, "2001:db8::102:304", &v6addr);
2778 result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2779 ASSERT_TRUE(result != nullptr);
2780 result_str = result->h_name ? result->h_name : "null";
2781 EXPECT_EQ(result_str, "v4v6.example.com");
2782}
2783
2784TEST_F(ResolverTest, GetHostByAddr_ReverseDns64Query) {
2785 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002786 constexpr char dns64_name[] = "ipv4only.arpa.";
2787 constexpr char ptr_name[] = "v4only.example.com.";
2788 // PTR record for IPv4 address 1.2.3.4
2789 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2790 // PTR record for IPv6 address 64:ff9b::1.2.3.4
2791 constexpr char ptr_addr_v6_nomapping[] =
2792 "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.";
2793 constexpr char ptr_name_v6_synthesis[] = "v6synthesis.example.com.";
2794 // PTR record for IPv6 address 64:ff9b::5.6.7.8
2795 constexpr char ptr_addr_v6_synthesis[] =
2796 "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 Ma09b71022018-12-11 17:56:32 +09002797 const std::vector<DnsRecord> records = {
2798 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2799 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2800 {ptr_addr_v6_synthesis, ns_type::ns_t_ptr, ptr_name_v6_synthesis},
2801 };
nuccachena26cc2a2018-07-17 18:07:23 +08002802
Xiao Ma09b71022018-12-11 17:56:32 +09002803 test::DNSResponder dns(listen_addr);
2804 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002805 // "ptr_addr_v6_nomapping" is not mapped in DNS server
nuccachena26cc2a2018-07-17 18:07:23 +08002806 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002807 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002808
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002809 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002810 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002811 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002812
2813 // Synthesized PTR record doesn't exist on DNS server
2814 // Reverse IPv6 DNS64 query while DNS server doesn't have an answer for synthesized address.
2815 // After querying synthesized address failed, expect that prefix is removed from IPv6
2816 // synthesized address and do reverse IPv4 query instead.
2817 struct in6_addr v6addr;
2818 inet_pton(AF_INET6, "64:ff9b::1.2.3.4", &v6addr);
2819 struct hostent* result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2820 ASSERT_TRUE(result != nullptr);
2821 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_nomapping)); // PTR record not exist
2822 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4)); // PTR record exist
2823 std::string result_str = result->h_name ? result->h_name : "null";
2824 EXPECT_EQ(result_str, "v4only.example.com");
2825 // Check that return address has been mapped from IPv4 to IPv6 address because Netd
2826 // removes NAT64 prefix and does IPv4 DNS reverse lookup in this case. Then, Netd
2827 // fakes the return IPv4 address as original queried IPv6 address.
2828 result_str = ToString(result);
2829 EXPECT_EQ(result_str, "64:ff9b::102:304");
2830 dns.clearQueries();
2831
2832 // Synthesized PTR record exists on DNS server
2833 // Reverse IPv6 DNS64 query while DNS server has an answer for synthesized address.
2834 // Expect to Netd pass through synthesized address for DNS queries.
2835 inet_pton(AF_INET6, "64:ff9b::5.6.7.8", &v6addr);
2836 result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2837 ASSERT_TRUE(result != nullptr);
2838 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_synthesis));
2839 result_str = result->h_name ? result->h_name : "null";
2840 EXPECT_EQ(result_str, "v6synthesis.example.com");
2841}
2842
2843TEST_F(ResolverTest, GetHostByAddr_ReverseDns64QueryFromHostFile) {
2844 constexpr char dns64_name[] = "ipv4only.arpa.";
2845 constexpr char host_name[] = "localhost";
2846 // The address is synthesized by prefix64:localhost.
2847 constexpr char host_addr[] = "64:ff9b::7f00:1";
nuccachena26cc2a2018-07-17 18:07:23 +08002848 constexpr char listen_addr[] = "::1";
Xiao Ma09b71022018-12-11 17:56:32 +09002849
2850 test::DNSResponder dns(listen_addr);
2851 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
nuccachena26cc2a2018-07-17 18:07:23 +08002852 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002853 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002854
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002855 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002856 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002857 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002858
2859 // Using synthesized "localhost" address to be a trick for resolving host name
2860 // from host file /etc/hosts and "localhost" is the only name in /etc/hosts. Note that this is
2861 // not realistic: the code never synthesizes AAAA records for addresses in 127.0.0.0/8.
2862 struct in6_addr v6addr;
2863 inet_pton(AF_INET6, host_addr, &v6addr);
2864 struct hostent* result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2865 ASSERT_TRUE(result != nullptr);
2866 // Expect no DNS queries; localhost is resolved via /etc/hosts.
2867 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
2868
2869 ASSERT_EQ(sizeof(in6_addr), (unsigned) result->h_length);
2870 ASSERT_EQ(AF_INET6, result->h_addrtype);
2871 std::string result_str = ToString(result);
2872 EXPECT_EQ(result_str, host_addr);
2873 result_str = result->h_name ? result->h_name : "null";
2874 EXPECT_EQ(result_str, host_name);
2875}
2876
2877TEST_F(ResolverTest, GetNameInfo_ReverseDnsQueryWithHavingNat64Prefix) {
2878 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002879 constexpr char dns64_name[] = "ipv4only.arpa.";
2880 constexpr char ptr_name[] = "v4v6.example.com.";
2881 // PTR record for IPv4 address 1.2.3.4
2882 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2883 // PTR record for IPv6 address 2001:db8::102:304
2884 constexpr char ptr_addr_v6[] =
2885 "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 Ma09b71022018-12-11 17:56:32 +09002886 const std::vector<DnsRecord> records = {
2887 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2888 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2889 {ptr_addr_v6, ns_type::ns_t_ptr, ptr_name},
2890 };
nuccachena26cc2a2018-07-17 18:07:23 +08002891
Xiao Ma09b71022018-12-11 17:56:32 +09002892 test::DNSResponder dns(listen_addr);
2893 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002894 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002895 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002896
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002897 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002898 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002899 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002900
2901 static const struct TestConfig {
2902 int flag;
2903 int family;
2904 std::string addr;
2905 std::string host;
2906
2907 std::string asParameters() const {
2908 return StringPrintf("flag=%d, family=%d, addr=%s, host=%s", flag, family, addr.c_str(),
2909 host.c_str());
2910 }
2911 } testConfigs[]{
2912 {NI_NAMEREQD, AF_INET, "1.2.3.4", "v4v6.example.com"},
2913 {NI_NUMERICHOST, AF_INET, "1.2.3.4", "1.2.3.4"},
2914 {0, AF_INET, "1.2.3.4", "v4v6.example.com"},
2915 {0, AF_INET, "5.6.7.8", "5.6.7.8"}, // unmapped
2916 {NI_NAMEREQD, AF_INET6, "2001:db8::102:304", "v4v6.example.com"},
2917 {NI_NUMERICHOST, AF_INET6, "2001:db8::102:304", "2001:db8::102:304"},
2918 {0, AF_INET6, "2001:db8::102:304", "v4v6.example.com"},
2919 {0, AF_INET6, "2001:db8::506:708", "2001:db8::506:708"}, // unmapped
2920 };
2921
2922 // Reverse IPv4/IPv6 DNS query. Prefix should have no effect on it.
2923 for (const auto& config : testConfigs) {
2924 SCOPED_TRACE(config.asParameters());
2925
2926 int rv;
2927 char host[NI_MAXHOST];
2928 struct sockaddr_in sin;
2929 struct sockaddr_in6 sin6;
2930 if (config.family == AF_INET) {
2931 memset(&sin, 0, sizeof(sin));
2932 sin.sin_family = AF_INET;
2933 inet_pton(AF_INET, config.addr.c_str(), &sin.sin_addr);
2934 rv = getnameinfo((const struct sockaddr*) &sin, sizeof(sin), host, sizeof(host),
2935 nullptr, 0, config.flag);
2936 if (config.flag == NI_NAMEREQD) EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4));
2937 } else if (config.family == AF_INET6) {
2938 memset(&sin6, 0, sizeof(sin6));
2939 sin6.sin6_family = AF_INET6;
2940 inet_pton(AF_INET6, config.addr.c_str(), &sin6.sin6_addr);
2941 rv = getnameinfo((const struct sockaddr*) &sin6, sizeof(sin6), host, sizeof(host),
2942 nullptr, 0, config.flag);
2943 if (config.flag == NI_NAMEREQD) EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6));
2944 }
2945 ASSERT_EQ(0, rv);
2946 std::string result_str = host;
2947 EXPECT_EQ(result_str, config.host);
2948 dns.clearQueries();
2949 }
2950}
2951
2952TEST_F(ResolverTest, GetNameInfo_ReverseDns64Query) {
2953 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002954 constexpr char dns64_name[] = "ipv4only.arpa.";
2955 constexpr char ptr_name[] = "v4only.example.com.";
2956 // PTR record for IPv4 address 1.2.3.4
2957 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2958 // PTR record for IPv6 address 64:ff9b::1.2.3.4
2959 constexpr char ptr_addr_v6_nomapping[] =
2960 "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.";
2961 constexpr char ptr_name_v6_synthesis[] = "v6synthesis.example.com.";
2962 // PTR record for IPv6 address 64:ff9b::5.6.7.8
2963 constexpr char ptr_addr_v6_synthesis[] =
2964 "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 Ma09b71022018-12-11 17:56:32 +09002965 const std::vector<DnsRecord> records = {
2966 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2967 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2968 {ptr_addr_v6_synthesis, ns_type::ns_t_ptr, ptr_name_v6_synthesis},
2969 };
nuccachena26cc2a2018-07-17 18:07:23 +08002970
Xiao Ma09b71022018-12-11 17:56:32 +09002971 test::DNSResponder dns(listen_addr);
2972 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002973 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002974 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002975
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002976 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002977 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002978 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002979
2980 static const struct TestConfig {
2981 bool hasSynthesizedPtrRecord;
2982 int flag;
2983 std::string addr;
2984 std::string host;
2985
2986 std::string asParameters() const {
2987 return StringPrintf("hasSynthesizedPtrRecord=%d, flag=%d, addr=%s, host=%s",
2988 hasSynthesizedPtrRecord, flag, addr.c_str(), host.c_str());
2989 }
2990 } testConfigs[]{
2991 {false, NI_NAMEREQD, "64:ff9b::102:304", "v4only.example.com"},
2992 {false, NI_NUMERICHOST, "64:ff9b::102:304", "64:ff9b::102:304"},
2993 {false, 0, "64:ff9b::102:304", "v4only.example.com"},
2994 {true, NI_NAMEREQD, "64:ff9b::506:708", "v6synthesis.example.com"},
2995 {true, NI_NUMERICHOST, "64:ff9b::506:708", "64:ff9b::506:708"},
2996 {true, 0, "64:ff9b::506:708", "v6synthesis.example.com"}
2997 };
2998
2999 // hasSynthesizedPtrRecord = false
3000 // Synthesized PTR record doesn't exist on DNS server
3001 // Reverse IPv6 DNS64 query while DNS server doesn't have an answer for synthesized address.
3002 // After querying synthesized address failed, expect that prefix is removed from IPv6
3003 // synthesized address and do reverse IPv4 query instead.
3004 //
3005 // hasSynthesizedPtrRecord = true
3006 // Synthesized PTR record exists on DNS server
3007 // Reverse IPv6 DNS64 query while DNS server has an answer for synthesized address.
3008 // Expect to just pass through synthesized address for DNS queries.
3009 for (const auto& config : testConfigs) {
3010 SCOPED_TRACE(config.asParameters());
3011
3012 char host[NI_MAXHOST];
3013 struct sockaddr_in6 sin6;
3014 memset(&sin6, 0, sizeof(sin6));
3015 sin6.sin6_family = AF_INET6;
3016 inet_pton(AF_INET6, config.addr.c_str(), &sin6.sin6_addr);
3017 int rv = getnameinfo((const struct sockaddr*) &sin6, sizeof(sin6), host, sizeof(host),
3018 nullptr, 0, config.flag);
3019 ASSERT_EQ(0, rv);
3020 if (config.flag == NI_NAMEREQD) {
3021 if (config.hasSynthesizedPtrRecord) {
3022 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_synthesis));
3023 } else {
3024 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_nomapping)); // PTR record not exist.
3025 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4)); // PTR record exist.
3026 }
3027 }
3028 std::string result_str = host;
3029 EXPECT_EQ(result_str, config.host);
3030 dns.clearQueries();
3031 }
3032}
3033
3034TEST_F(ResolverTest, GetNameInfo_ReverseDns64QueryFromHostFile) {
3035 constexpr char dns64_name[] = "ipv4only.arpa.";
3036 constexpr char host_name[] = "localhost";
3037 // The address is synthesized by prefix64:localhost.
3038 constexpr char host_addr[] = "64:ff9b::7f00:1";
nuccachena26cc2a2018-07-17 18:07:23 +08003039 constexpr char listen_addr[] = "::1";
Xiao Ma09b71022018-12-11 17:56:32 +09003040
3041 test::DNSResponder dns(listen_addr);
3042 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
nuccachena26cc2a2018-07-17 18:07:23 +08003043 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09003044 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08003045
Lorenzo Colittid39345c2019-02-18 10:59:29 +09003046 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08003047 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003048 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08003049
3050 // Using synthesized "localhost" address to be a trick for resolving host name
3051 // from host file /etc/hosts and "localhost" is the only name in /etc/hosts. Note that this is
3052 // not realistic: the code never synthesizes AAAA records for addresses in 127.0.0.0/8.
3053 char host[NI_MAXHOST];
Xiao Ma09b71022018-12-11 17:56:32 +09003054 struct sockaddr_in6 sin6 = {.sin6_family = AF_INET6};
nuccachena26cc2a2018-07-17 18:07:23 +08003055 inet_pton(AF_INET6, host_addr, &sin6.sin6_addr);
3056 int rv = getnameinfo((const struct sockaddr*) &sin6, sizeof(sin6), host, sizeof(host), nullptr,
3057 0, NI_NAMEREQD);
3058 ASSERT_EQ(0, rv);
3059 // Expect no DNS queries; localhost is resolved via /etc/hosts.
3060 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
3061
3062 std::string result_str = host;
3063 EXPECT_EQ(result_str, host_name);
3064}
3065
nuccachena26cc2a2018-07-17 18:07:23 +08003066TEST_F(ResolverTest, GetHostByName2_Dns64Synthesize) {
Xiao Ma09b71022018-12-11 17:56:32 +09003067 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08003068 constexpr char dns64_name[] = "ipv4only.arpa.";
3069 constexpr char host_name[] = "ipv4only.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09003070 const std::vector<DnsRecord> records = {
3071 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3072 {host_name, ns_type::ns_t_a, "1.2.3.4"},
3073 };
nuccachena26cc2a2018-07-17 18:07:23 +08003074
Xiao Ma09b71022018-12-11 17:56:32 +09003075 test::DNSResponder dns(listen_addr);
3076 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08003077 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09003078 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08003079
Lorenzo Colittid39345c2019-02-18 10:59:29 +09003080 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08003081 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003082 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08003083
3084 // Query an IPv4-only hostname. Expect that gets a synthesized address.
3085 struct hostent* result = gethostbyname2("ipv4only", AF_INET6);
3086 ASSERT_TRUE(result != nullptr);
3087 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3088 std::string result_str = ToString(result);
3089 EXPECT_EQ(result_str, "64:ff9b::102:304");
3090}
nuccachena26cc2a2018-07-17 18:07:23 +08003091
3092TEST_F(ResolverTest, GetHostByName2_DnsQueryWithHavingNat64Prefix) {
3093 constexpr char dns64_name[] = "ipv4only.arpa.";
3094 constexpr char host_name[] = "v4v6.example.com.";
nuccachena26cc2a2018-07-17 18:07:23 +08003095 constexpr char listen_addr[] = "::1";
Xiao Ma09b71022018-12-11 17:56:32 +09003096 const std::vector<DnsRecord> records = {
3097 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3098 {host_name, ns_type::ns_t_a, "1.2.3.4"},
3099 {host_name, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
3100 };
3101
3102 test::DNSResponder dns(listen_addr);
3103 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08003104 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09003105 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08003106
Lorenzo Colittid39345c2019-02-18 10:59:29 +09003107 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08003108 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003109 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08003110
3111 // IPv4 DNS query. Prefix should have no effect on it.
3112 struct hostent* result = gethostbyname2("v4v6", AF_INET);
3113 ASSERT_TRUE(result != nullptr);
3114 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3115 std::string result_str = ToString(result);
3116 EXPECT_EQ(result_str, "1.2.3.4");
3117 dns.clearQueries();
3118
3119 // IPv6 DNS query. Prefix should have no effect on it.
3120 result = gethostbyname2("v4v6", AF_INET6);
3121 ASSERT_TRUE(result != nullptr);
3122 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3123 result_str = ToString(result);
3124 EXPECT_EQ(result_str, "2001:db8::102:304");
3125}
3126
3127TEST_F(ResolverTest, GetHostByName2_Dns64QuerySpecialUseIPv4Addresses) {
3128 constexpr char THIS_NETWORK[] = "this_network";
3129 constexpr char LOOPBACK[] = "loopback";
3130 constexpr char LINK_LOCAL[] = "link_local";
3131 constexpr char MULTICAST[] = "multicast";
3132 constexpr char LIMITED_BROADCAST[] = "limited_broadcast";
3133
3134 constexpr char ADDR_THIS_NETWORK[] = "0.0.0.1";
3135 constexpr char ADDR_LOOPBACK[] = "127.0.0.1";
3136 constexpr char ADDR_LINK_LOCAL[] = "169.254.0.1";
3137 constexpr char ADDR_MULTICAST[] = "224.0.0.1";
3138 constexpr char ADDR_LIMITED_BROADCAST[] = "255.255.255.255";
3139
3140 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08003141 constexpr char dns64_name[] = "ipv4only.arpa.";
3142
Xiao Ma09b71022018-12-11 17:56:32 +09003143 test::DNSResponder dns(listen_addr);
3144 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
nuccachena26cc2a2018-07-17 18:07:23 +08003145 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09003146 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08003147
Lorenzo Colittid39345c2019-02-18 10:59:29 +09003148 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08003149 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003150 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08003151
3152 static const struct TestConfig {
3153 std::string name;
3154 std::string addr;
3155
3156 std::string asHostName() const {
3157 return StringPrintf("%s.example.com.",
3158 name.c_str());
3159 }
3160 } testConfigs[]{
3161 {THIS_NETWORK, ADDR_THIS_NETWORK},
3162 {LOOPBACK, ADDR_LOOPBACK},
3163 {LINK_LOCAL, ADDR_LINK_LOCAL},
3164 {MULTICAST, ADDR_MULTICAST},
3165 {LIMITED_BROADCAST, ADDR_LIMITED_BROADCAST}
3166 };
3167
3168 for (const auto& config : testConfigs) {
3169 const std::string testHostName = config.asHostName();
3170 SCOPED_TRACE(testHostName);
3171
3172 const char* host_name = testHostName.c_str();
3173 dns.addMapping(host_name, ns_type::ns_t_a, config.addr.c_str());
3174
3175 struct hostent* result = gethostbyname2(config.name.c_str(), AF_INET6);
3176 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3177
3178 // In AF_INET6 case, don't synthesize special use IPv4 address.
3179 // Expect to have no answer
3180 EXPECT_EQ(nullptr, result);
3181
3182 dns.clearQueries();
3183 }
Bernie Innocenti2fef2b82018-12-20 15:56:40 +09003184}
Mike Yuf14e1a92019-05-10 13:54:58 +08003185
3186TEST_F(ResolverTest, PrefixDiscoveryBypassTls) {
3187 constexpr char listen_addr[] = "::1";
3188 constexpr char cleartext_port[] = "53";
3189 constexpr char tls_port[] = "853";
3190 constexpr char dns64_name[] = "ipv4only.arpa.";
3191 const std::vector<std::string> servers = {listen_addr};
3192
3193 test::DNSResponder dns(listen_addr);
3194 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
3195 test::DnsTlsFrontend tls(listen_addr, tls_port, listen_addr, cleartext_port);
3196 ASSERT_TRUE(tls.startServer());
3197
3198 // Setup OPPORTUNISTIC mode and wait for the validation complete.
3199 ASSERT_TRUE(
3200 mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "", {}));
3201 EXPECT_TRUE(tls.waitForQueries(1, 5000));
3202 tls.clearQueries();
3203
3204 // Start NAT64 prefix discovery and wait for it complete.
3205 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003206 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
Mike Yuf14e1a92019-05-10 13:54:58 +08003207
3208 // Verify it bypassed TLS even though there's a TLS server available.
3209 EXPECT_EQ(0, tls.queries());
3210 EXPECT_EQ(1U, GetNumQueries(dns, dns64_name));
3211
3212 // Restart the testing network to reset the cache.
3213 mDnsClient.TearDown();
3214 mDnsClient.SetUp();
3215 dns.clearQueries();
3216
3217 // Setup STRICT mode and wait for the validation complete.
3218 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, "",
3219 {base64Encode(tls.fingerprint())}));
3220 EXPECT_TRUE(tls.waitForQueries(1, 5000));
3221 tls.clearQueries();
3222
3223 // Start NAT64 prefix discovery and wait for it to complete.
3224 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003225 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
Mike Yuf14e1a92019-05-10 13:54:58 +08003226
3227 // Verify it bypassed TLS despite STRICT mode.
3228 EXPECT_EQ(0, tls.queries());
3229 EXPECT_EQ(1U, GetNumQueries(dns, dns64_name));
3230}
Luke Huang9807e6b2019-05-20 16:17:12 +08003231
3232namespace {
3233
Luke Huang0d592bc2019-05-25 18:24:03 +08003234class ScopedSetNetworkForProcess {
3235 public:
3236 explicit ScopedSetNetworkForProcess(unsigned netId) {
3237 mStoredNetId = getNetworkForProcess();
3238 if (netId == mStoredNetId) return;
3239 EXPECT_EQ(0, setNetworkForProcess(netId));
3240 }
3241 ~ScopedSetNetworkForProcess() { EXPECT_EQ(0, setNetworkForProcess(mStoredNetId)); }
3242
3243 private:
3244 unsigned mStoredNetId;
3245};
3246
3247class ScopedSetNetworkForResolv {
3248 public:
3249 explicit ScopedSetNetworkForResolv(unsigned netId) { EXPECT_EQ(0, setNetworkForResolv(netId)); }
3250 ~ScopedSetNetworkForResolv() { EXPECT_EQ(0, setNetworkForResolv(NETID_UNSET)); }
3251};
3252
Luke Huang9807e6b2019-05-20 16:17:12 +08003253void sendCommand(int fd, const std::string& cmd) {
3254 ssize_t rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size() + 1));
3255 EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size() + 1));
3256}
3257
3258int32_t readBE32(int fd) {
3259 int32_t tmp;
3260 int n = TEMP_FAILURE_RETRY(read(fd, &tmp, sizeof(tmp)));
3261 EXPECT_TRUE(n > 0);
3262 return ntohl(tmp);
3263}
3264
Luke Huang0d592bc2019-05-25 18:24:03 +08003265int readResponseCode(int fd) {
Luke Huang9807e6b2019-05-20 16:17:12 +08003266 char buf[4];
3267 int n = TEMP_FAILURE_RETRY(read(fd, &buf, sizeof(buf)));
3268 EXPECT_TRUE(n > 0);
3269 // The format of response code is that 4 bytes for the code & null.
3270 buf[3] = '\0';
3271 int result;
3272 EXPECT_TRUE(ParseInt(buf, &result));
3273 return result;
3274}
3275
Luke Huang0d592bc2019-05-25 18:24:03 +08003276bool checkAndClearUseLocalNameserversFlag(unsigned* netid) {
3277 if (netid == nullptr || ((*netid) & NETID_USE_LOCAL_NAMESERVERS) == 0) {
3278 return false;
3279 }
3280 *netid = (*netid) & ~NETID_USE_LOCAL_NAMESERVERS;
3281 return true;
3282}
3283
3284android::net::UidRangeParcel makeUidRangeParcel(int start, int stop) {
3285 android::net::UidRangeParcel res;
3286 res.start = start;
3287 res.stop = stop;
3288
3289 return res;
3290}
3291
3292void expectNetIdWithLocalNameserversFlag(unsigned netId) {
3293 unsigned dnsNetId = 0;
3294 EXPECT_EQ(0, getNetworkForDns(&dnsNetId));
3295 EXPECT_TRUE(checkAndClearUseLocalNameserversFlag(&dnsNetId));
3296 EXPECT_EQ(netId, static_cast<unsigned>(dnsNetId));
3297}
3298
3299void expectDnsNetIdEquals(unsigned netId) {
3300 unsigned dnsNetId = 0;
3301 EXPECT_EQ(0, getNetworkForDns(&dnsNetId));
3302 EXPECT_EQ(netId, static_cast<unsigned>(dnsNetId));
3303}
3304
3305void expectDnsNetIdIsDefaultNetwork(android::net::INetd* netdService) {
3306 int currentNetid;
3307 EXPECT_TRUE(netdService->networkGetDefault(&currentNetid).isOk());
3308 expectDnsNetIdEquals(currentNetid);
3309}
3310
3311void expectDnsNetIdWithVpn(android::net::INetd* netdService, unsigned vpnNetId,
3312 unsigned expectedNetId) {
3313 EXPECT_TRUE(netdService->networkCreateVpn(vpnNetId, false /* secure */).isOk());
3314 uid_t uid = getuid();
3315 // Add uid to VPN
3316 EXPECT_TRUE(netdService->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3317 expectDnsNetIdEquals(expectedNetId);
3318 EXPECT_TRUE(netdService->networkDestroy(vpnNetId).isOk());
3319}
3320
Luke Huang9807e6b2019-05-20 16:17:12 +08003321} // namespace
3322
3323TEST_F(ResolverTest, getDnsNetId) {
3324 // We've called setNetworkForProcess in SetupOemNetwork, so reset to default first.
3325 setNetworkForProcess(NETID_UNSET);
Luke Huang0d592bc2019-05-25 18:24:03 +08003326
3327 expectDnsNetIdIsDefaultNetwork(mDnsClient.netdService());
3328 expectDnsNetIdWithVpn(mDnsClient.netdService(), TEST_VPN_NETID, TEST_VPN_NETID);
Luke Huang9807e6b2019-05-20 16:17:12 +08003329
3330 // Test with setNetworkForProcess
Luke Huang0d592bc2019-05-25 18:24:03 +08003331 {
3332 ScopedSetNetworkForProcess scopedSetNetworkForProcess(TEST_NETID);
3333 expectDnsNetIdEquals(TEST_NETID);
3334 }
3335
3336 // Test with setNetworkForProcess with NETID_USE_LOCAL_NAMESERVERS
3337 {
3338 ScopedSetNetworkForProcess scopedSetNetworkForProcess(TEST_NETID |
3339 NETID_USE_LOCAL_NAMESERVERS);
3340 expectNetIdWithLocalNameserversFlag(TEST_NETID);
3341 }
Luke Huang9807e6b2019-05-20 16:17:12 +08003342
3343 // Test with setNetworkForResolv
Luke Huang0d592bc2019-05-25 18:24:03 +08003344 {
3345 ScopedSetNetworkForResolv scopedSetNetworkForResolv(TEST_NETID);
3346 expectDnsNetIdEquals(TEST_NETID);
3347 }
3348
3349 // Test with setNetworkForResolv with NETID_USE_LOCAL_NAMESERVERS
3350 {
3351 ScopedSetNetworkForResolv scopedSetNetworkForResolv(TEST_NETID |
3352 NETID_USE_LOCAL_NAMESERVERS);
3353 expectNetIdWithLocalNameserversFlag(TEST_NETID);
3354 }
3355
3356 // Test with setNetworkForResolv under bypassable vpn
3357 {
3358 ScopedSetNetworkForResolv scopedSetNetworkForResolv(TEST_NETID);
3359 expectDnsNetIdWithVpn(mDnsClient.netdService(), TEST_VPN_NETID, TEST_NETID);
3360 }
Luke Huang9807e6b2019-05-20 16:17:12 +08003361
3362 // Create socket connected to DnsProxyListener
3363 int fd = dns_open_proxy();
3364 EXPECT_TRUE(fd > 0);
3365 unique_fd ufd(fd);
3366
3367 // Test command with wrong netId
3368 sendCommand(fd, "getdnsnetid abc");
Luke Huang0d592bc2019-05-25 18:24:03 +08003369 EXPECT_EQ(ResponseCode::DnsProxyQueryResult, readResponseCode(fd));
Luke Huang9807e6b2019-05-20 16:17:12 +08003370 EXPECT_EQ(-EINVAL, readBE32(fd));
3371
3372 // Test unsupported command
3373 sendCommand(fd, "getdnsnetidNotSupported");
3374 // Keep in sync with FrameworkListener.cpp (500, "Command not recognized")
Luke Huang0d592bc2019-05-25 18:24:03 +08003375 EXPECT_EQ(500, readResponseCode(fd));
Luke Huang9807e6b2019-05-20 16:17:12 +08003376}