blob: 5b8dd4fac6af3e62b4ec92040b1e4a7c0d8474c7 [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 *
Lorenzo Colitti0a8b4aa2019-06-26 22:31:03 +090010 * Unless required by applicable law or agreed to in writing, software
Ken Chenb9fa2062018-11-13 21:51:13 +080011 * 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>
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +090028#include <bpf/BpfUtils.h>
Bernie Innocenti41b82c42019-06-05 22:38:25 +090029#include <cutils/sockets.h>
30#include <gmock/gmock-matchers.h>
31#include <gtest/gtest.h>
Ken Chenb9fa2062018-11-13 21:51:13 +080032#include <netdb.h>
Luke Huang9d2d25b2019-06-14 00:34:05 +080033#include <netdutils/InternetAddresses.h>
Luke Huang579ddc72019-06-14 00:59:39 +080034#include <netdutils/NetworkConstants.h> // SHA256_SIZE
Luke Huang9d2d25b2019-06-14 00:34:05 +080035#include <netdutils/ResponseCode.h>
Hungming Chen63779052019-10-30 15:06:13 +080036#include <netdutils/Slice.h>
Luke Huang9d2d25b2019-06-14 00:34:05 +080037#include <netdutils/SocketOption.h>
Luke Huang94b10b92018-11-21 20:13:38 +080038#include <netinet/in.h>
Bernie Innocenti41b82c42019-06-05 22:38:25 +090039#include <openssl/base64.h>
Luke Huang94b10b92018-11-21 20:13:38 +080040#include <poll.h> /* poll */
Bernie Innocenti41b82c42019-06-05 22:38:25 +090041#include <private/android_filesystem_config.h>
Luke Huang94b10b92018-11-21 20:13:38 +080042#include <resolv.h>
Ken Chenb9fa2062018-11-13 21:51:13 +080043#include <stdarg.h>
Ken Chenb9fa2062018-11-13 21:51:13 +080044#include <stdlib.h>
Luke Huang94b10b92018-11-21 20:13:38 +080045#include <sys/socket.h>
46#include <sys/un.h>
Ken Chenb9fa2062018-11-13 21:51:13 +080047#include <unistd.h>
48
49#include <algorithm>
50#include <chrono>
51#include <iterator>
52#include <numeric>
53#include <thread>
54
Bernie Innocenti41b82c42019-06-05 22:38:25 +090055#include "NetdClient.h"
Bernie Innocenti41b82c42019-06-05 22:38:25 +090056#include "ResolverStats.h"
57#include "android/net/IDnsResolver.h"
58#include "binder/IServiceManager.h"
Bernie Innocenti41b82c42019-06-05 22:38:25 +090059#include "netd_resolv/params.h" // MAXNS
chenbruceb43ec752019-07-24 20:19:41 +080060#include "netid_client.h" // NETID_UNSET
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +090061#include "test_utils.h"
Hungming Chene8f970c2019-04-10 17:34:06 +080062#include "tests/dns_metrics_listener/dns_metrics_listener.h"
chenbruceb43ec752019-07-24 20:19:41 +080063#include "tests/dns_responder/dns_responder.h"
64#include "tests/dns_responder/dns_responder_client.h"
65#include "tests/dns_responder/dns_tls_frontend.h"
Luke Huangfde82482019-06-04 01:04:53 +080066#include "tests/resolv_test_utils.h"
Ken Chenb9fa2062018-11-13 21:51:13 +080067
Luke Huang0d592bc2019-05-25 18:24:03 +080068// Valid VPN netId range is 100 ~ 65535
69constexpr int TEST_VPN_NETID = 65502;
Luke Huang94b10b92018-11-21 20:13:38 +080070constexpr int MAXPACKET = (8 * 1024);
Ken Chenb9fa2062018-11-13 21:51:13 +080071
Sehee Park2c118782019-05-07 13:02:45 +090072// Use maximum reserved appId for applications to avoid conflict with existing uids.
73static const int TEST_UID = 99999;
74
waynema0e73c2e2019-07-31 15:04:08 +080075// Currently the hostname of TLS server must match the CN filed on the server's certificate.
76// Inject a test CA whose hostname is "example.com" for DNS-OVER-TLS tests.
77static const std::string kDefaultPrivateDnsHostName = "example.com";
78static const std::string kDefaultIncorrectPrivateDnsHostName = "www.example.com";
79
Ken Chenb9fa2062018-11-13 21:51:13 +080080// Semi-public Bionic hook used by the NDK (frameworks/base/native/android/net.c)
81// Tested here for convenience.
82extern "C" int android_getaddrinfofornet(const char* hostname, const char* servname,
83 const addrinfo* hints, unsigned netid, unsigned mark,
84 struct addrinfo** result);
85
Luke Huang9807e6b2019-05-20 16:17:12 +080086using android::base::ParseInt;
Ken Chenb9fa2062018-11-13 21:51:13 +080087using android::base::StringPrintf;
Luke Huang9807e6b2019-05-20 16:17:12 +080088using android::base::unique_fd;
Sehee Park2c118782019-05-07 13:02:45 +090089using android::net::INetd;
Ken Chenb9fa2062018-11-13 21:51:13 +080090using android::net::ResolverStats;
Hungming Chene8f970c2019-04-10 17:34:06 +080091using android::net::metrics::DnsMetricsListener;
Ken Chenb9fa2062018-11-13 21:51:13 +080092using android::netdutils::enableSockopt;
Hungming Chen63779052019-10-30 15:06:13 +080093using android::netdutils::makeSlice;
Luke Huang9807e6b2019-05-20 16:17:12 +080094using android::netdutils::ResponseCode;
Luke Huang9d2d25b2019-06-14 00:34:05 +080095using android::netdutils::ScopedAddrinfo;
Hungming Chen63779052019-10-30 15:06:13 +080096using android::netdutils::toHex;
Ken Chenb9fa2062018-11-13 21:51:13 +080097
98// TODO: move into libnetdutils?
99namespace {
Luke Huangfde82482019-06-04 01:04:53 +0800100
Ken Chenb9fa2062018-11-13 21:51:13 +0800101ScopedAddrinfo safe_getaddrinfo(const char* node, const char* service,
102 const struct addrinfo* hints) {
103 addrinfo* result = nullptr;
104 if (getaddrinfo(node, service, hints, &result) != 0) {
105 result = nullptr; // Should already be the case, but...
106 }
107 return ScopedAddrinfo(result);
108}
Luke Huangfde82482019-06-04 01:04:53 +0800109
Ken Chenb9fa2062018-11-13 21:51:13 +0800110} // namespace
111
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900112class ResolverTest : public ::testing::Test {
Hungming Chene8f970c2019-04-10 17:34:06 +0800113 public:
Hungming Chen5bf09772019-04-25 11:16:13 +0800114 static void SetUpTestCase() {
115 // Get binder service.
116 // Note that |mDnsClient| is not used for getting binder service in this static function.
117 // The reason is that wants to keep |mDnsClient| as a non-static data member. |mDnsClient|
118 // which sets up device network configuration could be independent from every test.
Hungming Chen9e6185a2019-06-04 16:09:19 +0800119 // TODO: Perhaps add a static function in resolv_test_utils.{cpp,h} to get binder service.
Hungming Chen5bf09772019-04-25 11:16:13 +0800120 auto resolvBinder =
121 android::defaultServiceManager()->getService(android::String16("dnsresolver"));
122 auto resolvService = android::interface_cast<android::net::IDnsResolver>(resolvBinder);
123 ASSERT_NE(nullptr, resolvService.get());
124
125 // Subscribe the death recipient to the service IDnsResolver for detecting Netd death.
126 sResolvDeathRecipient = new ResolvDeathRecipient();
127 ASSERT_EQ(android::NO_ERROR, resolvBinder->linkToDeath(sResolvDeathRecipient));
128
129 // Subscribe the DNS listener for verifying DNS metrics event contents.
130 sDnsMetricsListener = new DnsMetricsListener(TEST_NETID /*monitor specific network*/);
131 ASSERT_TRUE(resolvService->registerEventListener(sDnsMetricsListener).isOk());
132
133 // Start the binder thread pool for listening DNS metrics events and receiving death
134 // recipient.
135 android::ProcessState::self()->startThreadPool();
Hungming Chene8f970c2019-04-10 17:34:06 +0800136 }
137
Ken Chenb9fa2062018-11-13 21:51:13 +0800138 protected:
Xiao Ma09b71022018-12-11 17:56:32 +0900139 struct DnsRecord {
140 std::string host_name; // host name
141 ns_type type; // record type
142 std::string addr; // ipv4/v6 address
143 };
144
Hungming Chen5bf09772019-04-25 11:16:13 +0800145 class ResolvDeathRecipient : public android::IBinder::DeathRecipient {
146 public:
147 ~ResolvDeathRecipient() override = default;
Hungming Chene8f970c2019-04-10 17:34:06 +0800148
Hungming Chen5bf09772019-04-25 11:16:13 +0800149 // GTEST assertion macros are not invoked for generating a test failure in the death
150 // recipient because the macros can't indicate failed test if Netd died between tests.
151 // Moreover, continuing testing may have no meaningful after Netd death. Therefore, the
152 // death recipient aborts process by GTEST_LOG_(FATAL) once Netd died.
153 void binderDied(const android::wp<android::IBinder>& /*who*/) override {
Hungming Chen9e6185a2019-06-04 16:09:19 +0800154 constexpr char errorMessage[] = "Netd died";
Hungming Chen5bf09772019-04-25 11:16:13 +0800155 LOG(ERROR) << errorMessage;
156 GTEST_LOG_(FATAL) << errorMessage;
157 }
158 };
Hungming Chene8f970c2019-04-10 17:34:06 +0800159
Hungming Chen5bf09772019-04-25 11:16:13 +0800160 void SetUp() { mDnsClient.SetUp(); }
Hungming Chene8f970c2019-04-10 17:34:06 +0800161 void TearDown() { mDnsClient.TearDown(); }
nuccachena26cc2a2018-07-17 18:07:23 +0800162
Xiao Ma09b71022018-12-11 17:56:32 +0900163 void StartDns(test::DNSResponder& dns, const std::vector<DnsRecord>& records) {
164 for (const auto& r : records) {
165 dns.addMapping(r.host_name, r.type, r.addr);
166 }
167
168 ASSERT_TRUE(dns.startServer());
169 dns.clearQueries();
170 }
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900171
Hungming Chene8f970c2019-04-10 17:34:06 +0800172 bool WaitForNat64Prefix(ExpectNat64PrefixStatus status,
173 std::chrono::milliseconds timeout = std::chrono::milliseconds(1000)) {
Hungming Chen5bf09772019-04-25 11:16:13 +0800174 return sDnsMetricsListener->waitForNat64Prefix(status, timeout);
Hungming Chene8f970c2019-04-10 17:34:06 +0800175 }
176
Mike Yu724f77d2019-08-16 11:14:50 +0800177 bool WaitForPrivateDnsValidation(std::string serverAddr, bool validated) {
178 return sDnsMetricsListener->waitForPrivateDnsValidation(serverAddr, validated);
179 }
180
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900181 DnsResponderClient mDnsClient;
Xiao Ma09b71022018-12-11 17:56:32 +0900182
Hungming Chen5bf09772019-04-25 11:16:13 +0800183 // Use a shared static DNS listener for all tests to avoid registering lots of listeners
184 // which may be released late until process terminated. Currently, registered DNS listener
185 // is removed by binder death notification which is fired when the process hosting an
186 // IBinder has gone away. If every test in ResolverTest registers its DNS listener, Netd
187 // may temporarily hold lots of dead listeners until the unit test process terminates.
188 // TODO: Perhaps add an unregistering listener binder call or fork a listener process which
189 // could be terminated earlier.
190 static android::sp<DnsMetricsListener> sDnsMetricsListener; // Initialized in SetUpTestCase.
191
192 // Use a shared static death recipient to monitor the service death. The static death
193 // recipient could monitor the death not only during the test but also between tests.
194 static android::sp<ResolvDeathRecipient>
195 sResolvDeathRecipient; // Initialized in SetUpTestCase.
Ken Chenb9fa2062018-11-13 21:51:13 +0800196};
197
Hungming Chen5bf09772019-04-25 11:16:13 +0800198// Initialize static member of class.
199android::sp<DnsMetricsListener> ResolverTest::sDnsMetricsListener;
200android::sp<ResolverTest::ResolvDeathRecipient> ResolverTest::sResolvDeathRecipient;
201
Ken Chenb9fa2062018-11-13 21:51:13 +0800202TEST_F(ResolverTest, GetHostByName) {
Xiao Ma09b71022018-12-11 17:56:32 +0900203 constexpr char nonexistent_host_name[] = "nonexistent.example.com.";
204
205 test::DNSResponder dns;
206 StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.3"}});
207 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800208
209 const hostent* result;
Ken Chenb9fa2062018-11-13 21:51:13 +0800210 result = gethostbyname("nonexistent");
211 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, nonexistent_host_name));
212 ASSERT_TRUE(result == nullptr);
213 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
214
215 dns.clearQueries();
216 result = gethostbyname("hello");
Xiao Ma09b71022018-12-11 17:56:32 +0900217 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, kHelloExampleCom));
Ken Chenb9fa2062018-11-13 21:51:13 +0800218 ASSERT_FALSE(result == nullptr);
219 ASSERT_EQ(4, result->h_length);
220 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
221 EXPECT_EQ("1.2.3.3", ToString(result));
222 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800223}
224
lifr4e4a2e02019-01-29 16:53:51 +0800225TEST_F(ResolverTest, GetHostByName_cnames) {
226 constexpr char host_name[] = "host.example.com.";
227 size_t cnamecount = 0;
228 test::DNSResponder dns;
229
230 const std::vector<DnsRecord> records = {
231 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
232 {"a.example.com.", ns_type::ns_t_cname, "b.example.com."},
233 {"b.example.com.", ns_type::ns_t_cname, "c.example.com."},
234 {"c.example.com.", ns_type::ns_t_cname, "d.example.com."},
235 {"d.example.com.", ns_type::ns_t_cname, "e.example.com."},
236 {"e.example.com.", ns_type::ns_t_cname, host_name},
237 {host_name, ns_type::ns_t_a, "1.2.3.3"},
238 {host_name, ns_type::ns_t_aaaa, "2001:db8::42"},
239 };
240 StartDns(dns, records);
241 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
242
243 // using gethostbyname2() to resolve ipv4 hello.example.com. to 1.2.3.3
244 // Ensure the v4 address and cnames are correct
245 const hostent* result;
246 result = gethostbyname2("hello", AF_INET);
247 ASSERT_FALSE(result == nullptr);
248
249 for (int i = 0; result != nullptr && result->h_aliases[i] != nullptr; i++) {
250 std::string domain_name = records[i].host_name.substr(0, records[i].host_name.size() - 1);
251 EXPECT_EQ(result->h_aliases[i], domain_name);
252 cnamecount++;
253 }
254 // The size of "Non-cname type" record in DNS records is 2
255 ASSERT_EQ(cnamecount, records.size() - 2);
256 ASSERT_EQ(4, result->h_length);
257 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
258 EXPECT_EQ("1.2.3.3", ToString(result));
259 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
260 EXPECT_EQ(1U, dns.queries().size()) << dns.dumpQueries();
261
262 // using gethostbyname2() to resolve ipv6 hello.example.com. to 2001:db8::42
263 // Ensure the v6 address and cnames are correct
264 cnamecount = 0;
265 dns.clearQueries();
266 result = gethostbyname2("hello", AF_INET6);
267 for (unsigned i = 0; result != nullptr && result->h_aliases[i] != nullptr; i++) {
268 std::string domain_name = records[i].host_name.substr(0, records[i].host_name.size() - 1);
269 EXPECT_EQ(result->h_aliases[i], domain_name);
270 cnamecount++;
271 }
272 // The size of "Non-cname type" DNS record in records is 2
273 ASSERT_EQ(cnamecount, records.size() - 2);
274 ASSERT_FALSE(result == nullptr);
275 ASSERT_EQ(16, result->h_length);
276 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
277 EXPECT_EQ("2001:db8::42", ToString(result));
278 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
279}
280
281TEST_F(ResolverTest, GetHostByName_cnamesInfiniteLoop) {
282 test::DNSResponder dns;
283 const std::vector<DnsRecord> records = {
284 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
285 {"a.example.com.", ns_type::ns_t_cname, kHelloExampleCom},
286 };
287 StartDns(dns, records);
288 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
289
290 const hostent* result;
291 result = gethostbyname2("hello", AF_INET);
292 ASSERT_TRUE(result == nullptr);
293
294 dns.clearQueries();
295 result = gethostbyname2("hello", AF_INET6);
296 ASSERT_TRUE(result == nullptr);
297}
298
Ken Chenb9fa2062018-11-13 21:51:13 +0800299TEST_F(ResolverTest, GetHostByName_localhost) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800300 constexpr char name_camelcase[] = "LocalHost";
Ken Chenb9fa2062018-11-13 21:51:13 +0800301 constexpr char name_ip6_dot[] = "ip6-localhost.";
302 constexpr char name_ip6_fqdn[] = "ip6-localhost.example.com.";
303
304 // Add a dummy nameserver which shouldn't receive any queries
Xiao Ma09b71022018-12-11 17:56:32 +0900305 test::DNSResponder dns;
306 StartDns(dns, {});
307 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800308
309 // Expect no DNS queries; localhost is resolved via /etc/hosts
Xiao Ma09b71022018-12-11 17:56:32 +0900310 const hostent* result = gethostbyname(kLocalHost);
Ken Chenb9fa2062018-11-13 21:51:13 +0800311 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
312 ASSERT_FALSE(result == nullptr);
313 ASSERT_EQ(4, result->h_length);
314 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
Xiao Ma09b71022018-12-11 17:56:32 +0900315 EXPECT_EQ(kLocalHostAddr, ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +0800316 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
317
318 // Ensure the hosts file resolver ignores case of hostnames
319 result = gethostbyname(name_camelcase);
320 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
321 ASSERT_FALSE(result == nullptr);
322 ASSERT_EQ(4, result->h_length);
323 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
Xiao Ma09b71022018-12-11 17:56:32 +0900324 EXPECT_EQ(kLocalHostAddr, ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +0800325 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
326
327 // The hosts file also contains ip6-localhost, but gethostbyname() won't
chenbruce018fdb22019-06-12 18:08:04 +0800328 // return it. This would be easy to
Ken Chenb9fa2062018-11-13 21:51:13 +0800329 // change, but there's no point in changing the legacy behavior; new code
330 // should be calling getaddrinfo() anyway.
331 // So we check the legacy behavior, which results in amusing A-record
332 // lookups for ip6-localhost, with and without search domains appended.
333 dns.clearQueries();
Xiao Ma09b71022018-12-11 17:56:32 +0900334 result = gethostbyname(kIp6LocalHost);
Sehee Parkbbca0202018-11-16 10:53:16 +0900335 EXPECT_EQ(2U, dns.queries().size()) << dns.dumpQueries();
336 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, name_ip6_dot)) << dns.dumpQueries();
337 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, name_ip6_fqdn)) << dns.dumpQueries();
Ken Chenb9fa2062018-11-13 21:51:13 +0800338 ASSERT_TRUE(result == nullptr);
339
340 // Finally, use gethostbyname2() to resolve ip6-localhost to ::1 from
341 // the hosts file.
342 dns.clearQueries();
Xiao Ma09b71022018-12-11 17:56:32 +0900343 result = gethostbyname2(kIp6LocalHost, AF_INET6);
Ken Chenb9fa2062018-11-13 21:51:13 +0800344 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
345 ASSERT_FALSE(result == nullptr);
346 ASSERT_EQ(16, result->h_length);
347 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
Xiao Ma09b71022018-12-11 17:56:32 +0900348 EXPECT_EQ(kIp6LocalHostAddr, ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +0800349 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800350}
351
352TEST_F(ResolverTest, GetHostByName_numeric) {
353 // Add a dummy nameserver which shouldn't receive any queries
Xiao Ma09b71022018-12-11 17:56:32 +0900354 test::DNSResponder dns;
355 StartDns(dns, {});
356 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800357
358 // Numeric v4 address: expect no DNS queries
359 constexpr char numeric_v4[] = "192.168.0.1";
Ken Chenb9fa2062018-11-13 21:51:13 +0800360 const hostent* result = gethostbyname(numeric_v4);
Sehee Parkbbca0202018-11-16 10:53:16 +0900361 EXPECT_EQ(0U, dns.queries().size());
Ken Chenb9fa2062018-11-13 21:51:13 +0800362 ASSERT_FALSE(result == nullptr);
363 ASSERT_EQ(4, result->h_length); // v4
364 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
365 EXPECT_EQ(numeric_v4, ToString(result));
366 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
367
368 // gethostbyname() recognizes a v6 address, and fails with no DNS queries
369 constexpr char numeric_v6[] = "2001:db8::42";
370 dns.clearQueries();
371 result = gethostbyname(numeric_v6);
Sehee Parkbbca0202018-11-16 10:53:16 +0900372 EXPECT_EQ(0U, dns.queries().size());
Ken Chenb9fa2062018-11-13 21:51:13 +0800373 EXPECT_TRUE(result == nullptr);
374
375 // Numeric v6 address with gethostbyname2(): succeeds with no DNS queries
376 dns.clearQueries();
377 result = gethostbyname2(numeric_v6, AF_INET6);
Sehee Parkbbca0202018-11-16 10:53:16 +0900378 EXPECT_EQ(0U, dns.queries().size());
Ken Chenb9fa2062018-11-13 21:51:13 +0800379 ASSERT_FALSE(result == nullptr);
380 ASSERT_EQ(16, result->h_length); // v6
381 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
382 EXPECT_EQ(numeric_v6, ToString(result));
383 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
384
385 // Numeric v6 address with scope work with getaddrinfo(),
386 // but gethostbyname2() does not understand them; it issues two dns
387 // queries, then fails. This hardly ever happens, there's no point
388 // in fixing this. This test simply verifies the current (bogus)
389 // behavior to avoid further regressions (like crashes, or leaks).
390 constexpr char numeric_v6_scope[] = "fe80::1%lo";
391 dns.clearQueries();
392 result = gethostbyname2(numeric_v6_scope, AF_INET6);
Sehee Parkbbca0202018-11-16 10:53:16 +0900393 EXPECT_EQ(2U, dns.queries().size()); // OUCH!
Ken Chenb9fa2062018-11-13 21:51:13 +0800394 ASSERT_TRUE(result == nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800395}
396
397TEST_F(ResolverTest, BinderSerialization) {
Luke Huang5bd827c2019-03-14 16:10:04 +0800398 using android::net::IDnsResolver;
Ken Chenb9fa2062018-11-13 21:51:13 +0800399 std::vector<int> params_offsets = {
Luke Huang5bd827c2019-03-14 16:10:04 +0800400 IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY,
401 IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD,
402 IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES,
403 IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES,
404 IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC,
405 IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT,
Ken Chenb9fa2062018-11-13 21:51:13 +0800406 };
Bernie Innocentib102dd22018-12-04 14:57:48 +0900407 const int size = static_cast<int>(params_offsets.size());
Luke Huang5bd827c2019-03-14 16:10:04 +0800408 EXPECT_EQ(size, IDnsResolver::RESOLVER_PARAMS_COUNT);
Ken Chenb9fa2062018-11-13 21:51:13 +0800409 std::sort(params_offsets.begin(), params_offsets.end());
Bernie Innocentib102dd22018-12-04 14:57:48 +0900410 for (int i = 0; i < size; ++i) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800411 EXPECT_EQ(params_offsets[i], i);
412 }
413}
414
415TEST_F(ResolverTest, GetHostByName_Binder) {
Luke Huang5bd827c2019-03-14 16:10:04 +0800416 using android::net::IDnsResolver;
Ken Chenb9fa2062018-11-13 21:51:13 +0800417
418 std::vector<std::string> domains = { "example.com" };
419 std::vector<std::unique_ptr<test::DNSResponder>> dns;
420 std::vector<std::string> servers;
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900421 std::vector<DnsResponderClient::Mapping> mappings;
422 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(1, domains, &mappings));
423 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(4, mappings, &dns, &servers));
Ken Chenb9fa2062018-11-13 21:51:13 +0800424 ASSERT_EQ(1U, mappings.size());
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900425 const DnsResponderClient::Mapping& mapping = mappings[0];
Ken Chenb9fa2062018-11-13 21:51:13 +0800426
Xiao Ma09b71022018-12-11 17:56:32 +0900427 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains, kDefaultParams));
Ken Chenb9fa2062018-11-13 21:51:13 +0800428
429 const hostent* result = gethostbyname(mapping.host.c_str());
Bernie Innocentib102dd22018-12-04 14:57:48 +0900430 const size_t total_queries =
Luke Huangfde82482019-06-04 01:04:53 +0800431 std::accumulate(dns.begin(), dns.end(), 0, [&mapping](size_t total, auto& d) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800432 return total + GetNumQueriesForType(*d, ns_type::ns_t_a, mapping.entry.c_str());
433 });
434
435 EXPECT_LE(1U, total_queries);
436 ASSERT_FALSE(result == nullptr);
437 ASSERT_EQ(4, result->h_length);
438 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
439 EXPECT_EQ(mapping.ip4, ToString(result));
440 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
441
442 std::vector<std::string> res_servers;
443 std::vector<std::string> res_domains;
Mike Yu0a1c53d2018-11-26 13:26:21 +0900444 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +0900445 res_params res_params;
Ken Chenb9fa2062018-11-13 21:51:13 +0800446 std::vector<ResolverStats> res_stats;
Ken Chen92bed612018-12-22 21:46:55 +0800447 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +0800448 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
449 &res_tls_servers, &res_params, &res_stats,
450 &wait_for_pending_req_timeout_count));
Ken Chenb9fa2062018-11-13 21:51:13 +0800451 EXPECT_EQ(servers.size(), res_servers.size());
452 EXPECT_EQ(domains.size(), res_domains.size());
Mike Yu0a1c53d2018-11-26 13:26:21 +0900453 EXPECT_EQ(0U, res_tls_servers.size());
Luke Huang5bd827c2019-03-14 16:10:04 +0800454 ASSERT_EQ(static_cast<size_t>(IDnsResolver::RESOLVER_PARAMS_COUNT), kDefaultParams.size());
455 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY],
456 res_params.sample_validity);
457 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD],
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900458 res_params.success_threshold);
Luke Huang5bd827c2019-03-14 16:10:04 +0800459 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES], res_params.min_samples);
460 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES], res_params.max_samples);
461 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
Ken Chenb9fa2062018-11-13 21:51:13 +0800462 res_params.base_timeout_msec);
463 EXPECT_EQ(servers.size(), res_stats.size());
464
Bernie Innocenti0c067e42019-04-01 15:33:16 +0900465 EXPECT_THAT(res_servers, testing::UnorderedElementsAreArray(servers));
466 EXPECT_THAT(res_domains, testing::UnorderedElementsAreArray(domains));
Ken Chenb9fa2062018-11-13 21:51:13 +0800467}
468
469TEST_F(ResolverTest, GetAddrInfo) {
Xiao Ma09b71022018-12-11 17:56:32 +0900470 constexpr char listen_addr[] = "127.0.0.4";
471 constexpr char listen_addr2[] = "127.0.0.5";
472 constexpr char host_name[] = "howdy.example.com.";
Ken Chenb9fa2062018-11-13 21:51:13 +0800473
Xiao Ma09b71022018-12-11 17:56:32 +0900474 const std::vector<DnsRecord> records = {
475 {host_name, ns_type::ns_t_a, "1.2.3.4"},
476 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
477 };
478 test::DNSResponder dns(listen_addr);
479 test::DNSResponder dns2(listen_addr2);
480 StartDns(dns, records);
481 StartDns(dns2, records);
Ken Chenb9fa2062018-11-13 21:51:13 +0800482
Xiao Ma09b71022018-12-11 17:56:32 +0900483 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr}));
Ken Chenb9fa2062018-11-13 21:51:13 +0800484 dns.clearQueries();
485 dns2.clearQueries();
486
487 ScopedAddrinfo result = safe_getaddrinfo("howdy", nullptr, nullptr);
488 EXPECT_TRUE(result != nullptr);
489 size_t found = GetNumQueries(dns, host_name);
490 EXPECT_LE(1U, found);
491 // Could be A or AAAA
492 std::string result_str = ToString(result);
493 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
494 << ", result_str='" << result_str << "'";
495
496 // Verify that the name is cached.
497 size_t old_found = found;
498 result = safe_getaddrinfo("howdy", nullptr, nullptr);
499 EXPECT_TRUE(result != nullptr);
500 found = GetNumQueries(dns, host_name);
501 EXPECT_LE(1U, found);
502 EXPECT_EQ(old_found, found);
503 result_str = ToString(result);
504 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
505 << result_str;
506
507 // Change the DNS resolver, ensure that queries are still cached.
Xiao Ma09b71022018-12-11 17:56:32 +0900508 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr2}));
Ken Chenb9fa2062018-11-13 21:51:13 +0800509 dns.clearQueries();
510 dns2.clearQueries();
511
512 result = safe_getaddrinfo("howdy", nullptr, nullptr);
513 EXPECT_TRUE(result != nullptr);
514 found = GetNumQueries(dns, host_name);
515 size_t found2 = GetNumQueries(dns2, host_name);
516 EXPECT_EQ(0U, found);
517 EXPECT_LE(0U, found2);
518
519 // Could be A or AAAA
520 result_str = ToString(result);
521 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
522 << ", result_str='" << result_str << "'";
Ken Chenb9fa2062018-11-13 21:51:13 +0800523}
524
525TEST_F(ResolverTest, GetAddrInfoV4) {
Xiao Ma09b71022018-12-11 17:56:32 +0900526 test::DNSResponder dns;
527 StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.5"}});
528 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800529
Xiao Ma09b71022018-12-11 17:56:32 +0900530 const addrinfo hints = {.ai_family = AF_INET};
531 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
Ken Chenb9fa2062018-11-13 21:51:13 +0800532 EXPECT_TRUE(result != nullptr);
Xiao Ma09b71022018-12-11 17:56:32 +0900533 EXPECT_EQ(1U, GetNumQueries(dns, kHelloExampleCom));
Ken Chenb9fa2062018-11-13 21:51:13 +0800534 EXPECT_EQ("1.2.3.5", ToString(result));
535}
536
537TEST_F(ResolverTest, GetAddrInfo_localhost) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800538 // Add a dummy nameserver which shouldn't receive any queries
Xiao Ma09b71022018-12-11 17:56:32 +0900539 test::DNSResponder dns;
540 StartDns(dns, {});
541 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800542
Xiao Ma09b71022018-12-11 17:56:32 +0900543 ScopedAddrinfo result = safe_getaddrinfo(kLocalHost, nullptr, nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800544 EXPECT_TRUE(result != nullptr);
545 // Expect no DNS queries; localhost is resolved via /etc/hosts
546 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
Xiao Ma09b71022018-12-11 17:56:32 +0900547 EXPECT_EQ(kLocalHostAddr, ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +0800548
Xiao Ma09b71022018-12-11 17:56:32 +0900549 result = safe_getaddrinfo(kIp6LocalHost, nullptr, nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800550 EXPECT_TRUE(result != nullptr);
551 // Expect no DNS queries; ip6-localhost is resolved via /etc/hosts
552 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
Xiao Ma09b71022018-12-11 17:56:32 +0900553 EXPECT_EQ(kIp6LocalHostAddr, ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +0800554}
555
Luke Huangd8ac4752019-06-18 17:05:47 +0800556TEST_F(ResolverTest, GetAddrInfo_InvalidSocketType) {
557 test::DNSResponder dns;
558 StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.5"}});
559 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
560
561 // TODO: Test other invalid socket types.
562 const addrinfo hints = {
563 .ai_family = AF_UNSPEC,
Luke Huangd8ac4752019-06-18 17:05:47 +0800564 .ai_socktype = SOCK_PACKET,
Nick Desaulnierscd6395a2019-10-11 09:15:24 -0700565 .ai_protocol = ANY,
Luke Huangd8ac4752019-06-18 17:05:47 +0800566 };
567 addrinfo* result = nullptr;
568 // This is a valid hint, but the query won't be sent because the socket type is
569 // not supported.
570 EXPECT_EQ(EAI_NODATA, getaddrinfo("hello", nullptr, &hints, &result));
571 ScopedAddrinfo result_cleanup(result);
572 EXPECT_EQ(nullptr, result);
573}
574
Ken Chen92bed612018-12-22 21:46:55 +0800575// Verify if the resolver correctly handle multiple queries simultaneously
576// step 1: set dns server#1 into deferred responding mode.
577// step 2: thread#1 query "hello.example.com." --> resolver send query to server#1.
578// step 3: thread#2 query "hello.example.com." --> resolver hold the request and wait for
579// response of previous pending query sent by thread#1.
580// step 4: thread#3 query "konbanha.example.com." --> resolver send query to server#3. Server
581// respond to resolver immediately.
582// step 5: check if server#1 get 1 query by thread#1, server#2 get 0 query, server#3 get 1 query.
583// step 6: resume dns server#1 to respond dns query in step#2.
584// step 7: thread#1 and #2 should get returned from DNS query after step#6. Also, check the
585// number of queries in server#2 is 0 to ensure thread#2 does not wake up unexpectedly
586// before signaled by thread#1.
587TEST_F(ResolverTest, GetAddrInfoV4_deferred_resp) {
588 const char* listen_addr1 = "127.0.0.9";
589 const char* listen_addr2 = "127.0.0.10";
590 const char* listen_addr3 = "127.0.0.11";
591 const char* listen_srv = "53";
592 const char* host_name_deferred = "hello.example.com.";
593 const char* host_name_normal = "konbanha.example.com.";
Mike Yufc125e42019-05-15 20:41:28 +0800594 test::DNSResponder dns1(listen_addr1, listen_srv, ns_rcode::ns_r_servfail);
595 test::DNSResponder dns2(listen_addr2, listen_srv, ns_rcode::ns_r_servfail);
596 test::DNSResponder dns3(listen_addr3, listen_srv, ns_rcode::ns_r_servfail);
Ken Chen92bed612018-12-22 21:46:55 +0800597 dns1.addMapping(host_name_deferred, ns_type::ns_t_a, "1.2.3.4");
598 dns2.addMapping(host_name_deferred, ns_type::ns_t_a, "1.2.3.4");
599 dns3.addMapping(host_name_normal, ns_type::ns_t_a, "1.2.3.5");
600 ASSERT_TRUE(dns1.startServer());
601 ASSERT_TRUE(dns2.startServer());
602 ASSERT_TRUE(dns3.startServer());
603 const std::vector<std::string> servers_for_t1 = {listen_addr1};
604 const std::vector<std::string> servers_for_t2 = {listen_addr2};
605 const std::vector<std::string> servers_for_t3 = {listen_addr3};
606 addrinfo hints = {.ai_family = AF_INET};
607 const std::vector<int> params = {300, 25, 8, 8, 5000};
608 bool t3_task_done = false;
609
610 dns1.setDeferredResp(true);
611 std::thread t1([&, this]() {
612 ASSERT_TRUE(
613 mDnsClient.SetResolversForNetwork(servers_for_t1, kDefaultSearchDomains, params));
614 ScopedAddrinfo result = safe_getaddrinfo(host_name_deferred, nullptr, &hints);
615 // t3's dns query should got returned first
616 EXPECT_TRUE(t3_task_done);
617 EXPECT_EQ(1U, GetNumQueries(dns1, host_name_deferred));
618 EXPECT_TRUE(result != nullptr);
619 EXPECT_EQ("1.2.3.4", ToString(result));
620 });
621
622 // ensuring t1 and t2 handler functions are processed in order
623 usleep(100 * 1000);
624 std::thread t2([&, this]() {
625 ASSERT_TRUE(
626 mDnsClient.SetResolversForNetwork(servers_for_t2, kDefaultSearchDomains, params));
627 ScopedAddrinfo result = safe_getaddrinfo(host_name_deferred, nullptr, &hints);
628 EXPECT_TRUE(t3_task_done);
629 EXPECT_EQ(0U, GetNumQueries(dns2, host_name_deferred));
630 EXPECT_TRUE(result != nullptr);
631 EXPECT_EQ("1.2.3.4", ToString(result));
632
633 std::vector<std::string> res_servers;
634 std::vector<std::string> res_domains;
635 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +0900636 res_params res_params;
Ken Chen92bed612018-12-22 21:46:55 +0800637 std::vector<ResolverStats> res_stats;
638 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +0800639 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers,
640 &res_domains, &res_tls_servers, &res_params, &res_stats,
641 &wait_for_pending_req_timeout_count));
Ken Chen92bed612018-12-22 21:46:55 +0800642 EXPECT_EQ(0, wait_for_pending_req_timeout_count);
643 });
644
645 // ensuring t2 and t3 handler functions are processed in order
646 usleep(100 * 1000);
647 std::thread t3([&, this]() {
648 ASSERT_TRUE(
649 mDnsClient.SetResolversForNetwork(servers_for_t3, kDefaultSearchDomains, params));
650 ScopedAddrinfo result = safe_getaddrinfo(host_name_normal, nullptr, &hints);
651 EXPECT_EQ(1U, GetNumQueries(dns1, host_name_deferred));
652 EXPECT_EQ(0U, GetNumQueries(dns2, host_name_deferred));
653 EXPECT_EQ(1U, GetNumQueries(dns3, host_name_normal));
654 EXPECT_TRUE(result != nullptr);
655 EXPECT_EQ("1.2.3.5", ToString(result));
656
657 t3_task_done = true;
658 dns1.setDeferredResp(false);
659 });
660 t3.join();
661 t1.join();
662 t2.join();
663}
664
lifr4e4a2e02019-01-29 16:53:51 +0800665TEST_F(ResolverTest, GetAddrInfo_cnames) {
666 constexpr char host_name[] = "host.example.com.";
667 test::DNSResponder dns;
668 const std::vector<DnsRecord> records = {
669 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
670 {"a.example.com.", ns_type::ns_t_cname, "b.example.com."},
671 {"b.example.com.", ns_type::ns_t_cname, "c.example.com."},
672 {"c.example.com.", ns_type::ns_t_cname, "d.example.com."},
673 {"d.example.com.", ns_type::ns_t_cname, "e.example.com."},
674 {"e.example.com.", ns_type::ns_t_cname, host_name},
675 {host_name, ns_type::ns_t_a, "1.2.3.3"},
676 {host_name, ns_type::ns_t_aaaa, "2001:db8::42"},
677 };
678 StartDns(dns, records);
679 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
680
681 addrinfo hints = {.ai_family = AF_INET};
682 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
683 EXPECT_TRUE(result != nullptr);
684 EXPECT_EQ("1.2.3.3", ToString(result));
685
686 dns.clearQueries();
687 hints = {.ai_family = AF_INET6};
688 result = safe_getaddrinfo("hello", nullptr, &hints);
689 EXPECT_TRUE(result != nullptr);
690 EXPECT_EQ("2001:db8::42", ToString(result));
691}
692
693TEST_F(ResolverTest, GetAddrInfo_cnamesNoIpAddress) {
694 test::DNSResponder dns;
695 const std::vector<DnsRecord> records = {
696 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
697 };
698 StartDns(dns, records);
699 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
700
701 addrinfo hints = {.ai_family = AF_INET};
702 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
703 EXPECT_TRUE(result == nullptr);
704
705 dns.clearQueries();
706 hints = {.ai_family = AF_INET6};
707 result = safe_getaddrinfo("hello", nullptr, &hints);
708 EXPECT_TRUE(result == nullptr);
709}
710
711TEST_F(ResolverTest, GetAddrInfo_cnamesIllegalRdata) {
712 test::DNSResponder dns;
713 const std::vector<DnsRecord> records = {
714 {kHelloExampleCom, ns_type::ns_t_cname, ".!#?"},
715 };
716 StartDns(dns, records);
717 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
718
719 addrinfo hints = {.ai_family = AF_INET};
720 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
721 EXPECT_TRUE(result == nullptr);
722
723 dns.clearQueries();
724 hints = {.ai_family = AF_INET6};
725 result = safe_getaddrinfo("hello", nullptr, &hints);
726 EXPECT_TRUE(result == nullptr);
727}
728
Ken Chenb9fa2062018-11-13 21:51:13 +0800729TEST_F(ResolverTest, MultidomainResolution) {
Xiao Ma09b71022018-12-11 17:56:32 +0900730 constexpr char host_name[] = "nihao.example2.com.";
Ken Chenb9fa2062018-11-13 21:51:13 +0800731 std::vector<std::string> searchDomains = { "example1.com", "example2.com", "example3.com" };
Ken Chenb9fa2062018-11-13 21:51:13 +0800732
Xiao Ma09b71022018-12-11 17:56:32 +0900733 test::DNSResponder dns("127.0.0.6");
734 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.3"}});
735 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({"127.0.0.6"}, searchDomains));
736
Ken Chenb9fa2062018-11-13 21:51:13 +0800737 const hostent* result = gethostbyname("nihao");
Xiao Ma09b71022018-12-11 17:56:32 +0900738
Ken Chenb9fa2062018-11-13 21:51:13 +0800739 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
740 ASSERT_FALSE(result == nullptr);
741 ASSERT_EQ(4, result->h_length);
742 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
743 EXPECT_EQ("1.2.3.3", ToString(result));
744 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800745}
746
747TEST_F(ResolverTest, GetAddrInfoV6_numeric) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800748 constexpr char host_name[] = "ohayou.example.com.";
749 constexpr char numeric_addr[] = "fe80::1%lo";
750
Xiao Ma09b71022018-12-11 17:56:32 +0900751 test::DNSResponder dns;
Ken Chenb9fa2062018-11-13 21:51:13 +0800752 dns.setResponseProbability(0.0);
Xiao Ma09b71022018-12-11 17:56:32 +0900753 StartDns(dns, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
754 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800755
756 addrinfo hints = {.ai_family = AF_INET6};
757 ScopedAddrinfo result = safe_getaddrinfo(numeric_addr, nullptr, &hints);
758 EXPECT_TRUE(result != nullptr);
759 EXPECT_EQ(numeric_addr, ToString(result));
760 EXPECT_TRUE(dns.queries().empty()); // Ensure no DNS queries were sent out
761
762 // Now try a non-numeric hostname query with the AI_NUMERICHOST flag set.
763 // We should fail without sending out a DNS query.
764 hints.ai_flags |= AI_NUMERICHOST;
765 result = safe_getaddrinfo(host_name, nullptr, &hints);
766 EXPECT_TRUE(result == nullptr);
767 EXPECT_TRUE(dns.queries().empty()); // Ensure no DNS queries were sent out
768}
769
770TEST_F(ResolverTest, GetAddrInfoV6_failing) {
Xiao Ma09b71022018-12-11 17:56:32 +0900771 constexpr char listen_addr0[] = "127.0.0.7";
772 constexpr char listen_addr1[] = "127.0.0.8";
Ken Chenb9fa2062018-11-13 21:51:13 +0800773 const char* host_name = "ohayou.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +0900774
775 test::DNSResponder dns0(listen_addr0);
776 test::DNSResponder dns1(listen_addr1);
Ken Chenb9fa2062018-11-13 21:51:13 +0800777 dns0.setResponseProbability(0.0);
Xiao Ma09b71022018-12-11 17:56:32 +0900778 StartDns(dns0, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
779 StartDns(dns1, {{host_name, ns_type::ns_t_aaaa, "2001:db8::6"}});
780
Ken Chenb9fa2062018-11-13 21:51:13 +0800781 std::vector<std::string> servers = { listen_addr0, listen_addr1 };
782 // <sample validity in s> <success threshold in percent> <min samples> <max samples>
783 int sample_count = 8;
784 const std::vector<int> params = { 300, 25, sample_count, sample_count };
Xiao Ma09b71022018-12-11 17:56:32 +0900785 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, kDefaultSearchDomains, params));
Ken Chenb9fa2062018-11-13 21:51:13 +0800786
787 // Repeatedly perform resolutions for non-existing domains until MAXNSSAMPLES resolutions have
788 // reached the dns0, which is set to fail. No more requests should then arrive at that server
789 // for the next sample_lifetime seconds.
790 // TODO: This approach is implementation-dependent, change once metrics reporting is available.
Xiao Ma09b71022018-12-11 17:56:32 +0900791 const addrinfo hints = {.ai_family = AF_INET6};
Bernie Innocentib102dd22018-12-04 14:57:48 +0900792 for (int i = 0; i < sample_count; ++i) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800793 std::string domain = StringPrintf("nonexistent%d", i);
794 ScopedAddrinfo result = safe_getaddrinfo(domain.c_str(), nullptr, &hints);
795 }
796 // Due to 100% errors for all possible samples, the server should be ignored from now on and
797 // only the second one used for all following queries, until NSSAMPLE_VALIDITY is reached.
798 dns0.clearQueries();
799 dns1.clearQueries();
800 ScopedAddrinfo result = safe_getaddrinfo("ohayou", nullptr, &hints);
801 EXPECT_TRUE(result != nullptr);
802 EXPECT_EQ(0U, GetNumQueries(dns0, host_name));
803 EXPECT_EQ(1U, GetNumQueries(dns1, host_name));
804}
805
806TEST_F(ResolverTest, GetAddrInfoV6_nonresponsive) {
Xiao Ma09b71022018-12-11 17:56:32 +0900807 constexpr char listen_addr0[] = "127.0.0.7";
808 constexpr char listen_addr1[] = "127.0.0.8";
809 constexpr char listen_srv[] = "53";
810 constexpr char host_name1[] = "ohayou.example.com.";
811 constexpr char host_name2[] = "ciao.example.com.";
Luke Huang483cf332019-06-03 17:24:51 +0800812 const std::vector<std::string> defaultSearchDomain = {"example.com"};
813 // The minimal timeout is 1000ms, so we can't decrease timeout
814 // So reduce retry count.
815 const std::vector<int> reduceRetryParams = {
816 300, // sample validity in seconds
817 25, // success threshod in percent
818 8, 8, // {MIN,MAX}_SAMPLES
819 1000, // BASE_TIMEOUT_MSEC
820 1, // retry count
821 };
Xiao Ma09b71022018-12-11 17:56:32 +0900822 const std::vector<DnsRecord> records0 = {
823 {host_name1, ns_type::ns_t_aaaa, "2001:db8::5"},
824 {host_name2, ns_type::ns_t_aaaa, "2001:db8::5"},
825 };
826 const std::vector<DnsRecord> records1 = {
827 {host_name1, ns_type::ns_t_aaaa, "2001:db8::6"},
828 {host_name2, ns_type::ns_t_aaaa, "2001:db8::6"},
829 };
Ken Chenb9fa2062018-11-13 21:51:13 +0800830
831 // dns0 does not respond with 100% probability, while
832 // dns1 responds normally, at least initially.
Mike Yufc125e42019-05-15 20:41:28 +0800833 test::DNSResponder dns0(listen_addr0, listen_srv, static_cast<ns_rcode>(-1));
834 test::DNSResponder dns1(listen_addr1, listen_srv, static_cast<ns_rcode>(-1));
Ken Chenb9fa2062018-11-13 21:51:13 +0800835 dns0.setResponseProbability(0.0);
Xiao Ma09b71022018-12-11 17:56:32 +0900836 StartDns(dns0, records0);
837 StartDns(dns1, records1);
Luke Huang483cf332019-06-03 17:24:51 +0800838 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr0, listen_addr1}, defaultSearchDomain,
839 reduceRetryParams));
Ken Chenb9fa2062018-11-13 21:51:13 +0800840
Luke Huang483cf332019-06-03 17:24:51 +0800841 // Specify ai_socktype to make getaddrinfo will only query 1 time
842 const addrinfo hints = {.ai_family = AF_INET6, .ai_socktype = SOCK_STREAM};
Ken Chenb9fa2062018-11-13 21:51:13 +0800843
844 // dns0 will ignore the request, and we'll fallback to dns1 after the first
845 // retry.
846 ScopedAddrinfo result = safe_getaddrinfo(host_name1, nullptr, &hints);
847 EXPECT_TRUE(result != nullptr);
848 EXPECT_EQ(1U, GetNumQueries(dns0, host_name1));
849 EXPECT_EQ(1U, GetNumQueries(dns1, host_name1));
850
851 // Now make dns1 also ignore 100% requests... The resolve should alternate
Luke Huang483cf332019-06-03 17:24:51 +0800852 // queries between the nameservers and fail
Ken Chenb9fa2062018-11-13 21:51:13 +0800853 dns1.setResponseProbability(0.0);
854 addrinfo* result2 = nullptr;
855 EXPECT_EQ(EAI_NODATA, getaddrinfo(host_name2, nullptr, &hints, &result2));
856 EXPECT_EQ(nullptr, result2);
Luke Huang483cf332019-06-03 17:24:51 +0800857 EXPECT_EQ(1U, GetNumQueries(dns0, host_name2));
858 EXPECT_EQ(1U, GetNumQueries(dns1, host_name2));
Ken Chenb9fa2062018-11-13 21:51:13 +0800859}
860
861TEST_F(ResolverTest, GetAddrInfoV6_concurrent) {
Xiao Ma09b71022018-12-11 17:56:32 +0900862 constexpr char listen_addr0[] = "127.0.0.9";
863 constexpr char listen_addr1[] = "127.0.0.10";
864 constexpr char listen_addr2[] = "127.0.0.11";
865 constexpr char host_name[] = "konbanha.example.com.";
866
867 test::DNSResponder dns0(listen_addr0);
868 test::DNSResponder dns1(listen_addr1);
869 test::DNSResponder dns2(listen_addr2);
870 StartDns(dns0, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
871 StartDns(dns1, {{host_name, ns_type::ns_t_aaaa, "2001:db8::6"}});
872 StartDns(dns2, {{host_name, ns_type::ns_t_aaaa, "2001:db8::7"}});
873
Ken Chenb9fa2062018-11-13 21:51:13 +0800874 const std::vector<std::string> servers = { listen_addr0, listen_addr1, listen_addr2 };
875 std::vector<std::thread> threads(10);
876 for (std::thread& thread : threads) {
877 thread = std::thread([this, &servers]() {
878 unsigned delay = arc4random_uniform(1*1000*1000); // <= 1s
879 usleep(delay);
880 std::vector<std::string> serverSubset;
881 for (const auto& server : servers) {
882 if (arc4random_uniform(2)) {
883 serverSubset.push_back(server);
884 }
885 }
886 if (serverSubset.empty()) serverSubset = servers;
Xiao Ma09b71022018-12-11 17:56:32 +0900887 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(serverSubset));
888 const addrinfo hints = {.ai_family = AF_INET6};
Ken Chenb9fa2062018-11-13 21:51:13 +0800889 addrinfo* result = nullptr;
890 int rv = getaddrinfo("konbanha", nullptr, &hints, &result);
891 EXPECT_EQ(0, rv) << "error [" << rv << "] " << gai_strerror(rv);
892 if (result) {
893 freeaddrinfo(result);
894 result = nullptr;
895 }
896 });
897 }
898 for (std::thread& thread : threads) {
899 thread.join();
900 }
Ken Chen92bed612018-12-22 21:46:55 +0800901
902 std::vector<std::string> res_servers;
903 std::vector<std::string> res_domains;
904 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +0900905 res_params res_params;
Ken Chen92bed612018-12-22 21:46:55 +0800906 std::vector<ResolverStats> res_stats;
907 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +0800908 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
909 &res_tls_servers, &res_params, &res_stats,
910 &wait_for_pending_req_timeout_count));
Ken Chen92bed612018-12-22 21:46:55 +0800911 EXPECT_EQ(0, wait_for_pending_req_timeout_count);
Ken Chenb9fa2062018-11-13 21:51:13 +0800912}
913
Ken Chenb9fa2062018-11-13 21:51:13 +0800914TEST_F(ResolverTest, EmptySetup) {
Luke Huang5bd827c2019-03-14 16:10:04 +0800915 using android::net::IDnsResolver;
Ken Chenb9fa2062018-11-13 21:51:13 +0800916 std::vector<std::string> servers;
917 std::vector<std::string> domains;
Xiao Ma09b71022018-12-11 17:56:32 +0900918 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
Ken Chenb9fa2062018-11-13 21:51:13 +0800919 std::vector<std::string> res_servers;
920 std::vector<std::string> res_domains;
Mike Yu0a1c53d2018-11-26 13:26:21 +0900921 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +0900922 res_params res_params;
Ken Chenb9fa2062018-11-13 21:51:13 +0800923 std::vector<ResolverStats> res_stats;
Ken Chen92bed612018-12-22 21:46:55 +0800924 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +0800925 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
926 &res_tls_servers, &res_params, &res_stats,
927 &wait_for_pending_req_timeout_count));
Ken Chenb9fa2062018-11-13 21:51:13 +0800928 EXPECT_EQ(0U, res_servers.size());
929 EXPECT_EQ(0U, res_domains.size());
Mike Yu0a1c53d2018-11-26 13:26:21 +0900930 EXPECT_EQ(0U, res_tls_servers.size());
Luke Huang5bd827c2019-03-14 16:10:04 +0800931 ASSERT_EQ(static_cast<size_t>(IDnsResolver::RESOLVER_PARAMS_COUNT), kDefaultParams.size());
932 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY],
933 res_params.sample_validity);
934 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD],
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900935 res_params.success_threshold);
Luke Huang5bd827c2019-03-14 16:10:04 +0800936 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES], res_params.min_samples);
937 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES], res_params.max_samples);
938 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
Ken Chenb9fa2062018-11-13 21:51:13 +0800939 res_params.base_timeout_msec);
Luke Huang5bd827c2019-03-14 16:10:04 +0800940 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT], res_params.retry_count);
Ken Chenb9fa2062018-11-13 21:51:13 +0800941}
942
943TEST_F(ResolverTest, SearchPathChange) {
Xiao Ma09b71022018-12-11 17:56:32 +0900944 constexpr char listen_addr[] = "127.0.0.13";
945 constexpr char host_name1[] = "test13.domain1.org.";
946 constexpr char host_name2[] = "test13.domain2.org.";
Ken Chenb9fa2062018-11-13 21:51:13 +0800947 std::vector<std::string> servers = { listen_addr };
948 std::vector<std::string> domains = { "domain1.org" };
Xiao Ma09b71022018-12-11 17:56:32 +0900949
950 const std::vector<DnsRecord> records = {
951 {host_name1, ns_type::ns_t_aaaa, "2001:db8::13"},
952 {host_name2, ns_type::ns_t_aaaa, "2001:db8::1:13"},
953 };
954 test::DNSResponder dns(listen_addr);
955 StartDns(dns, records);
956 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
Ken Chenb9fa2062018-11-13 21:51:13 +0800957
958 const addrinfo hints = {.ai_family = AF_INET6};
959 ScopedAddrinfo result = safe_getaddrinfo("test13", nullptr, &hints);
960 EXPECT_TRUE(result != nullptr);
961 EXPECT_EQ(1U, dns.queries().size());
962 EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
963 EXPECT_EQ("2001:db8::13", ToString(result));
964
965 // Test that changing the domain search path on its own works.
966 domains = { "domain2.org" };
Xiao Ma09b71022018-12-11 17:56:32 +0900967 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
Ken Chenb9fa2062018-11-13 21:51:13 +0800968 dns.clearQueries();
969
970 result = safe_getaddrinfo("test13", nullptr, &hints);
971 EXPECT_TRUE(result != nullptr);
972 EXPECT_EQ(1U, dns.queries().size());
973 EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
974 EXPECT_EQ("2001:db8::1:13", ToString(result));
975}
976
Luke Huang2dac4382019-06-24 13:28:44 +0800977namespace {
978
979std::vector<std::string> getResolverDomains(android::net::IDnsResolver* dnsResolverService,
980 unsigned netId) {
981 std::vector<std::string> res_servers;
982 std::vector<std::string> res_domains;
983 std::vector<std::string> res_tls_servers;
984 res_params res_params;
985 std::vector<ResolverStats> res_stats;
986 int wait_for_pending_req_timeout_count;
987 GetResolverInfo(dnsResolverService, netId, &res_servers, &res_domains, &res_tls_servers,
988 &res_params, &res_stats, &wait_for_pending_req_timeout_count);
989 return res_domains;
990}
991
992} // namespace
993
994TEST_F(ResolverTest, SearchPathPrune) {
995 constexpr size_t DUPLICATED_DOMAIN_NUM = 3;
996 constexpr char listen_addr[] = "127.0.0.13";
997 constexpr char domian_name1[] = "domain13.org.";
998 constexpr char domian_name2[] = "domain14.org.";
999 constexpr char host_name1[] = "test13.domain13.org.";
1000 constexpr char host_name2[] = "test14.domain14.org.";
1001 std::vector<std::string> servers = {listen_addr};
1002
1003 std::vector<std::string> testDomains1;
1004 std::vector<std::string> testDomains2;
1005 // Domain length should be <= 255
1006 // Max number of domains in search path is 6
1007 for (size_t i = 0; i < MAXDNSRCH + 1; i++) {
1008 // Fill up with invalid domain
1009 testDomains1.push_back(std::string(300, i + '0'));
1010 // Fill up with valid but duplicated domain
1011 testDomains2.push_back(StringPrintf("domain%zu.org", i % DUPLICATED_DOMAIN_NUM));
1012 }
1013
1014 // Add valid domain used for query.
1015 testDomains1.push_back(domian_name1);
1016
1017 // Add valid domain twice used for query.
1018 testDomains2.push_back(domian_name2);
1019 testDomains2.push_back(domian_name2);
1020
1021 const std::vector<DnsRecord> records = {
1022 {host_name1, ns_type::ns_t_aaaa, "2001:db8::13"},
1023 {host_name2, ns_type::ns_t_aaaa, "2001:db8::1:13"},
1024 };
1025 test::DNSResponder dns(listen_addr);
1026 StartDns(dns, records);
1027 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, testDomains1));
1028
1029 const addrinfo hints = {.ai_family = AF_INET6};
1030 ScopedAddrinfo result = safe_getaddrinfo("test13", nullptr, &hints);
1031
1032 EXPECT_TRUE(result != nullptr);
1033
1034 EXPECT_EQ(1U, dns.queries().size());
1035 EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
1036 EXPECT_EQ("2001:db8::13", ToString(result));
1037
1038 const auto& res_domains1 = getResolverDomains(mDnsClient.resolvService(), TEST_NETID);
1039 // Expect 1 valid domain, invalid domains are removed.
1040 ASSERT_EQ(1U, res_domains1.size());
1041 EXPECT_EQ(domian_name1, res_domains1[0]);
1042
1043 dns.clearQueries();
1044
1045 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, testDomains2));
1046
1047 result = safe_getaddrinfo("test14", nullptr, &hints);
1048 EXPECT_TRUE(result != nullptr);
1049
1050 // (3 domains * 2 retries) + 1 success query = 7
1051 EXPECT_EQ(7U, dns.queries().size());
1052 EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
1053 EXPECT_EQ("2001:db8::1:13", ToString(result));
1054
1055 const auto& res_domains2 = getResolverDomains(mDnsClient.resolvService(), TEST_NETID);
1056 // Expect 4 valid domain, duplicate domains are removed.
1057 EXPECT_EQ(DUPLICATED_DOMAIN_NUM + 1U, res_domains2.size());
1058 EXPECT_THAT(
1059 std::vector<std::string>({"domain0.org", "domain1.org", "domain2.org", domian_name2}),
1060 testing::ElementsAreArray(res_domains2));
1061}
1062
Mike Yu0a1c53d2018-11-26 13:26:21 +09001063// If we move this function to dns_responder_client, it will complicate the dependency need of
1064// dns_tls_frontend.h.
1065static void setupTlsServers(const std::vector<std::string>& servers,
waynema0e73c2e2019-07-31 15:04:08 +08001066 std::vector<std::unique_ptr<test::DnsTlsFrontend>>* tls) {
Xiao Ma09b71022018-12-11 17:56:32 +09001067 constexpr char listen_udp[] = "53";
1068 constexpr char listen_tls[] = "853";
Mike Yu0a1c53d2018-11-26 13:26:21 +09001069
1070 for (const auto& server : servers) {
1071 auto t = std::make_unique<test::DnsTlsFrontend>(server, listen_tls, server, listen_udp);
1072 t = std::make_unique<test::DnsTlsFrontend>(server, listen_tls, server, listen_udp);
1073 t->startServer();
Mike Yu0a1c53d2018-11-26 13:26:21 +09001074 tls->push_back(std::move(t));
1075 }
1076}
1077
Mike Yu0a1c53d2018-11-26 13:26:21 +09001078TEST_F(ResolverTest, MaxServerPrune_Binder) {
Mike Yu0a1c53d2018-11-26 13:26:21 +09001079 std::vector<std::string> domains;
1080 std::vector<std::unique_ptr<test::DNSResponder>> dns;
1081 std::vector<std::unique_ptr<test::DnsTlsFrontend>> tls;
1082 std::vector<std::string> servers;
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001083 std::vector<DnsResponderClient::Mapping> mappings;
Mike Yu0a1c53d2018-11-26 13:26:21 +09001084
1085 for (unsigned i = 0; i < MAXDNSRCH + 1; i++) {
1086 domains.push_back(StringPrintf("example%u.com", i));
1087 }
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001088 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(1, domains, &mappings));
1089 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(MAXNS + 1, mappings, &dns, &servers));
waynema0e73c2e2019-07-31 15:04:08 +08001090 ASSERT_NO_FATAL_FAILURE(setupTlsServers(servers, &tls));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001091
waynema0e73c2e2019-07-31 15:04:08 +08001092 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, domains, kDefaultParams,
1093 kDefaultPrivateDnsHostName));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001094
Mike Yu383855b2019-01-15 17:53:27 +08001095 // If the private DNS validation hasn't completed yet before backend DNS servers stop,
1096 // TLS servers will get stuck in handleOneRequest(), which causes this test stuck in
1097 // ~DnsTlsFrontend() because the TLS server loop threads can't be terminated.
1098 // So, wait for private DNS validation done before stopping backend DNS servers.
1099 for (int i = 0; i < MAXNS; i++) {
chenbruceaff85842019-05-31 15:46:42 +08001100 LOG(INFO) << "Waiting for private DNS validation on " << tls[i]->listen_address() << ".";
Mike Yu724f77d2019-08-16 11:14:50 +08001101 EXPECT_TRUE(WaitForPrivateDnsValidation(tls[i]->listen_address(), true));
chenbruceaff85842019-05-31 15:46:42 +08001102 LOG(INFO) << "private DNS validation on " << tls[i]->listen_address() << " done.";
Mike Yu383855b2019-01-15 17:53:27 +08001103 }
1104
Mike Yu0a1c53d2018-11-26 13:26:21 +09001105 std::vector<std::string> res_servers;
1106 std::vector<std::string> res_domains;
1107 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +09001108 res_params res_params;
Mike Yu0a1c53d2018-11-26 13:26:21 +09001109 std::vector<ResolverStats> res_stats;
Ken Chen92bed612018-12-22 21:46:55 +08001110 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +08001111 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
1112 &res_tls_servers, &res_params, &res_stats,
1113 &wait_for_pending_req_timeout_count));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001114
1115 // Check the size of the stats and its contents.
1116 EXPECT_EQ(static_cast<size_t>(MAXNS), res_servers.size());
1117 EXPECT_EQ(static_cast<size_t>(MAXNS), res_tls_servers.size());
1118 EXPECT_EQ(static_cast<size_t>(MAXDNSRCH), res_domains.size());
1119 EXPECT_TRUE(std::equal(servers.begin(), servers.begin() + MAXNS, res_servers.begin()));
1120 EXPECT_TRUE(std::equal(servers.begin(), servers.begin() + MAXNS, res_tls_servers.begin()));
1121 EXPECT_TRUE(std::equal(domains.begin(), domains.begin() + MAXDNSRCH, res_domains.begin()));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001122}
1123
1124TEST_F(ResolverTest, ResolverStats) {
Xiao Ma09b71022018-12-11 17:56:32 +09001125 constexpr char listen_addr1[] = "127.0.0.4";
1126 constexpr char listen_addr2[] = "127.0.0.5";
1127 constexpr char listen_addr3[] = "127.0.0.6";
Mike Yu0a1c53d2018-11-26 13:26:21 +09001128
1129 // Set server 1 timeout.
Mike Yufc125e42019-05-15 20:41:28 +08001130 test::DNSResponder dns1(listen_addr1, "53", static_cast<ns_rcode>(-1));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001131 dns1.setResponseProbability(0.0);
1132 ASSERT_TRUE(dns1.startServer());
1133
1134 // Set server 2 responding server failure.
Xiao Ma09b71022018-12-11 17:56:32 +09001135 test::DNSResponder dns2(listen_addr2);
Mike Yu0a1c53d2018-11-26 13:26:21 +09001136 dns2.setResponseProbability(0.0);
1137 ASSERT_TRUE(dns2.startServer());
1138
1139 // Set server 3 workable.
Xiao Ma09b71022018-12-11 17:56:32 +09001140 test::DNSResponder dns3(listen_addr3);
1141 dns3.addMapping(kHelloExampleCom, ns_type::ns_t_a, "1.2.3.4");
Mike Yu0a1c53d2018-11-26 13:26:21 +09001142 ASSERT_TRUE(dns3.startServer());
1143
1144 std::vector<std::string> servers = {listen_addr1, listen_addr2, listen_addr3};
Xiao Ma09b71022018-12-11 17:56:32 +09001145 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001146
1147 dns3.clearQueries();
Xiao Ma09b71022018-12-11 17:56:32 +09001148 const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
Mike Yu0a1c53d2018-11-26 13:26:21 +09001149 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
Xiao Ma09b71022018-12-11 17:56:32 +09001150 size_t found = GetNumQueries(dns3, kHelloExampleCom);
Mike Yu0a1c53d2018-11-26 13:26:21 +09001151 EXPECT_LE(1U, found);
1152 std::string result_str = ToString(result);
1153 EXPECT_TRUE(result_str == "1.2.3.4") << ", result_str='" << result_str << "'";
1154
1155 std::vector<std::string> res_servers;
1156 std::vector<std::string> res_domains;
1157 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +09001158 res_params res_params;
Mike Yu0a1c53d2018-11-26 13:26:21 +09001159 std::vector<ResolverStats> res_stats;
Ken Chen92bed612018-12-22 21:46:55 +08001160 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +08001161 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
1162 &res_tls_servers, &res_params, &res_stats,
1163 &wait_for_pending_req_timeout_count));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001164
1165 EXPECT_EQ(1, res_stats[0].timeouts);
1166 EXPECT_EQ(1, res_stats[1].errors);
1167 EXPECT_EQ(1, res_stats[2].successes);
Mike Yu0a1c53d2018-11-26 13:26:21 +09001168}
1169
Ken Chenb9fa2062018-11-13 21:51:13 +08001170// Test what happens if the specified TLS server is nonexistent.
1171TEST_F(ResolverTest, GetHostByName_TlsMissing) {
Xiao Ma09b71022018-12-11 17:56:32 +09001172 constexpr char listen_addr[] = "127.0.0.3";
1173 constexpr char host_name[] = "tlsmissing.example.com.";
1174
1175 test::DNSResponder dns;
1176 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.3"}});
Ken Chenb9fa2062018-11-13 21:51:13 +08001177 std::vector<std::string> servers = { listen_addr };
1178
1179 // There's nothing listening on this address, so validation will either fail or
1180 /// hang. Either way, queries will continue to flow to the DNSResponder.
waynema0e73c2e2019-07-31 15:04:08 +08001181 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
Ken Chenb9fa2062018-11-13 21:51:13 +08001182
1183 const hostent* result;
1184
1185 result = gethostbyname("tlsmissing");
1186 ASSERT_FALSE(result == nullptr);
1187 EXPECT_EQ("1.2.3.3", ToString(result));
1188
1189 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001190 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001191}
1192
1193// Test what happens if the specified TLS server replies with garbage.
1194TEST_F(ResolverTest, GetHostByName_TlsBroken) {
Xiao Ma09b71022018-12-11 17:56:32 +09001195 constexpr char listen_addr[] = "127.0.0.3";
1196 constexpr char host_name1[] = "tlsbroken1.example.com.";
1197 constexpr char host_name2[] = "tlsbroken2.example.com.";
1198 const std::vector<DnsRecord> records = {
1199 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1200 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1201 };
1202
1203 test::DNSResponder dns;
1204 StartDns(dns, records);
Ken Chenb9fa2062018-11-13 21:51:13 +08001205 std::vector<std::string> servers = { listen_addr };
1206
1207 // Bind the specified private DNS socket but don't respond to any client sockets yet.
1208 int s = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP);
1209 ASSERT_TRUE(s >= 0);
1210 struct sockaddr_in tlsServer = {
1211 .sin_family = AF_INET,
1212 .sin_port = htons(853),
1213 };
1214 ASSERT_TRUE(inet_pton(AF_INET, listen_addr, &tlsServer.sin_addr));
1215 ASSERT_TRUE(enableSockopt(s, SOL_SOCKET, SO_REUSEPORT).ok());
1216 ASSERT_TRUE(enableSockopt(s, SOL_SOCKET, SO_REUSEADDR).ok());
1217 ASSERT_FALSE(bind(s, reinterpret_cast<struct sockaddr*>(&tlsServer), sizeof(tlsServer)));
1218 ASSERT_FALSE(listen(s, 1));
1219
1220 // Trigger TLS validation.
waynema0e73c2e2019-07-31 15:04:08 +08001221 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
Ken Chenb9fa2062018-11-13 21:51:13 +08001222
1223 struct sockaddr_storage cliaddr;
1224 socklen_t sin_size = sizeof(cliaddr);
1225 int new_fd = accept4(s, reinterpret_cast<struct sockaddr *>(&cliaddr), &sin_size, SOCK_CLOEXEC);
1226 ASSERT_TRUE(new_fd > 0);
1227
1228 // We've received the new file descriptor but not written to it or closed, so the
1229 // validation is still pending. Queries should still flow correctly because the
1230 // server is not used until validation succeeds.
1231 const hostent* result;
1232 result = gethostbyname("tlsbroken1");
1233 ASSERT_FALSE(result == nullptr);
1234 EXPECT_EQ("1.2.3.1", ToString(result));
1235
1236 // Now we cause the validation to fail.
1237 std::string garbage = "definitely not a valid TLS ServerHello";
1238 write(new_fd, garbage.data(), garbage.size());
1239 close(new_fd);
1240
1241 // Validation failure shouldn't interfere with lookups, because lookups won't be sent
1242 // to the TLS server unless validation succeeds.
1243 result = gethostbyname("tlsbroken2");
1244 ASSERT_FALSE(result == nullptr);
1245 EXPECT_EQ("1.2.3.2", ToString(result));
1246
1247 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001248 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001249 close(s);
1250}
1251
1252TEST_F(ResolverTest, GetHostByName_Tls) {
Xiao Ma09b71022018-12-11 17:56:32 +09001253 constexpr char listen_addr[] = "127.0.0.3";
1254 constexpr char listen_udp[] = "53";
1255 constexpr char listen_tls[] = "853";
1256 constexpr char host_name1[] = "tls1.example.com.";
1257 constexpr char host_name2[] = "tls2.example.com.";
1258 constexpr char host_name3[] = "tls3.example.com.";
1259 const std::vector<DnsRecord> records = {
1260 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1261 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1262 {host_name3, ns_type::ns_t_a, "1.2.3.3"},
1263 };
1264
1265 test::DNSResponder dns;
1266 StartDns(dns, records);
Ken Chenb9fa2062018-11-13 21:51:13 +08001267 std::vector<std::string> servers = { listen_addr };
1268
1269 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1270 ASSERT_TRUE(tls.startServer());
waynema0e73c2e2019-07-31 15:04:08 +08001271 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
Mike Yu724f77d2019-08-16 11:14:50 +08001272 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
Ken Chenb9fa2062018-11-13 21:51:13 +08001273
Mike Yu724f77d2019-08-16 11:14:50 +08001274 const hostent* result = gethostbyname("tls1");
Ken Chenb9fa2062018-11-13 21:51:13 +08001275 ASSERT_FALSE(result == nullptr);
1276 EXPECT_EQ("1.2.3.1", ToString(result));
1277
1278 // Wait for query to get counted.
1279 EXPECT_TRUE(tls.waitForQueries(2, 5000));
1280
1281 // Stop the TLS server. Since we're in opportunistic mode, queries will
1282 // fall back to the locally-assigned (clear text) nameservers.
1283 tls.stopServer();
1284
1285 dns.clearQueries();
1286 result = gethostbyname("tls2");
1287 EXPECT_FALSE(result == nullptr);
1288 EXPECT_EQ("1.2.3.2", ToString(result));
1289 const auto queries = dns.queries();
1290 EXPECT_EQ(1U, queries.size());
1291 EXPECT_EQ("tls2.example.com.", queries[0].first);
1292 EXPECT_EQ(ns_t_a, queries[0].second);
1293
1294 // Reset the resolvers without enabling TLS. Queries should still be routed
1295 // to the UDP endpoint.
Xiao Ma09b71022018-12-11 17:56:32 +09001296 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001297
1298 result = gethostbyname("tls3");
1299 ASSERT_FALSE(result == nullptr);
1300 EXPECT_EQ("1.2.3.3", ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +08001301}
1302
Ken Chenb9fa2062018-11-13 21:51:13 +08001303TEST_F(ResolverTest, GetHostByName_TlsFailover) {
Xiao Ma09b71022018-12-11 17:56:32 +09001304 constexpr char listen_addr1[] = "127.0.0.3";
1305 constexpr char listen_addr2[] = "127.0.0.4";
1306 constexpr char listen_udp[] = "53";
1307 constexpr char listen_tls[] = "853";
1308 constexpr char host_name1[] = "tlsfailover1.example.com.";
1309 constexpr char host_name2[] = "tlsfailover2.example.com.";
1310 const std::vector<DnsRecord> records1 = {
1311 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1312 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1313 };
1314 const std::vector<DnsRecord> records2 = {
1315 {host_name1, ns_type::ns_t_a, "1.2.3.3"},
1316 {host_name2, ns_type::ns_t_a, "1.2.3.4"},
1317 };
1318
1319 test::DNSResponder dns1(listen_addr1);
1320 test::DNSResponder dns2(listen_addr2);
1321 StartDns(dns1, records1);
1322 StartDns(dns2, records2);
1323
Ken Chenb9fa2062018-11-13 21:51:13 +08001324 std::vector<std::string> servers = { listen_addr1, listen_addr2 };
1325
1326 test::DnsTlsFrontend tls1(listen_addr1, listen_tls, listen_addr1, listen_udp);
1327 test::DnsTlsFrontend tls2(listen_addr2, listen_tls, listen_addr2, listen_udp);
1328 ASSERT_TRUE(tls1.startServer());
1329 ASSERT_TRUE(tls2.startServer());
waynema0e73c2e2019-07-31 15:04:08 +08001330 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
1331 kDefaultPrivateDnsHostName));
Mike Yu724f77d2019-08-16 11:14:50 +08001332 EXPECT_TRUE(WaitForPrivateDnsValidation(tls1.listen_address(), true));
1333 EXPECT_TRUE(WaitForPrivateDnsValidation(tls2.listen_address(), true));
Ken Chenb9fa2062018-11-13 21:51:13 +08001334
Mike Yu724f77d2019-08-16 11:14:50 +08001335 const hostent* result = gethostbyname("tlsfailover1");
Ken Chenb9fa2062018-11-13 21:51:13 +08001336 ASSERT_FALSE(result == nullptr);
1337 EXPECT_EQ("1.2.3.1", ToString(result));
1338
1339 // Wait for query to get counted.
1340 EXPECT_TRUE(tls1.waitForQueries(2, 5000));
1341 // No new queries should have reached tls2.
1342 EXPECT_EQ(1, tls2.queries());
1343
1344 // Stop tls1. Subsequent queries should attempt to reach tls1, fail, and retry to tls2.
1345 tls1.stopServer();
1346
1347 result = gethostbyname("tlsfailover2");
1348 EXPECT_EQ("1.2.3.4", ToString(result));
1349
1350 // Wait for query to get counted.
1351 EXPECT_TRUE(tls2.waitForQueries(2, 5000));
1352
1353 // No additional queries should have reached the insecure servers.
1354 EXPECT_EQ(2U, dns1.queries().size());
1355 EXPECT_EQ(2U, dns2.queries().size());
1356
1357 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001358 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Ken Chenb9fa2062018-11-13 21:51:13 +08001359}
1360
1361TEST_F(ResolverTest, GetHostByName_BadTlsName) {
Xiao Ma09b71022018-12-11 17:56:32 +09001362 constexpr char listen_addr[] = "127.0.0.3";
1363 constexpr char listen_udp[] = "53";
1364 constexpr char listen_tls[] = "853";
1365 constexpr char host_name[] = "badtlsname.example.com.";
1366
1367 test::DNSResponder dns;
1368 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.1"}});
Ken Chenb9fa2062018-11-13 21:51:13 +08001369 std::vector<std::string> servers = { listen_addr };
1370
1371 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1372 ASSERT_TRUE(tls.startServer());
Xiao Ma09b71022018-12-11 17:56:32 +09001373 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
waynema0e73c2e2019-07-31 15:04:08 +08001374 kDefaultIncorrectPrivateDnsHostName));
Ken Chenb9fa2062018-11-13 21:51:13 +08001375
waynema0e73c2e2019-07-31 15:04:08 +08001376 // The TLS handshake would fail because the name of TLS server doesn't
1377 // match with TLS server's certificate.
Mike Yu724f77d2019-08-16 11:14:50 +08001378 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), false));
Ken Chenb9fa2062018-11-13 21:51:13 +08001379
1380 // The query should fail hard, because a name was specified.
1381 EXPECT_EQ(nullptr, gethostbyname("badtlsname"));
1382
1383 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001384 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001385}
1386
1387TEST_F(ResolverTest, GetAddrInfo_Tls) {
Xiao Ma09b71022018-12-11 17:56:32 +09001388 constexpr char listen_addr[] = "127.0.0.3";
1389 constexpr char listen_udp[] = "53";
1390 constexpr char listen_tls[] = "853";
1391 constexpr char host_name[] = "addrinfotls.example.com.";
1392 const std::vector<DnsRecord> records = {
1393 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1394 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1395 };
1396
1397 test::DNSResponder dns;
1398 StartDns(dns, records);
Ken Chenb9fa2062018-11-13 21:51:13 +08001399 std::vector<std::string> servers = { listen_addr };
1400
1401 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1402 ASSERT_TRUE(tls.startServer());
waynema0e73c2e2019-07-31 15:04:08 +08001403 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
1404 kDefaultPrivateDnsHostName));
Mike Yu724f77d2019-08-16 11:14:50 +08001405 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
Ken Chenb9fa2062018-11-13 21:51:13 +08001406
1407 dns.clearQueries();
1408 ScopedAddrinfo result = safe_getaddrinfo("addrinfotls", nullptr, nullptr);
1409 EXPECT_TRUE(result != nullptr);
1410 size_t found = GetNumQueries(dns, host_name);
1411 EXPECT_LE(1U, found);
1412 // Could be A or AAAA
1413 std::string result_str = ToString(result);
1414 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
1415 << ", result_str='" << result_str << "'";
1416 // Wait for both A and AAAA queries to get counted.
1417 EXPECT_TRUE(tls.waitForQueries(3, 5000));
1418
1419 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001420 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001421}
1422
1423TEST_F(ResolverTest, TlsBypass) {
1424 const char OFF[] = "off";
1425 const char OPPORTUNISTIC[] = "opportunistic";
1426 const char STRICT[] = "strict";
1427
1428 const char GETHOSTBYNAME[] = "gethostbyname";
1429 const char GETADDRINFO[] = "getaddrinfo";
1430 const char GETADDRINFOFORNET[] = "getaddrinfofornet";
1431
1432 const unsigned BYPASS_NETID = NETID_USE_LOCAL_NAMESERVERS | TEST_NETID;
1433
Ken Chenb9fa2062018-11-13 21:51:13 +08001434 const char ADDR4[] = "192.0.2.1";
1435 const char ADDR6[] = "2001:db8::1";
1436
1437 const char cleartext_addr[] = "127.0.0.53";
1438 const char cleartext_port[] = "53";
1439 const char tls_port[] = "853";
1440 const std::vector<std::string> servers = { cleartext_addr };
1441
Xiao Ma09b71022018-12-11 17:56:32 +09001442 test::DNSResponder dns(cleartext_addr);
Ken Chenb9fa2062018-11-13 21:51:13 +08001443 ASSERT_TRUE(dns.startServer());
1444
1445 test::DnsTlsFrontend tls(cleartext_addr, tls_port, cleartext_addr, cleartext_port);
Mike Yudd4ac2d2019-05-31 16:52:11 +08001446 ASSERT_TRUE(tls.startServer());
Ken Chenb9fa2062018-11-13 21:51:13 +08001447
1448 struct TestConfig {
1449 const std::string mode;
1450 const bool withWorkingTLS;
1451 const std::string method;
1452
1453 std::string asHostName() const {
1454 return StringPrintf("%s.%s.%s.",
1455 mode.c_str(),
1456 withWorkingTLS ? "tlsOn" : "tlsOff",
1457 method.c_str());
1458 }
1459 } testConfigs[]{
Ken Chenb9fa2062018-11-13 21:51:13 +08001460 {OFF, true, GETHOSTBYNAME},
1461 {OPPORTUNISTIC, true, GETHOSTBYNAME},
1462 {STRICT, true, GETHOSTBYNAME},
Ken Chenb9fa2062018-11-13 21:51:13 +08001463 {OFF, true, GETADDRINFO},
1464 {OPPORTUNISTIC, true, GETADDRINFO},
1465 {STRICT, true, GETADDRINFO},
Ken Chenb9fa2062018-11-13 21:51:13 +08001466 {OFF, true, GETADDRINFOFORNET},
1467 {OPPORTUNISTIC, true, GETADDRINFOFORNET},
1468 {STRICT, true, GETADDRINFOFORNET},
Mike Yudd4ac2d2019-05-31 16:52:11 +08001469 {OFF, false, GETHOSTBYNAME},
1470 {OPPORTUNISTIC, false, GETHOSTBYNAME},
1471 {STRICT, false, GETHOSTBYNAME},
1472 {OFF, false, GETADDRINFO},
1473 {OPPORTUNISTIC, false, GETADDRINFO},
1474 {STRICT, false, GETADDRINFO},
1475 {OFF, false, GETADDRINFOFORNET},
1476 {OPPORTUNISTIC, false, GETADDRINFOFORNET},
1477 {STRICT, false, GETADDRINFOFORNET},
Ken Chenb9fa2062018-11-13 21:51:13 +08001478 };
1479
1480 for (const auto& config : testConfigs) {
1481 const std::string testHostName = config.asHostName();
1482 SCOPED_TRACE(testHostName);
1483
1484 // Don't tempt test bugs due to caching.
1485 const char* host_name = testHostName.c_str();
1486 dns.addMapping(host_name, ns_type::ns_t_a, ADDR4);
1487 dns.addMapping(host_name, ns_type::ns_t_aaaa, ADDR6);
1488
Mike Yudd4ac2d2019-05-31 16:52:11 +08001489 if (config.withWorkingTLS) {
1490 if (!tls.running()) {
1491 ASSERT_TRUE(tls.startServer());
1492 }
1493 } else {
1494 if (tls.running()) {
1495 ASSERT_TRUE(tls.stopServer());
1496 }
1497 }
Ken Chenb9fa2062018-11-13 21:51:13 +08001498
1499 if (config.mode == OFF) {
Xiao Ma09b71022018-12-11 17:56:32 +09001500 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, kDefaultSearchDomains,
1501 kDefaultParams));
Ken Chenb9fa2062018-11-13 21:51:13 +08001502 } else if (config.mode == OPPORTUNISTIC) {
Xiao Ma09b71022018-12-11 17:56:32 +09001503 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
waynema0e73c2e2019-07-31 15:04:08 +08001504 kDefaultParams, ""));
Mike Yu724f77d2019-08-16 11:14:50 +08001505
1506 // Wait for the validation event. If the server is running, the validation should
1507 // be successful; otherwise, the validation should be failed.
1508 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), config.withWorkingTLS));
Ken Chenb9fa2062018-11-13 21:51:13 +08001509 } else if (config.mode == STRICT) {
Xiao Ma09b71022018-12-11 17:56:32 +09001510 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
waynema0e73c2e2019-07-31 15:04:08 +08001511 kDefaultParams, kDefaultPrivateDnsHostName));
Mike Yu724f77d2019-08-16 11:14:50 +08001512
1513 // Wait for the validation event.
1514 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), config.withWorkingTLS));
Ken Chenb9fa2062018-11-13 21:51:13 +08001515 }
Mike Yudd4ac2d2019-05-31 16:52:11 +08001516 tls.clearQueries();
Ken Chenb9fa2062018-11-13 21:51:13 +08001517
1518 const hostent* h_result = nullptr;
1519 ScopedAddrinfo ai_result;
1520
1521 if (config.method == GETHOSTBYNAME) {
1522 ASSERT_EQ(0, setNetworkForResolv(BYPASS_NETID));
1523 h_result = gethostbyname(host_name);
1524
1525 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
1526 ASSERT_FALSE(h_result == nullptr);
1527 ASSERT_EQ(4, h_result->h_length);
1528 ASSERT_FALSE(h_result->h_addr_list[0] == nullptr);
1529 EXPECT_EQ(ADDR4, ToString(h_result));
1530 EXPECT_TRUE(h_result->h_addr_list[1] == nullptr);
1531 } else if (config.method == GETADDRINFO) {
1532 ASSERT_EQ(0, setNetworkForResolv(BYPASS_NETID));
1533 ai_result = safe_getaddrinfo(host_name, nullptr, nullptr);
1534 EXPECT_TRUE(ai_result != nullptr);
1535
1536 EXPECT_LE(1U, GetNumQueries(dns, host_name));
1537 // Could be A or AAAA
1538 const std::string result_str = ToString(ai_result);
1539 EXPECT_TRUE(result_str == ADDR4 || result_str == ADDR6)
1540 << ", result_str='" << result_str << "'";
1541 } else if (config.method == GETADDRINFOFORNET) {
1542 addrinfo* raw_ai_result = nullptr;
1543 EXPECT_EQ(0, android_getaddrinfofornet(host_name, /*servname=*/nullptr,
1544 /*hints=*/nullptr, BYPASS_NETID, MARK_UNSET,
1545 &raw_ai_result));
1546 ai_result.reset(raw_ai_result);
1547
1548 EXPECT_LE(1U, GetNumQueries(dns, host_name));
1549 // Could be A or AAAA
1550 const std::string result_str = ToString(ai_result);
1551 EXPECT_TRUE(result_str == ADDR4 || result_str == ADDR6)
1552 << ", result_str='" << result_str << "'";
Ken Chenb9fa2062018-11-13 21:51:13 +08001553 }
1554
Mike Yudd4ac2d2019-05-31 16:52:11 +08001555 EXPECT_EQ(0, tls.queries());
Ken Chenb9fa2062018-11-13 21:51:13 +08001556
1557 // Clear per-process resolv netid.
1558 ASSERT_EQ(0, setNetworkForResolv(NETID_UNSET));
Ken Chenb9fa2062018-11-13 21:51:13 +08001559 dns.clearQueries();
1560 }
Ken Chenb9fa2062018-11-13 21:51:13 +08001561}
1562
1563TEST_F(ResolverTest, StrictMode_NoTlsServers) {
Xiao Ma09b71022018-12-11 17:56:32 +09001564 constexpr char cleartext_addr[] = "127.0.0.53";
Ken Chenb9fa2062018-11-13 21:51:13 +08001565 const std::vector<std::string> servers = { cleartext_addr };
Xiao Ma09b71022018-12-11 17:56:32 +09001566 constexpr char host_name[] = "strictmode.notlsips.example.com.";
1567 const std::vector<DnsRecord> records = {
1568 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1569 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1570 };
Ken Chenb9fa2062018-11-13 21:51:13 +08001571
Xiao Ma09b71022018-12-11 17:56:32 +09001572 test::DNSResponder dns(cleartext_addr);
1573 StartDns(dns, records);
Ken Chenb9fa2062018-11-13 21:51:13 +08001574
waynema0e73c2e2019-07-31 15:04:08 +08001575 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
1576 kDefaultIncorrectPrivateDnsHostName));
Ken Chenb9fa2062018-11-13 21:51:13 +08001577
1578 addrinfo* ai_result = nullptr;
1579 EXPECT_NE(0, getaddrinfo(host_name, nullptr, nullptr, &ai_result));
1580 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
1581}
Luke Huang94b10b92018-11-21 20:13:38 +08001582
1583namespace {
1584
Luke Huang70931aa2019-01-31 11:57:41 +08001585int getAsyncResponse(int fd, int* rcode, uint8_t* buf, int bufLen) {
Luke Huang94b10b92018-11-21 20:13:38 +08001586 struct pollfd wait_fd[1];
1587 wait_fd[0].fd = fd;
1588 wait_fd[0].events = POLLIN;
1589 short revents;
1590 int ret;
1591
1592 ret = poll(wait_fd, 1, -1);
1593 revents = wait_fd[0].revents;
1594 if (revents & POLLIN) {
1595 int n = resNetworkResult(fd, rcode, buf, bufLen);
Luke Huangba7bef92018-12-26 16:53:03 +08001596 // Verify that resNetworkResult() closed the fd
1597 char dummy;
1598 EXPECT_EQ(-1, read(fd, &dummy, sizeof dummy));
1599 EXPECT_EQ(EBADF, errno);
Luke Huang94b10b92018-11-21 20:13:38 +08001600 return n;
1601 }
1602 return -1;
1603}
1604
Luke Huang70931aa2019-01-31 11:57:41 +08001605std::string toString(uint8_t* buf, int bufLen, int ipType) {
Luke Huang94b10b92018-11-21 20:13:38 +08001606 ns_msg handle;
1607 int ancount, n = 0;
1608 ns_rr rr;
1609
1610 if (ns_initparse((const uint8_t*) buf, bufLen, &handle) >= 0) {
1611 ancount = ns_msg_count(handle, ns_s_an);
1612 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
Luke Huang70931aa2019-01-31 11:57:41 +08001613 const uint8_t* rdata = ns_rr_rdata(rr);
Luke Huang94b10b92018-11-21 20:13:38 +08001614 char buffer[INET6_ADDRSTRLEN];
1615 if (inet_ntop(ipType, (const char*) rdata, buffer, sizeof(buffer))) {
1616 return buffer;
1617 }
1618 }
1619 }
1620 return "";
1621}
1622
1623int dns_open_proxy() {
1624 int s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
1625 if (s == -1) {
1626 return -1;
1627 }
1628 const int one = 1;
1629 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
1630
1631 static const struct sockaddr_un proxy_addr = {
1632 .sun_family = AF_UNIX,
1633 .sun_path = "/dev/socket/dnsproxyd",
1634 };
1635
1636 if (TEMP_FAILURE_RETRY(connect(s, (const struct sockaddr*) &proxy_addr, sizeof(proxy_addr))) !=
1637 0) {
1638 close(s);
1639 return -1;
1640 }
1641
1642 return s;
1643}
1644
Luke Huangba7bef92018-12-26 16:53:03 +08001645void expectAnswersValid(int fd, int ipType, const std::string& expectedAnswer) {
1646 int rcode = -1;
1647 uint8_t buf[MAXPACKET] = {};
1648
1649 int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
1650 EXPECT_GT(res, 0);
1651 EXPECT_EQ(expectedAnswer, toString(buf, res, ipType));
1652}
1653
1654void expectAnswersNotValid(int fd, int expectedErrno) {
1655 int rcode = -1;
1656 uint8_t buf[MAXPACKET] = {};
1657
1658 int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
1659 EXPECT_EQ(expectedErrno, res);
1660}
1661
Luke Huang94b10b92018-11-21 20:13:38 +08001662} // namespace
1663
1664TEST_F(ResolverTest, Async_NormalQueryV4V6) {
Xiao Ma09b71022018-12-11 17:56:32 +09001665 constexpr char listen_addr[] = "127.0.0.4";
1666 constexpr char host_name[] = "howdy.example.com.";
1667 const std::vector<DnsRecord> records = {
1668 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1669 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1670 };
1671
1672 test::DNSResponder dns(listen_addr);
1673 StartDns(dns, records);
Luke Huang94b10b92018-11-21 20:13:38 +08001674 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09001675 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huang94b10b92018-11-21 20:13:38 +08001676
Luke Huangba7bef92018-12-26 16:53:03 +08001677 int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1678 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001679 EXPECT_TRUE(fd1 != -1);
1680 EXPECT_TRUE(fd2 != -1);
1681
Luke Huang70931aa2019-01-31 11:57:41 +08001682 uint8_t buf[MAXPACKET] = {};
Luke Huang94b10b92018-11-21 20:13:38 +08001683 int rcode;
1684 int res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
1685 EXPECT_GT(res, 0);
1686 EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
1687
1688 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
1689 EXPECT_GT(res, 0);
1690 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
1691
1692 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
1693
1694 // Re-query verify cache works
Luke Huangba7bef92018-12-26 16:53:03 +08001695 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1696 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001697
1698 EXPECT_TRUE(fd1 != -1);
1699 EXPECT_TRUE(fd2 != -1);
1700
1701 res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
1702 EXPECT_GT(res, 0);
1703 EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
1704
1705 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
1706 EXPECT_GT(res, 0);
1707 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
1708
1709 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
1710}
1711
1712TEST_F(ResolverTest, Async_BadQuery) {
Xiao Ma09b71022018-12-11 17:56:32 +09001713 constexpr char listen_addr[] = "127.0.0.4";
1714 constexpr char host_name[] = "howdy.example.com.";
1715 const std::vector<DnsRecord> records = {
1716 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1717 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1718 };
1719
1720 test::DNSResponder dns(listen_addr);
1721 StartDns(dns, records);
Luke Huang94b10b92018-11-21 20:13:38 +08001722 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09001723 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huang94b10b92018-11-21 20:13:38 +08001724
1725 static struct {
1726 int fd;
1727 const char* dname;
1728 const int queryType;
1729 const int expectRcode;
1730 } kTestData[] = {
Luke Huangba7bef92018-12-26 16:53:03 +08001731 {-1, "", ns_t_aaaa, 0},
1732 {-1, "as65ass46", ns_t_aaaa, 0},
1733 {-1, "454564564564", ns_t_aaaa, 0},
1734 {-1, "h645235", ns_t_a, 0},
1735 {-1, "www.google.com", ns_t_a, 0},
Luke Huang94b10b92018-11-21 20:13:38 +08001736 };
1737
1738 for (auto& td : kTestData) {
1739 SCOPED_TRACE(td.dname);
Luke Huangba7bef92018-12-26 16:53:03 +08001740 td.fd = resNetworkQuery(TEST_NETID, td.dname, ns_c_in, td.queryType, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001741 EXPECT_TRUE(td.fd != -1);
1742 }
1743
1744 // dns_responder return empty resp(packet only contains query part) with no error currently
1745 for (const auto& td : kTestData) {
Luke Huang70931aa2019-01-31 11:57:41 +08001746 uint8_t buf[MAXPACKET] = {};
Luke Huang94b10b92018-11-21 20:13:38 +08001747 int rcode;
1748 SCOPED_TRACE(td.dname);
1749 int res = getAsyncResponse(td.fd, &rcode, buf, MAXPACKET);
1750 EXPECT_GT(res, 0);
1751 EXPECT_EQ(rcode, td.expectRcode);
1752 }
1753}
1754
1755TEST_F(ResolverTest, Async_EmptyAnswer) {
Xiao Ma09b71022018-12-11 17:56:32 +09001756 constexpr char listen_addr[] = "127.0.0.4";
1757 constexpr char host_name[] = "howdy.example.com.";
1758 const std::vector<DnsRecord> records = {
1759 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1760 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1761 };
1762
1763 test::DNSResponder dns(listen_addr);
1764 StartDns(dns, records);
Luke Huang94b10b92018-11-21 20:13:38 +08001765 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09001766 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huang94b10b92018-11-21 20:13:38 +08001767
Luke Huang9c264bb2018-12-18 16:44:41 +08001768 // TODO: Disable retry to make this test explicit.
1769 auto& cv = dns.getCv();
1770 auto& cvMutex = dns.getCvMutex();
1771 int fd1;
1772 // Wait on the condition variable to ensure that the DNS server has handled our first query.
1773 {
1774 std::unique_lock lk(cvMutex);
Luke Huangba7bef92018-12-26 16:53:03 +08001775 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
Luke Huang9c264bb2018-12-18 16:44:41 +08001776 EXPECT_TRUE(fd1 != -1);
1777 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lk, std::chrono::seconds(1)));
1778 }
Luke Huang94b10b92018-11-21 20:13:38 +08001779
Luke Huang94b10b92018-11-21 20:13:38 +08001780 dns.setResponseProbability(0.0);
Luke Huang94b10b92018-11-21 20:13:38 +08001781
Luke Huangba7bef92018-12-26 16:53:03 +08001782 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001783 EXPECT_TRUE(fd2 != -1);
1784
Luke Huangba7bef92018-12-26 16:53:03 +08001785 int fd3 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001786 EXPECT_TRUE(fd3 != -1);
1787
Luke Huang9c264bb2018-12-18 16:44:41 +08001788 uint8_t buf[MAXPACKET] = {};
Luke Huang94b10b92018-11-21 20:13:38 +08001789 int rcode;
1790
Luke Huang9c264bb2018-12-18 16:44:41 +08001791 // expect no response
1792 int res = getAsyncResponse(fd3, &rcode, buf, MAXPACKET);
1793 EXPECT_EQ(-ETIMEDOUT, res);
Luke Huang94b10b92018-11-21 20:13:38 +08001794
Luke Huang9c264bb2018-12-18 16:44:41 +08001795 // expect no response
Luke Huang94b10b92018-11-21 20:13:38 +08001796 memset(buf, 0, MAXPACKET);
Luke Huang9c264bb2018-12-18 16:44:41 +08001797 res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
1798 EXPECT_EQ(-ETIMEDOUT, res);
Luke Huang94b10b92018-11-21 20:13:38 +08001799
Luke Huang94b10b92018-11-21 20:13:38 +08001800 dns.setResponseProbability(1.0);
Luke Huang94b10b92018-11-21 20:13:38 +08001801
Luke Huangba7bef92018-12-26 16:53:03 +08001802 int fd4 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001803 EXPECT_TRUE(fd4 != -1);
1804
1805 memset(buf, 0, MAXPACKET);
1806 res = getAsyncResponse(fd4, &rcode, buf, MAXPACKET);
1807 EXPECT_GT(res, 0);
1808 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
1809
1810 memset(buf, 0, MAXPACKET);
1811 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
1812 EXPECT_GT(res, 0);
1813 EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
1814}
1815
1816TEST_F(ResolverTest, Async_MalformedQuery) {
Xiao Ma09b71022018-12-11 17:56:32 +09001817 constexpr char listen_addr[] = "127.0.0.4";
1818 constexpr char host_name[] = "howdy.example.com.";
1819 const std::vector<DnsRecord> records = {
1820 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1821 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1822 };
1823
1824 test::DNSResponder dns(listen_addr);
1825 StartDns(dns, records);
Luke Huang94b10b92018-11-21 20:13:38 +08001826 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09001827 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huang94b10b92018-11-21 20:13:38 +08001828
1829 int fd = dns_open_proxy();
1830 EXPECT_TRUE(fd > 0);
1831
1832 const std::string badMsg = "16-52512#";
Xiao Ma09b71022018-12-11 17:56:32 +09001833 static const struct {
Luke Huang94b10b92018-11-21 20:13:38 +08001834 const std::string cmd;
1835 const int expectErr;
1836 } kTestData[] = {
Luke Huangba7bef92018-12-26 16:53:03 +08001837 // Too few arguments
Luke Huang94b10b92018-11-21 20:13:38 +08001838 {"resnsend " + badMsg + '\0', -EINVAL},
1839 // Bad netId
Luke Huangba7bef92018-12-26 16:53:03 +08001840 {"resnsend badnetId 0 " + badMsg + '\0', -EINVAL},
Luke Huang94b10b92018-11-21 20:13:38 +08001841 // Bad raw data
Luke Huangba7bef92018-12-26 16:53:03 +08001842 {"resnsend " + std::to_string(TEST_NETID) + " 0 " + badMsg + '\0', -EILSEQ},
Luke Huang94b10b92018-11-21 20:13:38 +08001843 };
1844
1845 for (unsigned int i = 0; i < std::size(kTestData); i++) {
1846 auto& td = kTestData[i];
1847 SCOPED_TRACE(td.cmd);
1848 ssize_t rc = TEMP_FAILURE_RETRY(write(fd, td.cmd.c_str(), td.cmd.size()));
1849 EXPECT_EQ(rc, static_cast<ssize_t>(td.cmd.size()));
1850
1851 int32_t tmp;
1852 rc = TEMP_FAILURE_RETRY(read(fd, &tmp, sizeof(tmp)));
1853 EXPECT_TRUE(rc > 0);
1854 EXPECT_EQ(static_cast<int>(ntohl(tmp)), td.expectErr);
1855 }
1856 // Normal query with answer buffer
1857 // This is raw data of query "howdy.example.com" type 1 class 1
1858 std::string query = "81sBAAABAAAAAAAABWhvd2R5B2V4YW1wbGUDY29tAAABAAE=";
Luke Huangba7bef92018-12-26 16:53:03 +08001859 std::string cmd = "resnsend " + std::to_string(TEST_NETID) + " 0 " + query + '\0';
Luke Huang94b10b92018-11-21 20:13:38 +08001860 ssize_t rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
1861 EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
1862
Luke Huang70931aa2019-01-31 11:57:41 +08001863 uint8_t smallBuf[1] = {};
Luke Huang94b10b92018-11-21 20:13:38 +08001864 int rcode;
1865 rc = getAsyncResponse(fd, &rcode, smallBuf, 1);
Luke Huangba7bef92018-12-26 16:53:03 +08001866 EXPECT_EQ(-EMSGSIZE, rc);
Luke Huang94b10b92018-11-21 20:13:38 +08001867
1868 // Do the normal test with large buffer again
1869 fd = dns_open_proxy();
1870 EXPECT_TRUE(fd > 0);
1871 rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
1872 EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
Luke Huang70931aa2019-01-31 11:57:41 +08001873 uint8_t buf[MAXPACKET] = {};
Luke Huang94b10b92018-11-21 20:13:38 +08001874 rc = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
1875 EXPECT_EQ("1.2.3.4", toString(buf, rc, AF_INET));
Mike Yu4f3747b2018-12-02 17:54:29 +09001876}
1877
Luke Huangba7bef92018-12-26 16:53:03 +08001878TEST_F(ResolverTest, Async_CacheFlags) {
Xiao Ma09b71022018-12-11 17:56:32 +09001879 constexpr char listen_addr[] = "127.0.0.4";
1880 constexpr char host_name[] = "howdy.example.com.";
Luke Huang40f5f492019-05-09 19:37:35 +08001881 constexpr char another_host_name[] = "howdy.example2.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09001882 const std::vector<DnsRecord> records = {
1883 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1884 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
Luke Huang40f5f492019-05-09 19:37:35 +08001885 {another_host_name, ns_type::ns_t_a, "1.2.3.5"},
1886 {another_host_name, ns_type::ns_t_aaaa, "::1.2.3.5"},
Xiao Ma09b71022018-12-11 17:56:32 +09001887 };
1888
1889 test::DNSResponder dns(listen_addr);
1890 StartDns(dns, records);
Luke Huangba7bef92018-12-26 16:53:03 +08001891 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09001892 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huangba7bef92018-12-26 16:53:03 +08001893
1894 // ANDROID_RESOLV_NO_CACHE_STORE
1895 int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1896 ANDROID_RESOLV_NO_CACHE_STORE);
1897 EXPECT_TRUE(fd1 != -1);
1898 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1899 ANDROID_RESOLV_NO_CACHE_STORE);
1900 EXPECT_TRUE(fd2 != -1);
1901 int fd3 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1902 ANDROID_RESOLV_NO_CACHE_STORE);
1903 EXPECT_TRUE(fd3 != -1);
1904
1905 expectAnswersValid(fd3, AF_INET, "1.2.3.4");
1906 expectAnswersValid(fd2, AF_INET, "1.2.3.4");
1907 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
1908
1909 // No cache exists, expect 3 queries
1910 EXPECT_EQ(3U, GetNumQueries(dns, host_name));
1911
1912 // Re-query and cache
1913 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1914
1915 EXPECT_TRUE(fd1 != -1);
1916
1917 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
1918
1919 // Now we have cache, expect 4 queries
1920 EXPECT_EQ(4U, GetNumQueries(dns, host_name));
1921
1922 // ANDROID_RESOLV_NO_CACHE_LOOKUP
1923 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1924 ANDROID_RESOLV_NO_CACHE_LOOKUP);
1925 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1926 ANDROID_RESOLV_NO_CACHE_LOOKUP);
1927
1928 EXPECT_TRUE(fd1 != -1);
1929 EXPECT_TRUE(fd2 != -1);
1930
1931 expectAnswersValid(fd2, AF_INET, "1.2.3.4");
1932 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
1933
1934 // Skip cache, expect 6 queries
1935 EXPECT_EQ(6U, GetNumQueries(dns, host_name));
1936
1937 // Re-query verify cache works
1938 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1939 ANDROID_RESOLV_NO_CACHE_STORE);
1940 EXPECT_TRUE(fd1 != -1);
1941 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
1942
1943 // Cache hits, expect still 6 queries
1944 EXPECT_EQ(6U, GetNumQueries(dns, host_name));
Luke Huanga1d74182019-03-19 17:30:36 +08001945
1946 // Start to verify if ANDROID_RESOLV_NO_CACHE_LOOKUP does write response into cache
1947 dns.clearQueries();
1948
1949 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa,
1950 ANDROID_RESOLV_NO_CACHE_LOOKUP);
1951 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa,
1952 ANDROID_RESOLV_NO_CACHE_LOOKUP);
1953
1954 EXPECT_TRUE(fd1 != -1);
1955 EXPECT_TRUE(fd2 != -1);
1956
1957 expectAnswersValid(fd2, AF_INET6, "::1.2.3.4");
1958 expectAnswersValid(fd1, AF_INET6, "::1.2.3.4");
1959
1960 // Skip cache, expect 2 queries
1961 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
1962
1963 // Re-query without flags
1964 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
1965 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
1966
1967 EXPECT_TRUE(fd1 != -1);
1968 EXPECT_TRUE(fd2 != -1);
1969
1970 expectAnswersValid(fd2, AF_INET6, "::1.2.3.4");
1971 expectAnswersValid(fd1, AF_INET6, "::1.2.3.4");
1972
1973 // Cache hits, expect still 2 queries
1974 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
Luke Huang40f5f492019-05-09 19:37:35 +08001975
1976 // Test both ANDROID_RESOLV_NO_CACHE_STORE and ANDROID_RESOLV_NO_CACHE_LOOKUP are set
1977 dns.clearQueries();
1978
1979 // Make sure that the cache of "howdy.example2.com" exists.
1980 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa, 0);
1981 EXPECT_TRUE(fd1 != -1);
1982 expectAnswersValid(fd1, AF_INET6, "::1.2.3.5");
1983 EXPECT_EQ(1U, GetNumQueries(dns, another_host_name));
1984
1985 // Re-query with testFlags
1986 const int testFlag = ANDROID_RESOLV_NO_CACHE_STORE | ANDROID_RESOLV_NO_CACHE_LOOKUP;
1987 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa, testFlag);
1988 EXPECT_TRUE(fd1 != -1);
1989 expectAnswersValid(fd1, AF_INET6, "::1.2.3.5");
1990 // Expect cache lookup is skipped.
1991 EXPECT_EQ(2U, GetNumQueries(dns, another_host_name));
1992
1993 // Do another query with testFlags
1994 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_a, testFlag);
1995 EXPECT_TRUE(fd1 != -1);
1996 expectAnswersValid(fd1, AF_INET, "1.2.3.5");
1997 // Expect cache lookup is skipped.
1998 EXPECT_EQ(3U, GetNumQueries(dns, another_host_name));
1999
2000 // Re-query with no flags
2001 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_a, 0);
2002 EXPECT_TRUE(fd1 != -1);
2003 expectAnswersValid(fd1, AF_INET, "1.2.3.5");
2004 // Expect no cache hit because cache storing is also skipped in previous query.
2005 EXPECT_EQ(4U, GetNumQueries(dns, another_host_name));
Luke Huangba7bef92018-12-26 16:53:03 +08002006}
2007
2008TEST_F(ResolverTest, Async_NoRetryFlag) {
Luke Huang70931aa2019-01-31 11:57:41 +08002009 constexpr char listen_addr0[] = "127.0.0.4";
2010 constexpr char listen_addr1[] = "127.0.0.6";
Xiao Ma09b71022018-12-11 17:56:32 +09002011 constexpr char host_name[] = "howdy.example.com.";
2012 const std::vector<DnsRecord> records = {
2013 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2014 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2015 };
2016
Luke Huang70931aa2019-01-31 11:57:41 +08002017 test::DNSResponder dns0(listen_addr0);
2018 test::DNSResponder dns1(listen_addr1);
2019 StartDns(dns0, records);
2020 StartDns(dns1, records);
2021 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr0, listen_addr1}));
Luke Huangba7bef92018-12-26 16:53:03 +08002022
Luke Huang70931aa2019-01-31 11:57:41 +08002023 dns0.clearQueries();
2024 dns1.clearQueries();
2025
2026 dns0.setResponseProbability(0.0);
2027 dns1.setResponseProbability(0.0);
Luke Huangba7bef92018-12-26 16:53:03 +08002028
2029 int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2030 ANDROID_RESOLV_NO_RETRY);
2031 EXPECT_TRUE(fd1 != -1);
2032
2033 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa,
2034 ANDROID_RESOLV_NO_RETRY);
2035 EXPECT_TRUE(fd2 != -1);
2036
2037 // expect no response
2038 expectAnswersNotValid(fd1, -ETIMEDOUT);
2039 expectAnswersNotValid(fd2, -ETIMEDOUT);
2040
Luke Huang70931aa2019-01-31 11:57:41 +08002041 // No retry case, expect total 2 queries. The server is selected randomly.
2042 EXPECT_EQ(2U, GetNumQueries(dns0, host_name) + GetNumQueries(dns1, host_name));
Luke Huangba7bef92018-12-26 16:53:03 +08002043
Luke Huang70931aa2019-01-31 11:57:41 +08002044 dns0.clearQueries();
2045 dns1.clearQueries();
Luke Huangba7bef92018-12-26 16:53:03 +08002046
2047 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2048 EXPECT_TRUE(fd1 != -1);
2049
2050 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2051 EXPECT_TRUE(fd2 != -1);
2052
2053 // expect no response
2054 expectAnswersNotValid(fd1, -ETIMEDOUT);
2055 expectAnswersNotValid(fd2, -ETIMEDOUT);
2056
2057 // Retry case, expect 4 queries
Luke Huang70931aa2019-01-31 11:57:41 +08002058 EXPECT_EQ(4U, GetNumQueries(dns0, host_name));
2059 EXPECT_EQ(4U, GetNumQueries(dns1, host_name));
2060}
2061
2062TEST_F(ResolverTest, Async_VerifyQueryID) {
2063 constexpr char listen_addr[] = "127.0.0.4";
2064 constexpr char host_name[] = "howdy.example.com.";
2065 const std::vector<DnsRecord> records = {
2066 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2067 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2068 };
2069
2070 test::DNSResponder dns(listen_addr);
2071 StartDns(dns, records);
2072 std::vector<std::string> servers = {listen_addr};
2073 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2074
2075 const uint8_t queryBuf1[] = {
2076 /* Header */
2077 0x55, 0x66, /* Transaction ID */
2078 0x01, 0x00, /* Flags */
2079 0x00, 0x01, /* Questions */
2080 0x00, 0x00, /* Answer RRs */
2081 0x00, 0x00, /* Authority RRs */
2082 0x00, 0x00, /* Additional RRs */
2083 /* Queries */
2084 0x05, 0x68, 0x6f, 0x77, 0x64, 0x79, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
2085 0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */
2086 0x00, 0x01, /* Type */
2087 0x00, 0x01 /* Class */
2088 };
2089
2090 int fd = resNetworkSend(TEST_NETID, queryBuf1, sizeof(queryBuf1), 0);
2091 EXPECT_TRUE(fd != -1);
2092
2093 uint8_t buf[MAXPACKET] = {};
2094 int rcode;
2095
2096 int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2097 EXPECT_GT(res, 0);
2098 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2099
2100 auto hp = reinterpret_cast<HEADER*>(buf);
2101 EXPECT_EQ(21862U, htons(hp->id));
2102
2103 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2104
2105 const uint8_t queryBuf2[] = {
2106 /* Header */
2107 0x00, 0x53, /* Transaction ID */
2108 0x01, 0x00, /* Flags */
2109 0x00, 0x01, /* Questions */
2110 0x00, 0x00, /* Answer RRs */
2111 0x00, 0x00, /* Authority RRs */
2112 0x00, 0x00, /* Additional RRs */
2113 /* Queries */
2114 0x05, 0x68, 0x6f, 0x77, 0x64, 0x79, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
2115 0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */
2116 0x00, 0x01, /* Type */
2117 0x00, 0x01 /* Class */
2118 };
2119
2120 // Re-query verify cache works and query id is correct
2121 fd = resNetworkSend(TEST_NETID, queryBuf2, sizeof(queryBuf2), 0);
2122
2123 EXPECT_TRUE(fd != -1);
2124
2125 res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2126 EXPECT_GT(res, 0);
2127 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2128
2129 EXPECT_EQ(0x0053U, htons(hp->id));
2130
2131 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
Luke Huangba7bef92018-12-26 16:53:03 +08002132}
2133
Mike Yu4f3747b2018-12-02 17:54:29 +09002134// This test checks that the resolver should not generate the request containing OPT RR when using
Ken Chen0a015532019-01-02 14:59:38 +08002135// cleartext DNS. If we query the DNS server not supporting EDNS0 and it reponds with
2136// FORMERR_ON_EDNS, we will fallback to no EDNS0 and try again. If the server does no response, we
2137// won't retry so that we get no answer.
Mike Yu4f3747b2018-12-02 17:54:29 +09002138TEST_F(ResolverTest, BrokenEdns) {
2139 typedef test::DNSResponder::Edns Edns;
2140 enum ExpectResult { EXPECT_FAILURE, EXPECT_SUCCESS };
2141
2142 const char OFF[] = "off";
2143 const char OPPORTUNISTIC_UDP[] = "opportunistic_udp";
2144 const char OPPORTUNISTIC_TLS[] = "opportunistic_tls";
2145 const char STRICT[] = "strict";
2146 const char GETHOSTBYNAME[] = "gethostbyname";
2147 const char GETADDRINFO[] = "getaddrinfo";
Mike Yu4f3747b2018-12-02 17:54:29 +09002148 const char ADDR4[] = "192.0.2.1";
2149 const char CLEARTEXT_ADDR[] = "127.0.0.53";
2150 const char CLEARTEXT_PORT[] = "53";
2151 const char TLS_PORT[] = "853";
2152 const std::vector<std::string> servers = { CLEARTEXT_ADDR };
2153
Mike Yufc125e42019-05-15 20:41:28 +08002154 test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, ns_rcode::ns_r_servfail);
Mike Yu4f3747b2018-12-02 17:54:29 +09002155 ASSERT_TRUE(dns.startServer());
2156
2157 test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2158
2159 static const struct TestConfig {
2160 std::string mode;
2161 std::string method;
2162 Edns edns;
2163 ExpectResult expectResult;
2164
2165 std::string asHostName() const {
2166 const char* ednsString;
2167 switch (edns) {
2168 case Edns::ON:
2169 ednsString = "ednsOn";
2170 break;
Ken Chen0a015532019-01-02 14:59:38 +08002171 case Edns::FORMERR_ON_EDNS:
Mike Yu4f3747b2018-12-02 17:54:29 +09002172 ednsString = "ednsFormerr";
2173 break;
2174 case Edns::DROP:
2175 ednsString = "ednsDrop";
2176 break;
2177 default:
2178 ednsString = "";
2179 break;
2180 }
2181 return StringPrintf("%s.%s.%s.", mode.c_str(), method.c_str(), ednsString);
2182 }
2183 } testConfigs[] = {
2184 // In OPPORTUNISTIC_TLS, we get no answer if the DNS server supports TLS but not EDNS0.
2185 // Could such server exist? if so, we might need to fallback to query cleartext DNS.
2186 // Another thing is that {OPPORTUNISTIC_TLS, Edns::DROP} and {STRICT, Edns::DROP} are
2187 // commented out since TLS timeout is not configurable.
2188 // TODO: Uncomment them after TLS timeout is configurable.
2189 {OFF, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
2190 {OPPORTUNISTIC_UDP, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
2191 {OPPORTUNISTIC_TLS, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
2192 {STRICT, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
Ken Chen0a015532019-01-02 14:59:38 +08002193 {OFF, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2194 {OPPORTUNISTIC_UDP, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2195 {OPPORTUNISTIC_TLS, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
2196 {STRICT, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
Mike Yu4f3747b2018-12-02 17:54:29 +09002197 {OFF, GETHOSTBYNAME, Edns::DROP, EXPECT_SUCCESS},
2198 {OPPORTUNISTIC_UDP, GETHOSTBYNAME, Edns::DROP, EXPECT_SUCCESS},
2199 //{OPPORTUNISTIC_TLS, GETHOSTBYNAME, Edns::DROP, EXPECT_FAILURE},
2200 //{STRICT, GETHOSTBYNAME, Edns::DROP, EXPECT_FAILURE},
2201 {OFF, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
2202 {OPPORTUNISTIC_UDP, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
2203 {OPPORTUNISTIC_TLS, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
2204 {STRICT, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
Ken Chen0a015532019-01-02 14:59:38 +08002205 {OFF, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2206 {OPPORTUNISTIC_UDP, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2207 {OPPORTUNISTIC_TLS, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
2208 {STRICT, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
Mike Yu4f3747b2018-12-02 17:54:29 +09002209 {OFF, GETADDRINFO, Edns::DROP, EXPECT_SUCCESS},
2210 {OPPORTUNISTIC_UDP, GETADDRINFO, Edns::DROP, EXPECT_SUCCESS},
2211 //{OPPORTUNISTIC_TLS, GETADDRINFO, Edns::DROP, EXPECT_FAILURE},
2212 //{STRICT, GETADDRINFO, Edns::DROP, EXPECT_FAILURE},
2213 };
2214
2215 for (const auto& config : testConfigs) {
2216 const std::string testHostName = config.asHostName();
2217 SCOPED_TRACE(testHostName);
2218
2219 const char* host_name = testHostName.c_str();
2220 dns.addMapping(host_name, ns_type::ns_t_a, ADDR4);
2221 dns.setEdns(config.edns);
2222
2223 if (config.mode == OFF) {
Mike Yu0f20cdd2019-06-11 11:52:37 +08002224 if (tls.running()) {
2225 ASSERT_TRUE(tls.stopServer());
2226 }
Xiao Ma09b71022018-12-11 17:56:32 +09002227 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Mike Yu4f3747b2018-12-02 17:54:29 +09002228 } else if (config.mode == OPPORTUNISTIC_UDP) {
Mike Yu0f20cdd2019-06-11 11:52:37 +08002229 if (tls.running()) {
2230 ASSERT_TRUE(tls.stopServer());
2231 }
Xiao Ma09b71022018-12-11 17:56:32 +09002232 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
waynema0e73c2e2019-07-31 15:04:08 +08002233 kDefaultParams, ""));
Mike Yu724f77d2019-08-16 11:14:50 +08002234 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), false));
Mike Yu4f3747b2018-12-02 17:54:29 +09002235 } else if (config.mode == OPPORTUNISTIC_TLS) {
Mike Yu0f20cdd2019-06-11 11:52:37 +08002236 if (!tls.running()) {
2237 ASSERT_TRUE(tls.startServer());
2238 }
Xiao Ma09b71022018-12-11 17:56:32 +09002239 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
waynema0e73c2e2019-07-31 15:04:08 +08002240 kDefaultParams, ""));
Mike Yu724f77d2019-08-16 11:14:50 +08002241 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
Mike Yu4f3747b2018-12-02 17:54:29 +09002242 } else if (config.mode == STRICT) {
Mike Yu0f20cdd2019-06-11 11:52:37 +08002243 if (!tls.running()) {
2244 ASSERT_TRUE(tls.startServer());
2245 }
Xiao Ma09b71022018-12-11 17:56:32 +09002246 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
waynema0e73c2e2019-07-31 15:04:08 +08002247 kDefaultParams, kDefaultPrivateDnsHostName));
Mike Yu724f77d2019-08-16 11:14:50 +08002248 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
Mike Yu4f3747b2018-12-02 17:54:29 +09002249 }
2250
2251 if (config.method == GETHOSTBYNAME) {
2252 const hostent* h_result = gethostbyname(host_name);
2253 if (config.expectResult == EXPECT_SUCCESS) {
2254 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2255 ASSERT_TRUE(h_result != nullptr);
2256 ASSERT_EQ(4, h_result->h_length);
2257 ASSERT_FALSE(h_result->h_addr_list[0] == nullptr);
2258 EXPECT_EQ(ADDR4, ToString(h_result));
2259 EXPECT_TRUE(h_result->h_addr_list[1] == nullptr);
2260 } else {
2261 EXPECT_EQ(0U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
2262 ASSERT_TRUE(h_result == nullptr);
2263 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2264 }
2265 } else if (config.method == GETADDRINFO) {
2266 ScopedAddrinfo ai_result;
2267 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2268 ai_result = safe_getaddrinfo(host_name, nullptr, &hints);
2269 if (config.expectResult == EXPECT_SUCCESS) {
2270 EXPECT_TRUE(ai_result != nullptr);
2271 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2272 const std::string result_str = ToString(ai_result);
2273 EXPECT_EQ(ADDR4, result_str);
2274 } else {
2275 EXPECT_TRUE(ai_result == nullptr);
2276 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
2277 }
2278 } else {
2279 FAIL() << "Unsupported query method: " << config.method;
2280 }
2281
Mike Yudd4ac2d2019-05-31 16:52:11 +08002282 tls.clearQueries();
Mike Yu4f3747b2018-12-02 17:54:29 +09002283 dns.clearQueries();
2284 }
Mike Yu4f3747b2018-12-02 17:54:29 +09002285}
nuccachena26cc2a2018-07-17 18:07:23 +08002286
Ken Chen0a015532019-01-02 14:59:38 +08002287// DNS-over-TLS validation success, but server does not respond to TLS query after a while.
2288// Resolver should have a reasonable number of retries instead of spinning forever. We don't have
2289// an efficient way to know if resolver is stuck in an infinite loop. However, test case will be
2290// failed due to timeout.
2291TEST_F(ResolverTest, UnstableTls) {
2292 const char CLEARTEXT_ADDR[] = "127.0.0.53";
2293 const char CLEARTEXT_PORT[] = "53";
2294 const char TLS_PORT[] = "853";
2295 const char* host_name1 = "nonexistent1.example.com.";
2296 const char* host_name2 = "nonexistent2.example.com.";
2297 const std::vector<std::string> servers = {CLEARTEXT_ADDR};
2298
Mike Yufc125e42019-05-15 20:41:28 +08002299 test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, ns_rcode::ns_r_servfail);
Ken Chen0a015532019-01-02 14:59:38 +08002300 ASSERT_TRUE(dns.startServer());
2301 dns.setEdns(test::DNSResponder::Edns::FORMERR_ON_EDNS);
2302 test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2303 ASSERT_TRUE(tls.startServer());
waynema0e73c2e2019-07-31 15:04:08 +08002304 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
Mike Yu724f77d2019-08-16 11:14:50 +08002305 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
2306
Ken Chen0a015532019-01-02 14:59:38 +08002307 // Shutdown TLS server to get an error. It's similar to no response case but without waiting.
2308 tls.stopServer();
2309
2310 const hostent* h_result = gethostbyname(host_name1);
2311 EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
2312 ASSERT_TRUE(h_result == nullptr);
2313 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2314
2315 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2316 ScopedAddrinfo ai_result = safe_getaddrinfo(host_name2, nullptr, &hints);
2317 EXPECT_TRUE(ai_result == nullptr);
2318 EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
2319}
2320
2321// DNS-over-TLS validation success, but server does not respond to TLS query after a while.
2322// Moreover, server responds RCODE=FORMERR even on non-EDNS query.
2323TEST_F(ResolverTest, BogusDnsServer) {
2324 const char CLEARTEXT_ADDR[] = "127.0.0.53";
2325 const char CLEARTEXT_PORT[] = "53";
2326 const char TLS_PORT[] = "853";
2327 const char* host_name1 = "nonexistent1.example.com.";
2328 const char* host_name2 = "nonexistent2.example.com.";
2329 const std::vector<std::string> servers = {CLEARTEXT_ADDR};
2330
Mike Yufc125e42019-05-15 20:41:28 +08002331 test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, ns_rcode::ns_r_servfail);
Ken Chen0a015532019-01-02 14:59:38 +08002332 ASSERT_TRUE(dns.startServer());
2333 test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2334 ASSERT_TRUE(tls.startServer());
waynema0e73c2e2019-07-31 15:04:08 +08002335 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
Mike Yu724f77d2019-08-16 11:14:50 +08002336 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
2337
Ken Chen0a015532019-01-02 14:59:38 +08002338 // Shutdown TLS server to get an error. It's similar to no response case but without waiting.
2339 tls.stopServer();
2340 dns.setEdns(test::DNSResponder::Edns::FORMERR_UNCOND);
2341
2342 const hostent* h_result = gethostbyname(host_name1);
2343 EXPECT_EQ(0U, GetNumQueries(dns, host_name1));
2344 ASSERT_TRUE(h_result == nullptr);
2345 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2346
2347 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2348 ScopedAddrinfo ai_result = safe_getaddrinfo(host_name2, nullptr, &hints);
2349 EXPECT_TRUE(ai_result == nullptr);
2350 EXPECT_EQ(0U, GetNumQueries(dns, host_name2));
2351}
2352
nuccachena26cc2a2018-07-17 18:07:23 +08002353TEST_F(ResolverTest, GetAddrInfo_Dns64Synthesize) {
2354 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002355 constexpr char dns64_name[] = "ipv4only.arpa.";
2356 constexpr char host_name[] = "v4only.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09002357 const std::vector<DnsRecord> records = {
2358 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2359 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2360 };
nuccachena26cc2a2018-07-17 18:07:23 +08002361
Xiao Ma09b71022018-12-11 17:56:32 +09002362 test::DNSResponder dns(listen_addr);
Xiao Ma09b71022018-12-11 17:56:32 +09002363 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002364
2365 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002366 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002367
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002368 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002369 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002370 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002371
2372 // hints are necessary in order to let netd know which type of addresses the caller is
2373 // interested in.
Xiao Ma09b71022018-12-11 17:56:32 +09002374 const addrinfo hints = {.ai_family = AF_UNSPEC};
nuccachena26cc2a2018-07-17 18:07:23 +08002375 ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, &hints);
2376 EXPECT_TRUE(result != nullptr);
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002377 // TODO: BUG: there should only be two queries, one AAAA (which returns no records) and one A
2378 // (which returns 1.2.3.4). But there is an extra AAAA.
2379 EXPECT_EQ(3U, GetNumQueries(dns, host_name));
nuccachena26cc2a2018-07-17 18:07:23 +08002380
2381 std::string result_str = ToString(result);
2382 EXPECT_EQ(result_str, "64:ff9b::102:304");
2383
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002384 // Stopping NAT64 prefix discovery disables synthesis.
Luke Huang5bd827c2019-03-14 16:10:04 +08002385 EXPECT_TRUE(mDnsClient.resolvService()->stopPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002386 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_NOT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002387
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002388 dns.clearQueries();
nuccachena26cc2a2018-07-17 18:07:23 +08002389
2390 result = safe_getaddrinfo("v4only", nullptr, &hints);
2391 EXPECT_TRUE(result != nullptr);
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002392 // TODO: BUG: there should only be one query, an AAAA (which returns no records), because the
2393 // A is already cached. But there is an extra AAAA.
2394 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
nuccachena26cc2a2018-07-17 18:07:23 +08002395
2396 result_str = ToString(result);
2397 EXPECT_EQ(result_str, "1.2.3.4");
2398}
2399
nuccachena26cc2a2018-07-17 18:07:23 +08002400TEST_F(ResolverTest, GetAddrInfo_Dns64QuerySpecified) {
2401 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002402 constexpr char dns64_name[] = "ipv4only.arpa.";
2403 constexpr char host_name[] = "v4only.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09002404 const std::vector<DnsRecord> records = {
2405 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2406 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2407 };
nuccachena26cc2a2018-07-17 18:07:23 +08002408
Xiao Ma09b71022018-12-11 17:56:32 +09002409 test::DNSResponder dns(listen_addr);
2410 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002411 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002412 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002413
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002414 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002415 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002416 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002417
2418 // Ensure to synthesize AAAA if AF_INET6 is specified, and not to synthesize AAAA
2419 // in AF_INET case.
2420 addrinfo hints;
2421 memset(&hints, 0, sizeof(hints));
2422 hints.ai_family = AF_INET6;
2423 ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, &hints);
2424 EXPECT_TRUE(result != nullptr);
2425 std::string result_str = ToString(result);
2426 EXPECT_EQ(result_str, "64:ff9b::102:304");
2427
2428 hints.ai_family = AF_INET;
2429 result = safe_getaddrinfo("v4only", nullptr, &hints);
2430 EXPECT_TRUE(result != nullptr);
2431 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2432 result_str = ToString(result);
2433 EXPECT_EQ(result_str, "1.2.3.4");
2434}
nuccachena26cc2a2018-07-17 18:07:23 +08002435
2436TEST_F(ResolverTest, GetAddrInfo_Dns64QueryUnspecifiedV6) {
2437 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002438 constexpr char dns64_name[] = "ipv4only.arpa.";
2439 constexpr char host_name[] = "v4v6.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09002440 const std::vector<DnsRecord> records = {
2441 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2442 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2443 {host_name, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
2444 };
nuccachena26cc2a2018-07-17 18:07:23 +08002445
Xiao Ma09b71022018-12-11 17:56:32 +09002446 test::DNSResponder dns(listen_addr);
2447 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002448 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002449 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002450
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002451 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002452 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002453 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002454
Xiao Ma09b71022018-12-11 17:56:32 +09002455 const addrinfo hints = {.ai_family = AF_UNSPEC};
nuccachena26cc2a2018-07-17 18:07:23 +08002456 ScopedAddrinfo result = safe_getaddrinfo("v4v6", nullptr, &hints);
2457 EXPECT_TRUE(result != nullptr);
2458 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2459
2460 // In AF_UNSPEC case, do not synthesize AAAA if there's at least one AAAA answer.
Xiao Ma09b71022018-12-11 17:56:32 +09002461 const std::vector<std::string> result_strs = ToStrings(result);
nuccachena26cc2a2018-07-17 18:07:23 +08002462 for (const auto& str : result_strs) {
2463 EXPECT_TRUE(str == "1.2.3.4" || str == "2001:db8::102:304")
2464 << ", result_str='" << str << "'";
2465 }
2466}
2467
2468TEST_F(ResolverTest, GetAddrInfo_Dns64QueryUnspecifiedNoV6) {
2469 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002470 constexpr char dns64_name[] = "ipv4only.arpa.";
2471 constexpr char host_name[] = "v4v6.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09002472 const std::vector<DnsRecord> records = {
2473 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2474 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2475 };
nuccachena26cc2a2018-07-17 18:07:23 +08002476
Xiao Ma09b71022018-12-11 17:56:32 +09002477 test::DNSResponder dns(listen_addr);
2478 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002479 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002480 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002481
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002482 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002483 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002484 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002485
Xiao Ma09b71022018-12-11 17:56:32 +09002486 const addrinfo hints = {.ai_family = AF_UNSPEC};
nuccachena26cc2a2018-07-17 18:07:23 +08002487 ScopedAddrinfo result = safe_getaddrinfo("v4v6", nullptr, &hints);
2488 EXPECT_TRUE(result != nullptr);
2489 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2490
2491 // In AF_UNSPEC case, synthesize AAAA if there's no AAAA answer.
2492 std::string result_str = ToString(result);
2493 EXPECT_EQ(result_str, "64:ff9b::102:304");
2494}
2495
2496TEST_F(ResolverTest, GetAddrInfo_Dns64QuerySpecialUseIPv4Addresses) {
2497 constexpr char THIS_NETWORK[] = "this_network";
2498 constexpr char LOOPBACK[] = "loopback";
2499 constexpr char LINK_LOCAL[] = "link_local";
2500 constexpr char MULTICAST[] = "multicast";
2501 constexpr char LIMITED_BROADCAST[] = "limited_broadcast";
2502
2503 constexpr char ADDR_THIS_NETWORK[] = "0.0.0.1";
2504 constexpr char ADDR_LOOPBACK[] = "127.0.0.1";
2505 constexpr char ADDR_LINK_LOCAL[] = "169.254.0.1";
2506 constexpr char ADDR_MULTICAST[] = "224.0.0.1";
2507 constexpr char ADDR_LIMITED_BROADCAST[] = "255.255.255.255";
2508
2509 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002510 constexpr char dns64_name[] = "ipv4only.arpa.";
2511
Xiao Ma09b71022018-12-11 17:56:32 +09002512 test::DNSResponder dns(listen_addr);
2513 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
nuccachena26cc2a2018-07-17 18:07:23 +08002514 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002515 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002516
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002517 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002518 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002519 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002520
2521 static const struct TestConfig {
2522 std::string name;
2523 std::string addr;
2524
2525 std::string asHostName() const { return StringPrintf("%s.example.com.", name.c_str()); }
2526 } testConfigs[]{
2527 {THIS_NETWORK, ADDR_THIS_NETWORK},
2528 {LOOPBACK, ADDR_LOOPBACK},
2529 {LINK_LOCAL, ADDR_LINK_LOCAL},
2530 {MULTICAST, ADDR_MULTICAST},
2531 {LIMITED_BROADCAST, ADDR_LIMITED_BROADCAST}
2532 };
2533
2534 for (const auto& config : testConfigs) {
2535 const std::string testHostName = config.asHostName();
2536 SCOPED_TRACE(testHostName);
2537
2538 const char* host_name = testHostName.c_str();
2539 dns.addMapping(host_name, ns_type::ns_t_a, config.addr.c_str());
2540
2541 addrinfo hints;
2542 memset(&hints, 0, sizeof(hints));
2543 hints.ai_family = AF_INET6;
2544 ScopedAddrinfo result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
2545 // In AF_INET6 case, don't return IPv4 answers
2546 EXPECT_TRUE(result == nullptr);
2547 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2548 dns.clearQueries();
2549
2550 memset(&hints, 0, sizeof(hints));
2551 hints.ai_family = AF_UNSPEC;
2552 result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
2553 EXPECT_TRUE(result != nullptr);
2554 // Expect IPv6 query only. IPv4 answer has been cached in previous query.
2555 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2556 // In AF_UNSPEC case, don't synthesize special use IPv4 address.
2557 std::string result_str = ToString(result);
2558 EXPECT_EQ(result_str, config.addr.c_str());
2559 dns.clearQueries();
2560 }
2561}
2562
2563TEST_F(ResolverTest, GetAddrInfo_Dns64QueryWithNullArgumentHints) {
2564 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002565 constexpr char dns64_name[] = "ipv4only.arpa.";
2566 constexpr char host_name[] = "v4only.example.com.";
2567 constexpr char host_name2[] = "v4v6.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09002568 const std::vector<DnsRecord> records = {
2569 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2570 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2571 {host_name2, ns_type::ns_t_a, "1.2.3.4"},
2572 {host_name2, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
2573 };
nuccachena26cc2a2018-07-17 18:07:23 +08002574
Xiao Ma09b71022018-12-11 17:56:32 +09002575 test::DNSResponder dns(listen_addr);
2576 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002577 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002578 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002579
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002580 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002581 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002582 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002583
2584 // Assign argument hints of getaddrinfo() as null is equivalent to set ai_family AF_UNSPEC.
2585 // In AF_UNSPEC case, synthesize AAAA if there has A answer only.
2586 ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, nullptr);
2587 EXPECT_TRUE(result != nullptr);
2588 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2589 std::string result_str = ToString(result);
2590 EXPECT_EQ(result_str, "64:ff9b::102:304");
2591 dns.clearQueries();
2592
2593 // In AF_UNSPEC case, do not synthesize AAAA if there's at least one AAAA answer.
2594 result = safe_getaddrinfo("v4v6", nullptr, nullptr);
2595 EXPECT_TRUE(result != nullptr);
2596 EXPECT_LE(2U, GetNumQueries(dns, host_name2));
2597 std::vector<std::string> result_strs = ToStrings(result);
2598 for (const auto& str : result_strs) {
2599 EXPECT_TRUE(str == "1.2.3.4" || str == "2001:db8::102:304")
2600 << ", result_str='" << str << "'";
2601 }
2602}
2603
2604TEST_F(ResolverTest, GetAddrInfo_Dns64QueryNullArgumentNode) {
2605 constexpr char ADDR_ANYADDR_V4[] = "0.0.0.0";
2606 constexpr char ADDR_ANYADDR_V6[] = "::";
2607 constexpr char ADDR_LOCALHOST_V4[] = "127.0.0.1";
2608 constexpr char ADDR_LOCALHOST_V6[] = "::1";
2609
2610 constexpr char PORT_NAME_HTTP[] = "http";
2611 constexpr char PORT_NUMBER_HTTP[] = "80";
2612
2613 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002614 constexpr char dns64_name[] = "ipv4only.arpa.";
2615
Xiao Ma09b71022018-12-11 17:56:32 +09002616 test::DNSResponder dns(listen_addr);
2617 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
nuccachena26cc2a2018-07-17 18:07:23 +08002618 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002619 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002620
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002621 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002622 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002623 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002624
2625 // If node is null, return address is listed by libc/getaddrinfo.c as follows.
2626 // - passive socket -> anyaddr (0.0.0.0 or ::)
2627 // - non-passive socket -> localhost (127.0.0.1 or ::1)
2628 static const struct TestConfig {
2629 int flag;
2630 std::string addr_v4;
2631 std::string addr_v6;
2632
2633 std::string asParameters() const {
2634 return StringPrintf("flag=%d, addr_v4=%s, addr_v6=%s", flag, addr_v4.c_str(),
2635 addr_v6.c_str());
2636 }
2637 } testConfigs[]{
2638 {0 /* non-passive */, ADDR_LOCALHOST_V4, ADDR_LOCALHOST_V6},
2639 {AI_PASSIVE, ADDR_ANYADDR_V4, ADDR_ANYADDR_V6}
2640 };
2641
2642 for (const auto& config : testConfigs) {
2643 SCOPED_TRACE(config.asParameters());
2644
Xiao Ma09b71022018-12-11 17:56:32 +09002645 addrinfo hints = {
Nick Desaulnierscd6395a2019-10-11 09:15:24 -07002646 .ai_flags = config.flag,
Xiao Ma09b71022018-12-11 17:56:32 +09002647 .ai_family = AF_UNSPEC, // any address family
2648 .ai_socktype = 0, // any type
2649 .ai_protocol = 0, // any protocol
Xiao Ma09b71022018-12-11 17:56:32 +09002650 };
nuccachena26cc2a2018-07-17 18:07:23 +08002651
2652 // Assign hostname as null and service as port name.
2653 ScopedAddrinfo result = safe_getaddrinfo(nullptr, PORT_NAME_HTTP, &hints);
2654 ASSERT_TRUE(result != nullptr);
2655
2656 // Can't be synthesized because it should not get into Netd.
2657 std::vector<std::string> result_strs = ToStrings(result);
2658 for (const auto& str : result_strs) {
2659 EXPECT_TRUE(str == config.addr_v4 || str == config.addr_v6)
2660 << ", result_str='" << str << "'";
2661 }
2662
2663 // Assign hostname as null and service as numeric port number.
2664 hints.ai_flags = config.flag | AI_NUMERICSERV;
2665 result = safe_getaddrinfo(nullptr, PORT_NUMBER_HTTP, &hints);
2666 ASSERT_TRUE(result != nullptr);
2667
2668 // Can't be synthesized because it should not get into Netd.
2669 result_strs = ToStrings(result);
2670 for (const auto& str : result_strs) {
2671 EXPECT_TRUE(str == config.addr_v4 || str == config.addr_v6)
2672 << ", result_str='" << str << "'";
2673 }
2674 }
2675}
2676
2677TEST_F(ResolverTest, GetHostByAddr_ReverseDnsQueryWithHavingNat64Prefix) {
2678 struct hostent* result = nullptr;
2679 struct in_addr v4addr;
2680 struct in6_addr v6addr;
2681
2682 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002683 constexpr char dns64_name[] = "ipv4only.arpa.";
2684 constexpr char ptr_name[] = "v4v6.example.com.";
2685 // PTR record for IPv4 address 1.2.3.4
2686 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2687 // PTR record for IPv6 address 2001:db8::102:304
2688 constexpr char ptr_addr_v6[] =
2689 "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 +09002690 const std::vector<DnsRecord> records = {
2691 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2692 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2693 {ptr_addr_v6, ns_type::ns_t_ptr, ptr_name},
2694 };
nuccachena26cc2a2018-07-17 18:07:23 +08002695
Xiao Ma09b71022018-12-11 17:56:32 +09002696 test::DNSResponder dns(listen_addr);
2697 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002698 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002699 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002700
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002701 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002702 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002703 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002704
2705 // Reverse IPv4 DNS query. Prefix should have no effect on it.
2706 inet_pton(AF_INET, "1.2.3.4", &v4addr);
2707 result = gethostbyaddr(&v4addr, sizeof(v4addr), AF_INET);
2708 ASSERT_TRUE(result != nullptr);
2709 std::string result_str = result->h_name ? result->h_name : "null";
2710 EXPECT_EQ(result_str, "v4v6.example.com");
2711
2712 // Reverse IPv6 DNS query. Prefix should have no effect on it.
2713 inet_pton(AF_INET6, "2001:db8::102:304", &v6addr);
2714 result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2715 ASSERT_TRUE(result != nullptr);
2716 result_str = result->h_name ? result->h_name : "null";
2717 EXPECT_EQ(result_str, "v4v6.example.com");
2718}
2719
2720TEST_F(ResolverTest, GetHostByAddr_ReverseDns64Query) {
2721 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002722 constexpr char dns64_name[] = "ipv4only.arpa.";
2723 constexpr char ptr_name[] = "v4only.example.com.";
2724 // PTR record for IPv4 address 1.2.3.4
2725 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2726 // PTR record for IPv6 address 64:ff9b::1.2.3.4
2727 constexpr char ptr_addr_v6_nomapping[] =
2728 "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.";
2729 constexpr char ptr_name_v6_synthesis[] = "v6synthesis.example.com.";
2730 // PTR record for IPv6 address 64:ff9b::5.6.7.8
2731 constexpr char ptr_addr_v6_synthesis[] =
2732 "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 +09002733 const std::vector<DnsRecord> records = {
2734 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2735 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2736 {ptr_addr_v6_synthesis, ns_type::ns_t_ptr, ptr_name_v6_synthesis},
2737 };
nuccachena26cc2a2018-07-17 18:07:23 +08002738
Xiao Ma09b71022018-12-11 17:56:32 +09002739 test::DNSResponder dns(listen_addr);
2740 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002741 // "ptr_addr_v6_nomapping" is not mapped in DNS server
nuccachena26cc2a2018-07-17 18:07:23 +08002742 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002743 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002744
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002745 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002746 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002747 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002748
2749 // Synthesized PTR record doesn't exist on DNS server
2750 // Reverse IPv6 DNS64 query while DNS server doesn't have an answer for synthesized address.
2751 // After querying synthesized address failed, expect that prefix is removed from IPv6
2752 // synthesized address and do reverse IPv4 query instead.
2753 struct in6_addr v6addr;
2754 inet_pton(AF_INET6, "64:ff9b::1.2.3.4", &v6addr);
2755 struct hostent* result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2756 ASSERT_TRUE(result != nullptr);
2757 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_nomapping)); // PTR record not exist
2758 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4)); // PTR record exist
2759 std::string result_str = result->h_name ? result->h_name : "null";
2760 EXPECT_EQ(result_str, "v4only.example.com");
2761 // Check that return address has been mapped from IPv4 to IPv6 address because Netd
2762 // removes NAT64 prefix and does IPv4 DNS reverse lookup in this case. Then, Netd
2763 // fakes the return IPv4 address as original queried IPv6 address.
2764 result_str = ToString(result);
2765 EXPECT_EQ(result_str, "64:ff9b::102:304");
2766 dns.clearQueries();
2767
2768 // Synthesized PTR record exists on DNS server
2769 // Reverse IPv6 DNS64 query while DNS server has an answer for synthesized address.
2770 // Expect to Netd pass through synthesized address for DNS queries.
2771 inet_pton(AF_INET6, "64:ff9b::5.6.7.8", &v6addr);
2772 result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2773 ASSERT_TRUE(result != nullptr);
2774 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_synthesis));
2775 result_str = result->h_name ? result->h_name : "null";
2776 EXPECT_EQ(result_str, "v6synthesis.example.com");
2777}
2778
2779TEST_F(ResolverTest, GetHostByAddr_ReverseDns64QueryFromHostFile) {
2780 constexpr char dns64_name[] = "ipv4only.arpa.";
2781 constexpr char host_name[] = "localhost";
2782 // The address is synthesized by prefix64:localhost.
2783 constexpr char host_addr[] = "64:ff9b::7f00:1";
nuccachena26cc2a2018-07-17 18:07:23 +08002784 constexpr char listen_addr[] = "::1";
Xiao Ma09b71022018-12-11 17:56:32 +09002785
2786 test::DNSResponder dns(listen_addr);
2787 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
nuccachena26cc2a2018-07-17 18:07:23 +08002788 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002789 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002790
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002791 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002792 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002793 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002794
2795 // Using synthesized "localhost" address to be a trick for resolving host name
2796 // from host file /etc/hosts and "localhost" is the only name in /etc/hosts. Note that this is
2797 // not realistic: the code never synthesizes AAAA records for addresses in 127.0.0.0/8.
2798 struct in6_addr v6addr;
2799 inet_pton(AF_INET6, host_addr, &v6addr);
2800 struct hostent* result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2801 ASSERT_TRUE(result != nullptr);
2802 // Expect no DNS queries; localhost is resolved via /etc/hosts.
2803 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
2804
2805 ASSERT_EQ(sizeof(in6_addr), (unsigned) result->h_length);
2806 ASSERT_EQ(AF_INET6, result->h_addrtype);
2807 std::string result_str = ToString(result);
2808 EXPECT_EQ(result_str, host_addr);
2809 result_str = result->h_name ? result->h_name : "null";
2810 EXPECT_EQ(result_str, host_name);
2811}
2812
Hungming Chen9e6185a2019-06-04 16:09:19 +08002813TEST_F(ResolverTest, GetHostByAddr_cnamesClasslessReverseDelegation) {
2814 // IPv4 addresses in the subnet with notation '/' or '-'.
2815 constexpr char addr_slash[] = "192.0.2.1";
2816 constexpr char addr_hyphen[] = "192.0.3.1";
2817
2818 // Used to verify DNS reverse query for classless reverse lookup zone. See detail in RFC 2317
2819 // section 4.
2820 const static std::vector<DnsRecord> records = {
2821 // The records for reverse querying "192.0.2.1" in the subnet with notation '/'.
2822 {"1.2.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0/25.2.0.192.in-addr.arpa."},
2823 {"1.0/25.2.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
2824
2825 // The records for reverse querying "192.0.3.1" in the subnet with notation '-'.
2826 {"1.3.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0-127.3.0.192.in-addr.arpa."},
2827 {"1.0-127.3.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
2828 };
2829
2830 test::DNSResponder dns;
2831 StartDns(dns, records);
2832 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
2833
2834 for (const auto& address : {addr_slash, addr_hyphen}) {
2835 SCOPED_TRACE(address);
2836
2837 in_addr v4addr;
2838 ASSERT_TRUE(inet_pton(AF_INET, address, &v4addr));
2839 hostent* result = gethostbyaddr(&v4addr, sizeof(v4addr), AF_INET);
2840 ASSERT_TRUE(result != nullptr);
2841 EXPECT_STREQ("hello.example.com", result->h_name);
2842 }
2843}
2844
nuccachena26cc2a2018-07-17 18:07:23 +08002845TEST_F(ResolverTest, GetNameInfo_ReverseDnsQueryWithHavingNat64Prefix) {
2846 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002847 constexpr char dns64_name[] = "ipv4only.arpa.";
2848 constexpr char ptr_name[] = "v4v6.example.com.";
2849 // PTR record for IPv4 address 1.2.3.4
2850 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2851 // PTR record for IPv6 address 2001:db8::102:304
2852 constexpr char ptr_addr_v6[] =
2853 "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 +09002854 const std::vector<DnsRecord> records = {
2855 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2856 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2857 {ptr_addr_v6, ns_type::ns_t_ptr, ptr_name},
2858 };
nuccachena26cc2a2018-07-17 18:07:23 +08002859
Xiao Ma09b71022018-12-11 17:56:32 +09002860 test::DNSResponder dns(listen_addr);
2861 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002862 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002863 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002864
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002865 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002866 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002867 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002868
2869 static const struct TestConfig {
2870 int flag;
2871 int family;
2872 std::string addr;
2873 std::string host;
2874
2875 std::string asParameters() const {
2876 return StringPrintf("flag=%d, family=%d, addr=%s, host=%s", flag, family, addr.c_str(),
2877 host.c_str());
2878 }
2879 } testConfigs[]{
2880 {NI_NAMEREQD, AF_INET, "1.2.3.4", "v4v6.example.com"},
2881 {NI_NUMERICHOST, AF_INET, "1.2.3.4", "1.2.3.4"},
2882 {0, AF_INET, "1.2.3.4", "v4v6.example.com"},
2883 {0, AF_INET, "5.6.7.8", "5.6.7.8"}, // unmapped
2884 {NI_NAMEREQD, AF_INET6, "2001:db8::102:304", "v4v6.example.com"},
2885 {NI_NUMERICHOST, AF_INET6, "2001:db8::102:304", "2001:db8::102:304"},
2886 {0, AF_INET6, "2001:db8::102:304", "v4v6.example.com"},
2887 {0, AF_INET6, "2001:db8::506:708", "2001:db8::506:708"}, // unmapped
2888 };
2889
2890 // Reverse IPv4/IPv6 DNS query. Prefix should have no effect on it.
2891 for (const auto& config : testConfigs) {
2892 SCOPED_TRACE(config.asParameters());
2893
2894 int rv;
2895 char host[NI_MAXHOST];
2896 struct sockaddr_in sin;
2897 struct sockaddr_in6 sin6;
2898 if (config.family == AF_INET) {
2899 memset(&sin, 0, sizeof(sin));
2900 sin.sin_family = AF_INET;
2901 inet_pton(AF_INET, config.addr.c_str(), &sin.sin_addr);
2902 rv = getnameinfo((const struct sockaddr*) &sin, sizeof(sin), host, sizeof(host),
2903 nullptr, 0, config.flag);
2904 if (config.flag == NI_NAMEREQD) EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4));
2905 } else if (config.family == AF_INET6) {
2906 memset(&sin6, 0, sizeof(sin6));
2907 sin6.sin6_family = AF_INET6;
2908 inet_pton(AF_INET6, config.addr.c_str(), &sin6.sin6_addr);
2909 rv = getnameinfo((const struct sockaddr*) &sin6, sizeof(sin6), host, sizeof(host),
2910 nullptr, 0, config.flag);
2911 if (config.flag == NI_NAMEREQD) EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6));
2912 }
2913 ASSERT_EQ(0, rv);
2914 std::string result_str = host;
2915 EXPECT_EQ(result_str, config.host);
2916 dns.clearQueries();
2917 }
2918}
2919
2920TEST_F(ResolverTest, GetNameInfo_ReverseDns64Query) {
2921 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002922 constexpr char dns64_name[] = "ipv4only.arpa.";
2923 constexpr char ptr_name[] = "v4only.example.com.";
2924 // PTR record for IPv4 address 1.2.3.4
2925 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2926 // PTR record for IPv6 address 64:ff9b::1.2.3.4
2927 constexpr char ptr_addr_v6_nomapping[] =
2928 "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.";
2929 constexpr char ptr_name_v6_synthesis[] = "v6synthesis.example.com.";
2930 // PTR record for IPv6 address 64:ff9b::5.6.7.8
2931 constexpr char ptr_addr_v6_synthesis[] =
2932 "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 +09002933 const std::vector<DnsRecord> records = {
2934 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2935 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2936 {ptr_addr_v6_synthesis, ns_type::ns_t_ptr, ptr_name_v6_synthesis},
2937 };
nuccachena26cc2a2018-07-17 18:07:23 +08002938
Xiao Ma09b71022018-12-11 17:56:32 +09002939 test::DNSResponder dns(listen_addr);
2940 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002941 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002942 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002943
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002944 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002945 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002946 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002947
2948 static const struct TestConfig {
2949 bool hasSynthesizedPtrRecord;
2950 int flag;
2951 std::string addr;
2952 std::string host;
2953
2954 std::string asParameters() const {
2955 return StringPrintf("hasSynthesizedPtrRecord=%d, flag=%d, addr=%s, host=%s",
2956 hasSynthesizedPtrRecord, flag, addr.c_str(), host.c_str());
2957 }
2958 } testConfigs[]{
2959 {false, NI_NAMEREQD, "64:ff9b::102:304", "v4only.example.com"},
2960 {false, NI_NUMERICHOST, "64:ff9b::102:304", "64:ff9b::102:304"},
2961 {false, 0, "64:ff9b::102:304", "v4only.example.com"},
2962 {true, NI_NAMEREQD, "64:ff9b::506:708", "v6synthesis.example.com"},
2963 {true, NI_NUMERICHOST, "64:ff9b::506:708", "64:ff9b::506:708"},
2964 {true, 0, "64:ff9b::506:708", "v6synthesis.example.com"}
2965 };
2966
2967 // hasSynthesizedPtrRecord = false
2968 // Synthesized PTR record doesn't exist on DNS server
2969 // Reverse IPv6 DNS64 query while DNS server doesn't have an answer for synthesized address.
2970 // After querying synthesized address failed, expect that prefix is removed from IPv6
2971 // synthesized address and do reverse IPv4 query instead.
2972 //
2973 // hasSynthesizedPtrRecord = true
2974 // Synthesized PTR record exists on DNS server
2975 // Reverse IPv6 DNS64 query while DNS server has an answer for synthesized address.
2976 // Expect to just pass through synthesized address for DNS queries.
2977 for (const auto& config : testConfigs) {
2978 SCOPED_TRACE(config.asParameters());
2979
2980 char host[NI_MAXHOST];
2981 struct sockaddr_in6 sin6;
2982 memset(&sin6, 0, sizeof(sin6));
2983 sin6.sin6_family = AF_INET6;
2984 inet_pton(AF_INET6, config.addr.c_str(), &sin6.sin6_addr);
2985 int rv = getnameinfo((const struct sockaddr*) &sin6, sizeof(sin6), host, sizeof(host),
2986 nullptr, 0, config.flag);
2987 ASSERT_EQ(0, rv);
2988 if (config.flag == NI_NAMEREQD) {
2989 if (config.hasSynthesizedPtrRecord) {
2990 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_synthesis));
2991 } else {
2992 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_nomapping)); // PTR record not exist.
2993 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4)); // PTR record exist.
2994 }
2995 }
2996 std::string result_str = host;
2997 EXPECT_EQ(result_str, config.host);
2998 dns.clearQueries();
2999 }
3000}
3001
3002TEST_F(ResolverTest, GetNameInfo_ReverseDns64QueryFromHostFile) {
3003 constexpr char dns64_name[] = "ipv4only.arpa.";
3004 constexpr char host_name[] = "localhost";
3005 // The address is synthesized by prefix64:localhost.
3006 constexpr char host_addr[] = "64:ff9b::7f00:1";
nuccachena26cc2a2018-07-17 18:07:23 +08003007 constexpr char listen_addr[] = "::1";
Xiao Ma09b71022018-12-11 17:56:32 +09003008
3009 test::DNSResponder dns(listen_addr);
3010 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
nuccachena26cc2a2018-07-17 18:07:23 +08003011 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09003012 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08003013
Lorenzo Colittid39345c2019-02-18 10:59:29 +09003014 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08003015 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003016 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08003017
3018 // Using synthesized "localhost" address to be a trick for resolving host name
3019 // from host file /etc/hosts and "localhost" is the only name in /etc/hosts. Note that this is
3020 // not realistic: the code never synthesizes AAAA records for addresses in 127.0.0.0/8.
3021 char host[NI_MAXHOST];
Xiao Ma09b71022018-12-11 17:56:32 +09003022 struct sockaddr_in6 sin6 = {.sin6_family = AF_INET6};
nuccachena26cc2a2018-07-17 18:07:23 +08003023 inet_pton(AF_INET6, host_addr, &sin6.sin6_addr);
3024 int rv = getnameinfo((const struct sockaddr*) &sin6, sizeof(sin6), host, sizeof(host), nullptr,
3025 0, NI_NAMEREQD);
3026 ASSERT_EQ(0, rv);
3027 // Expect no DNS queries; localhost is resolved via /etc/hosts.
3028 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
3029
3030 std::string result_str = host;
3031 EXPECT_EQ(result_str, host_name);
3032}
3033
Hungming Chen9e6185a2019-06-04 16:09:19 +08003034TEST_F(ResolverTest, GetNameInfo_cnamesClasslessReverseDelegation) {
3035 // IPv4 addresses in the subnet with notation '/' or '-'.
3036 constexpr char addr_slash[] = "192.0.2.1";
3037 constexpr char addr_hyphen[] = "192.0.3.1";
3038
3039 // Used to verify DNS reverse query for classless reverse lookup zone. See detail in RFC 2317
3040 // section 4.
3041 const static std::vector<DnsRecord> records = {
3042 // The records for reverse querying "192.0.2.1" in the subnet with notation '/'.
3043 {"1.2.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0/25.2.0.192.in-addr.arpa."},
3044 {"1.0/25.2.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
3045
3046 // The records for reverse querying "192.0.3.1" in the subnet with notation '-'.
3047 {"1.3.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0-127.3.0.192.in-addr.arpa."},
3048 {"1.0-127.3.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
3049 };
3050
3051 test::DNSResponder dns;
3052 StartDns(dns, records);
3053 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
3054
3055 for (const auto& address : {addr_slash, addr_hyphen}) {
3056 SCOPED_TRACE(address);
3057
3058 char host[NI_MAXHOST];
3059 sockaddr_in sin = {.sin_family = AF_INET};
3060 ASSERT_TRUE(inet_pton(AF_INET, address, &sin.sin_addr));
3061 int rv = getnameinfo((const sockaddr*)&sin, sizeof(sin), host, sizeof(host), nullptr, 0,
3062 NI_NAMEREQD);
3063 ASSERT_EQ(0, rv);
3064 EXPECT_STREQ("hello.example.com", host);
3065 }
3066}
3067
nuccachena26cc2a2018-07-17 18:07:23 +08003068TEST_F(ResolverTest, GetHostByName2_Dns64Synthesize) {
Xiao Ma09b71022018-12-11 17:56:32 +09003069 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08003070 constexpr char dns64_name[] = "ipv4only.arpa.";
3071 constexpr char host_name[] = "ipv4only.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09003072 const std::vector<DnsRecord> records = {
3073 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3074 {host_name, ns_type::ns_t_a, "1.2.3.4"},
3075 };
nuccachena26cc2a2018-07-17 18:07:23 +08003076
Xiao Ma09b71022018-12-11 17:56:32 +09003077 test::DNSResponder dns(listen_addr);
3078 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08003079 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09003080 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08003081
Lorenzo Colittid39345c2019-02-18 10:59:29 +09003082 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08003083 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003084 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08003085
3086 // Query an IPv4-only hostname. Expect that gets a synthesized address.
3087 struct hostent* result = gethostbyname2("ipv4only", AF_INET6);
3088 ASSERT_TRUE(result != nullptr);
3089 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3090 std::string result_str = ToString(result);
3091 EXPECT_EQ(result_str, "64:ff9b::102:304");
3092}
nuccachena26cc2a2018-07-17 18:07:23 +08003093
3094TEST_F(ResolverTest, GetHostByName2_DnsQueryWithHavingNat64Prefix) {
3095 constexpr char dns64_name[] = "ipv4only.arpa.";
3096 constexpr char host_name[] = "v4v6.example.com.";
nuccachena26cc2a2018-07-17 18:07:23 +08003097 constexpr char listen_addr[] = "::1";
Xiao Ma09b71022018-12-11 17:56:32 +09003098 const std::vector<DnsRecord> records = {
3099 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3100 {host_name, ns_type::ns_t_a, "1.2.3.4"},
3101 {host_name, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
3102 };
3103
3104 test::DNSResponder dns(listen_addr);
3105 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08003106 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09003107 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08003108
Lorenzo Colittid39345c2019-02-18 10:59:29 +09003109 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08003110 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003111 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08003112
3113 // IPv4 DNS query. Prefix should have no effect on it.
3114 struct hostent* result = gethostbyname2("v4v6", AF_INET);
3115 ASSERT_TRUE(result != nullptr);
3116 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3117 std::string result_str = ToString(result);
3118 EXPECT_EQ(result_str, "1.2.3.4");
3119 dns.clearQueries();
3120
3121 // IPv6 DNS query. Prefix should have no effect on it.
3122 result = gethostbyname2("v4v6", AF_INET6);
3123 ASSERT_TRUE(result != nullptr);
3124 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3125 result_str = ToString(result);
3126 EXPECT_EQ(result_str, "2001:db8::102:304");
3127}
3128
3129TEST_F(ResolverTest, GetHostByName2_Dns64QuerySpecialUseIPv4Addresses) {
3130 constexpr char THIS_NETWORK[] = "this_network";
3131 constexpr char LOOPBACK[] = "loopback";
3132 constexpr char LINK_LOCAL[] = "link_local";
3133 constexpr char MULTICAST[] = "multicast";
3134 constexpr char LIMITED_BROADCAST[] = "limited_broadcast";
3135
3136 constexpr char ADDR_THIS_NETWORK[] = "0.0.0.1";
3137 constexpr char ADDR_LOOPBACK[] = "127.0.0.1";
3138 constexpr char ADDR_LINK_LOCAL[] = "169.254.0.1";
3139 constexpr char ADDR_MULTICAST[] = "224.0.0.1";
3140 constexpr char ADDR_LIMITED_BROADCAST[] = "255.255.255.255";
3141
3142 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08003143 constexpr char dns64_name[] = "ipv4only.arpa.";
3144
Xiao Ma09b71022018-12-11 17:56:32 +09003145 test::DNSResponder dns(listen_addr);
3146 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
nuccachena26cc2a2018-07-17 18:07:23 +08003147 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09003148 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08003149
Lorenzo Colittid39345c2019-02-18 10:59:29 +09003150 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08003151 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003152 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08003153
3154 static const struct TestConfig {
3155 std::string name;
3156 std::string addr;
3157
3158 std::string asHostName() const {
3159 return StringPrintf("%s.example.com.",
3160 name.c_str());
3161 }
3162 } testConfigs[]{
3163 {THIS_NETWORK, ADDR_THIS_NETWORK},
3164 {LOOPBACK, ADDR_LOOPBACK},
3165 {LINK_LOCAL, ADDR_LINK_LOCAL},
3166 {MULTICAST, ADDR_MULTICAST},
3167 {LIMITED_BROADCAST, ADDR_LIMITED_BROADCAST}
3168 };
3169
3170 for (const auto& config : testConfigs) {
3171 const std::string testHostName = config.asHostName();
3172 SCOPED_TRACE(testHostName);
3173
3174 const char* host_name = testHostName.c_str();
3175 dns.addMapping(host_name, ns_type::ns_t_a, config.addr.c_str());
3176
3177 struct hostent* result = gethostbyname2(config.name.c_str(), AF_INET6);
3178 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3179
3180 // In AF_INET6 case, don't synthesize special use IPv4 address.
3181 // Expect to have no answer
3182 EXPECT_EQ(nullptr, result);
3183
3184 dns.clearQueries();
3185 }
Bernie Innocenti2fef2b82018-12-20 15:56:40 +09003186}
Mike Yuf14e1a92019-05-10 13:54:58 +08003187
3188TEST_F(ResolverTest, PrefixDiscoveryBypassTls) {
3189 constexpr char listen_addr[] = "::1";
3190 constexpr char cleartext_port[] = "53";
3191 constexpr char tls_port[] = "853";
3192 constexpr char dns64_name[] = "ipv4only.arpa.";
3193 const std::vector<std::string> servers = {listen_addr};
3194
3195 test::DNSResponder dns(listen_addr);
3196 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
3197 test::DnsTlsFrontend tls(listen_addr, tls_port, listen_addr, cleartext_port);
3198 ASSERT_TRUE(tls.startServer());
3199
3200 // Setup OPPORTUNISTIC mode and wait for the validation complete.
waynema0e73c2e2019-07-31 15:04:08 +08003201 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
Mike Yu724f77d2019-08-16 11:14:50 +08003202 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
Mike Yuf14e1a92019-05-10 13:54:58 +08003203 tls.clearQueries();
3204
3205 // Start NAT64 prefix discovery and wait for it complete.
3206 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003207 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
Mike Yuf14e1a92019-05-10 13:54:58 +08003208
3209 // Verify it bypassed TLS even though there's a TLS server available.
3210 EXPECT_EQ(0, tls.queries());
3211 EXPECT_EQ(1U, GetNumQueries(dns, dns64_name));
3212
3213 // Restart the testing network to reset the cache.
3214 mDnsClient.TearDown();
3215 mDnsClient.SetUp();
3216 dns.clearQueries();
3217
3218 // Setup STRICT mode and wait for the validation complete.
waynema0e73c2e2019-07-31 15:04:08 +08003219 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
3220 kDefaultPrivateDnsHostName));
Mike Yu724f77d2019-08-16 11:14:50 +08003221 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
Mike Yuf14e1a92019-05-10 13:54:58 +08003222 tls.clearQueries();
3223
3224 // Start NAT64 prefix discovery and wait for it to complete.
3225 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003226 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
Mike Yuf14e1a92019-05-10 13:54:58 +08003227
3228 // Verify it bypassed TLS despite STRICT mode.
3229 EXPECT_EQ(0, tls.queries());
3230 EXPECT_EQ(1U, GetNumQueries(dns, dns64_name));
3231}
Luke Huang9807e6b2019-05-20 16:17:12 +08003232
3233namespace {
3234
Luke Huang0d592bc2019-05-25 18:24:03 +08003235class ScopedSetNetworkForProcess {
3236 public:
3237 explicit ScopedSetNetworkForProcess(unsigned netId) {
3238 mStoredNetId = getNetworkForProcess();
3239 if (netId == mStoredNetId) return;
3240 EXPECT_EQ(0, setNetworkForProcess(netId));
3241 }
3242 ~ScopedSetNetworkForProcess() { EXPECT_EQ(0, setNetworkForProcess(mStoredNetId)); }
3243
3244 private:
3245 unsigned mStoredNetId;
3246};
3247
3248class ScopedSetNetworkForResolv {
3249 public:
3250 explicit ScopedSetNetworkForResolv(unsigned netId) { EXPECT_EQ(0, setNetworkForResolv(netId)); }
3251 ~ScopedSetNetworkForResolv() { EXPECT_EQ(0, setNetworkForResolv(NETID_UNSET)); }
3252};
3253
Luke Huang9807e6b2019-05-20 16:17:12 +08003254void sendCommand(int fd, const std::string& cmd) {
3255 ssize_t rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size() + 1));
3256 EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size() + 1));
3257}
3258
3259int32_t readBE32(int fd) {
3260 int32_t tmp;
3261 int n = TEMP_FAILURE_RETRY(read(fd, &tmp, sizeof(tmp)));
3262 EXPECT_TRUE(n > 0);
3263 return ntohl(tmp);
3264}
3265
Luke Huang0d592bc2019-05-25 18:24:03 +08003266int readResponseCode(int fd) {
Luke Huang9807e6b2019-05-20 16:17:12 +08003267 char buf[4];
3268 int n = TEMP_FAILURE_RETRY(read(fd, &buf, sizeof(buf)));
3269 EXPECT_TRUE(n > 0);
3270 // The format of response code is that 4 bytes for the code & null.
3271 buf[3] = '\0';
3272 int result;
3273 EXPECT_TRUE(ParseInt(buf, &result));
3274 return result;
3275}
3276
Luke Huang0d592bc2019-05-25 18:24:03 +08003277bool checkAndClearUseLocalNameserversFlag(unsigned* netid) {
3278 if (netid == nullptr || ((*netid) & NETID_USE_LOCAL_NAMESERVERS) == 0) {
3279 return false;
3280 }
3281 *netid = (*netid) & ~NETID_USE_LOCAL_NAMESERVERS;
3282 return true;
3283}
3284
3285android::net::UidRangeParcel makeUidRangeParcel(int start, int stop) {
3286 android::net::UidRangeParcel res;
3287 res.start = start;
3288 res.stop = stop;
3289
3290 return res;
3291}
3292
3293void expectNetIdWithLocalNameserversFlag(unsigned netId) {
3294 unsigned dnsNetId = 0;
3295 EXPECT_EQ(0, getNetworkForDns(&dnsNetId));
3296 EXPECT_TRUE(checkAndClearUseLocalNameserversFlag(&dnsNetId));
3297 EXPECT_EQ(netId, static_cast<unsigned>(dnsNetId));
3298}
3299
3300void expectDnsNetIdEquals(unsigned netId) {
3301 unsigned dnsNetId = 0;
3302 EXPECT_EQ(0, getNetworkForDns(&dnsNetId));
3303 EXPECT_EQ(netId, static_cast<unsigned>(dnsNetId));
3304}
3305
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +09003306void expectDnsNetIdIsDefaultNetwork(INetd* netdService) {
Luke Huang0d592bc2019-05-25 18:24:03 +08003307 int currentNetid;
3308 EXPECT_TRUE(netdService->networkGetDefault(&currentNetid).isOk());
3309 expectDnsNetIdEquals(currentNetid);
3310}
3311
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +09003312void expectDnsNetIdWithVpn(INetd* netdService, unsigned vpnNetId, unsigned expectedNetId) {
Luke Huang0d592bc2019-05-25 18:24:03 +08003313 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}
Sehee Park2c118782019-05-07 13:02:45 +09003377
3378TEST_F(ResolverTest, BlockDnsQueryWithUidRule) {
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +09003379 // This test relies on blocking traffic on loopback, which xt_qtaguid does not do.
3380 // See aosp/358413 and b/34444781 for why.
3381 SKIP_IF_BPF_NOT_SUPPORTED;
3382
Sehee Park2c118782019-05-07 13:02:45 +09003383 constexpr char listen_addr1[] = "127.0.0.4";
3384 constexpr char listen_addr2[] = "::1";
3385 constexpr char host_name[] = "howdy.example.com.";
3386 const std::vector<DnsRecord> records = {
3387 {host_name, ns_type::ns_t_a, "1.2.3.4"},
3388 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
3389 };
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +09003390 INetd* netdService = mDnsClient.netdService();
Sehee Park2c118782019-05-07 13:02:45 +09003391
3392 test::DNSResponder dns1(listen_addr1);
3393 test::DNSResponder dns2(listen_addr2);
3394 StartDns(dns1, records);
3395 StartDns(dns2, records);
3396
3397 std::vector<std::string> servers = {listen_addr1, listen_addr2};
3398 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3399 dns1.clearQueries();
3400 dns2.clearQueries();
3401
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +09003402 // Add drop rule for TEST_UID. Also enable the standby chain because it might not be enabled.
3403 // Unfortunately we cannot use FIREWALL_CHAIN_NONE, or custom iptables rules, for this purpose
3404 // because netd calls fchown() on the DNS query sockets, and "iptables -m owner" matches the
3405 // UID of the socket creator, not the UID set by fchown().
3406 //
3407 // TODO: migrate FIREWALL_CHAIN_NONE to eBPF as well.
3408 EXPECT_TRUE(netdService->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true).isOk());
3409 EXPECT_TRUE(netdService
Sehee Park2c118782019-05-07 13:02:45 +09003410 ->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, TEST_UID,
3411 INetd::FIREWALL_RULE_DENY)
3412 .isOk());
3413
3414 // Save uid
3415 int suid = getuid();
3416
3417 // Switch to TEST_UID
3418 EXPECT_TRUE(seteuid(TEST_UID) == 0);
3419
3420 // Dns Query
3421 int fd1 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_a, 0);
3422 int fd2 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_aaaa, 0);
3423 EXPECT_TRUE(fd1 != -1);
3424 EXPECT_TRUE(fd2 != -1);
3425
3426 uint8_t buf[MAXPACKET] = {};
3427 int rcode;
3428 int res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
3429 EXPECT_EQ(-ECONNREFUSED, res);
3430
3431 memset(buf, 0, MAXPACKET);
3432 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
3433 EXPECT_EQ(-ECONNREFUSED, res);
3434
3435 // Restore uid
3436 EXPECT_TRUE(seteuid(suid) == 0);
3437
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +09003438 // Remove drop rule for TEST_UID, and disable the standby chain.
3439 EXPECT_TRUE(netdService
Sehee Park2c118782019-05-07 13:02:45 +09003440 ->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, TEST_UID,
3441 INetd::FIREWALL_RULE_ALLOW)
3442 .isOk());
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +09003443 EXPECT_TRUE(netdService->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false).isOk());
Sehee Park2c118782019-05-07 13:02:45 +09003444}
Mike Yua772c202019-09-23 17:47:21 +08003445
3446TEST_F(ResolverTest, ConnectTlsServerTimeout) {
3447 constexpr char listen_addr[] = "127.0.0.3";
3448 constexpr char listen_udp[] = "53";
3449 constexpr char listen_tls[] = "853";
3450 constexpr char host_name[] = "tls.example.com.";
3451 const std::vector<std::string> servers = {listen_addr};
3452 const std::vector<DnsRecord> records = {
3453 {host_name, ns_type::ns_t_a, "1.2.3.4"},
3454 };
3455
3456 test::DNSResponder dns;
3457 StartDns(dns, records);
3458
3459 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
3460 ASSERT_TRUE(tls.startServer());
3461
3462 // Opportunistic mode.
3463 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, {}));
3464
3465 // Wait for the server being marked as validated so that PrivateDnsStatus::validatedServers()
3466 // won't return empty list.
3467 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
3468 dns.clearQueries();
3469 tls.clearQueries();
3470
3471 // The server becomes unresponsive to the handshake request.
3472 tls.setHangOnHandshakeForTesting(true);
3473
3474 // Expect the things happening in getaddrinfo():
3475 // 1. Connect to the private DNS server.
3476 // 2. SSL handshake times out.
3477 // 3. Fallback to UDP transport, and then get the answer.
3478 const auto start = std::chrono::steady_clock::now();
3479 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
3480 ScopedAddrinfo result = safe_getaddrinfo("tls", nullptr, &hints);
3481 const auto end = std::chrono::steady_clock::now();
3482
3483 EXPECT_TRUE(result != nullptr);
3484 EXPECT_EQ(0, tls.queries());
3485 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
3486 EXPECT_EQ("1.2.3.4", ToString(result));
3487
3488 // 3000ms is a loose upper bound. Theoretically, it takes a bit more than 1000ms.
3489 EXPECT_GE(3000, std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count());
3490 EXPECT_LE(1000, std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count());
3491}
Hungming Chenbb90ab32019-10-28 18:20:31 +08003492
3493// Parameterized tests.
3494// TODO: Merge the existing tests as parameterized test if possible.
3495// TODO: Perhaps move parameterized tests to an independent file.
3496enum class CallType { GETADDRINFO, GETHOSTBYNAME };
3497class ResolverParameterizedTest : public ResolverTest,
Hungming Chen63779052019-10-30 15:06:13 +08003498 public testing::WithParamInterface<CallType> {
3499 protected:
3500 void VerifyQueryHelloExampleComV4(const test::DNSResponder& dns, const CallType calltype) {
3501 if (calltype == CallType::GETADDRINFO) {
3502 const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
3503 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
3504 ASSERT_TRUE(result != nullptr);
3505 EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
3506 } else if (calltype == CallType::GETHOSTBYNAME) {
3507 const hostent* result = gethostbyname("hello");
3508 ASSERT_TRUE(result != nullptr);
3509 ASSERT_EQ(4, result->h_length);
3510 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
3511 EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
3512 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
3513 } else {
3514 FAIL() << "Unsupported call type: " << static_cast<uint32_t>(calltype);
3515 }
3516 EXPECT_EQ(1U, GetNumQueries(dns, kHelloExampleCom));
3517 }
3518};
Hungming Chenbb90ab32019-10-28 18:20:31 +08003519
Hungming Chen63779052019-10-30 15:06:13 +08003520INSTANTIATE_TEST_SUITE_P(QueryCallTest, ResolverParameterizedTest,
Hungming Chenbb90ab32019-10-28 18:20:31 +08003521 testing::Values(CallType::GETADDRINFO, CallType::GETHOSTBYNAME),
3522 [](const testing::TestParamInfo<CallType>& info) {
Hungming Chenbb90ab32019-10-28 18:20:31 +08003523 switch (info.param) {
3524 case CallType::GETADDRINFO:
Hungming Chen63779052019-10-30 15:06:13 +08003525 return "GetAddrInfo";
Hungming Chenbb90ab32019-10-28 18:20:31 +08003526 case CallType::GETHOSTBYNAME:
Hungming Chen63779052019-10-30 15:06:13 +08003527 return "GetHostByName";
Hungming Chenbb90ab32019-10-28 18:20:31 +08003528 default:
Hungming Chen63779052019-10-30 15:06:13 +08003529 return "InvalidParameter"; // Should not happen.
Hungming Chenbb90ab32019-10-28 18:20:31 +08003530 }
Hungming Chenbb90ab32019-10-28 18:20:31 +08003531 });
3532
3533TEST_P(ResolverParameterizedTest, AuthoritySectionAndAdditionalSection) {
3534 // DNS response may have more information in authority section and additional section.
3535 // Currently, getanswer() of packages/modules/DnsResolver/getaddrinfo.cpp doesn't parse the
3536 // content of authority section and additional section. Test these sections if they crash
3537 // the resolver, just in case. See also RFC 1035 section 4.1.
3538 const auto& calltype = GetParam();
3539 test::DNSHeader header(kDefaultDnsHeader);
3540
3541 // Create a DNS response which has a authoritative nameserver record in authority
3542 // section and its relevant address record in additional section.
3543 //
3544 // Question
3545 // hello.example.com. IN A
3546 // Answer
3547 // hello.example.com. IN A 1.2.3.4
3548 // Authority:
3549 // hello.example.com. IN NS ns1.example.com.
3550 // Additional:
3551 // ns1.example.com. IN A 5.6.7.8
3552 //
3553 // A response may have only question, answer, and authority section. Current testing response
3554 // should be able to cover this condition.
3555
3556 // Question section.
3557 test::DNSQuestion question{
3558 .qname = {.name = kHelloExampleCom},
3559 .qtype = ns_type::ns_t_a,
3560 .qclass = ns_c_in,
3561 };
3562 header.questions.push_back(std::move(question));
3563
3564 // Answer section.
3565 test::DNSRecord recordAnswer{
3566 .name = {.name = kHelloExampleCom},
3567 .rtype = ns_type::ns_t_a,
3568 .rclass = ns_c_in,
3569 .ttl = 0, // no cache
3570 };
Hungming Chen63779052019-10-30 15:06:13 +08003571 EXPECT_TRUE(test::DNSResponder::fillRdata(kHelloExampleComAddrV4, recordAnswer));
Hungming Chenbb90ab32019-10-28 18:20:31 +08003572 header.answers.push_back(std::move(recordAnswer));
3573
3574 // Authority section.
3575 test::DNSRecord recordAuthority{
3576 .name = {.name = kHelloExampleCom},
3577 .rtype = ns_type::ns_t_ns,
3578 .rclass = ns_c_in,
3579 .ttl = 0, // no cache
3580 };
3581 EXPECT_TRUE(test::DNSResponder::fillRdata("ns1.example.com.", recordAuthority));
3582 header.authorities.push_back(std::move(recordAuthority));
3583
3584 // Additional section.
3585 test::DNSRecord recordAdditional{
3586 .name = {.name = "ns1.example.com."},
3587 .rtype = ns_type::ns_t_a,
3588 .rclass = ns_c_in,
3589 .ttl = 0, // no cache
3590 };
3591 EXPECT_TRUE(test::DNSResponder::fillRdata("5.6.7.8", recordAdditional));
3592 header.additionals.push_back(std::move(recordAdditional));
3593
3594 // Start DNS server.
3595 test::DNSResponder dns(test::DNSResponder::MappingType::DNS_HEADER);
3596 dns.addMappingDnsHeader(kHelloExampleCom, ns_type::ns_t_a, header);
3597 ASSERT_TRUE(dns.startServer());
3598 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
3599 dns.clearQueries();
3600
3601 // Expect that get the address and the resolver doesn't crash.
Hungming Chen63779052019-10-30 15:06:13 +08003602 VerifyQueryHelloExampleComV4(dns, calltype);
3603}
3604
3605TEST_P(ResolverParameterizedTest, MessageCompression) {
3606 const auto& calltype = GetParam();
3607
3608 // The response with compressed domain name by a pointer. See RFC 1035 section 4.1.4.
3609 //
3610 // Ignoring the other fields of the message, the domain name of question section and answer
3611 // section are presented as:
3612 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3613 // 12 | 5 | h |
3614 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3615 // 14 | e | l |
3616 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3617 // 16 | l | o |
3618 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3619 // 18 | 7 | e |
3620 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3621 // 20 | x | a |
3622 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3623 // 22 | m | p |
3624 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3625 // 24 | l | e |
3626 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3627 // 26 | 3 | c |
3628 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3629 // 28 | o | m |
3630 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3631 // 30 | 0 | ... |
3632 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3633 //
3634 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3635 // 35 | 1 1| 12 |
3636 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3637 const std::vector<uint8_t> kResponseAPointer = {
3638 /* Header */
3639 0x00, 0x00, /* Transaction ID: 0x0000 */
3640 0x81, 0x80, /* Flags: qr rd ra */
3641 0x00, 0x01, /* Questions: 1 */
3642 0x00, 0x01, /* Answer RRs: 1 */
3643 0x00, 0x00, /* Authority RRs: 0 */
3644 0x00, 0x00, /* Additional RRs: 0 */
3645 /* Queries */
3646 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
3647 0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name: hello.example.com */
3648 0x00, 0x01, /* Type: A */
3649 0x00, 0x01, /* Class: IN */
3650 /* Answers */
3651 0xc0, 0x0c, /* Name: hello.example.com (a pointer) */
3652 0x00, 0x01, /* Type: A */
3653 0x00, 0x01, /* Class: IN */
3654 0x00, 0x00, 0x00, 0x00, /* Time to live: 0 */
3655 0x00, 0x04, /* Data length: 4 */
3656 0x01, 0x02, 0x03, 0x04 /* Address: 1.2.3.4 */
3657 };
3658
3659 // The response with compressed domain name by a sequence of labels ending with a pointer. See
3660 // RFC 1035 section 4.1.4.
3661 //
3662 // Ignoring the other fields of the message, the domain name of question section and answer
3663 // section are presented as:
3664 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3665 // 12 | 5 | h |
3666 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3667 // 14 | e | l |
3668 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3669 // 16 | l | o |
3670 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3671 // 18 | 7 | e |
3672 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3673 // 20 | x | a |
3674 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3675 // 22 | m | p |
3676 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3677 // 24 | l | e |
3678 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3679 // 26 | 3 | c |
3680 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3681 // 28 | o | m |
3682 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3683 // 30 | 0 | ... |
3684 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3685 //
3686 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3687 // 35 | 5 | h |
3688 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3689 // 37 | e | l |
3690 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3691 // 39 | l | o |
3692 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3693 // 41 | 1 1| 18 |
3694 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3695 const std::vector<uint8_t> kResponseLabelEndingWithAPointer = {
3696 /* Header */
3697 0x00, 0x00, /* Transaction ID: 0x0000 */
3698 0x81, 0x80, /* Flags: qr rd ra */
3699 0x00, 0x01, /* Questions: 1 */
3700 0x00, 0x01, /* Answer RRs: 1 */
3701 0x00, 0x00, /* Authority RRs: 0 */
3702 0x00, 0x00, /* Additional RRs: 0 */
3703 /* Queries */
3704 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
3705 0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name: hello.example.com */
3706 0x00, 0x01, /* Type: A */
3707 0x00, 0x01, /* Class: IN */
3708 /* Answers */
3709 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0xc0,
3710 0x12, /* Name: hello.example.com (a label ending with a pointer) */
3711 0x00, 0x01, /* Type: A */
3712 0x00, 0x01, /* Class: IN */
3713 0x00, 0x00, 0x00, 0x00, /* Time to live: 0 */
3714 0x00, 0x04, /* Data length: 4 */
3715 0x01, 0x02, 0x03, 0x04 /* Address: 1.2.3.4 */
3716 };
3717
3718 for (const auto& response : {kResponseAPointer, kResponseLabelEndingWithAPointer}) {
3719 SCOPED_TRACE(StringPrintf("Hex dump: %s", toHex(makeSlice(response)).c_str()));
3720
3721 test::DNSResponder dns(test::DNSResponder::MappingType::BINARY_PACKET);
3722 dns.addMappingBinaryPacket(kHelloExampleComQueryV4, response);
3723 StartDns(dns, {});
3724 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
3725
3726 // Expect no cache because the TTL of testing responses are 0.
3727 VerifyQueryHelloExampleComV4(dns, calltype);
Hungming Chenbb90ab32019-10-28 18:20:31 +08003728 }
3729}