blob: 0129f9247a47fc9a167d5d164a45b2a0b90e1c09 [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>
Mike Yu40e67072019-10-09 21:14:09 +080022#include <android-base/properties.h>
Bernie Innocenti41b82c42019-06-05 22:38:25 +090023#include <android-base/stringprintf.h>
24#include <android-base/unique_fd.h>
25#include <android/multinetwork.h> // ResNsendFlags
Ken Chenb9fa2062018-11-13 21:51:13 +080026#include <arpa/inet.h>
Luke Huang94b10b92018-11-21 20:13:38 +080027#include <arpa/nameser.h>
Hungming Chene8f970c2019-04-10 17:34:06 +080028#include <binder/ProcessState.h>
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +090029#include <bpf/BpfUtils.h>
Bernie Innocenti41b82c42019-06-05 22:38:25 +090030#include <cutils/sockets.h>
31#include <gmock/gmock-matchers.h>
32#include <gtest/gtest.h>
Ken Chenb9fa2062018-11-13 21:51:13 +080033#include <netdb.h>
Luke Huang9d2d25b2019-06-14 00:34:05 +080034#include <netdutils/InternetAddresses.h>
Luke Huang579ddc72019-06-14 00:59:39 +080035#include <netdutils/NetworkConstants.h> // SHA256_SIZE
Luke Huang9d2d25b2019-06-14 00:34:05 +080036#include <netdutils/ResponseCode.h>
Hungming Chen63779052019-10-30 15:06:13 +080037#include <netdutils/Slice.h>
Luke Huang9d2d25b2019-06-14 00:34:05 +080038#include <netdutils/SocketOption.h>
Mike Yu40e67072019-10-09 21:14:09 +080039#include <netdutils/Stopwatch.h>
Luke Huang94b10b92018-11-21 20:13:38 +080040#include <netinet/in.h>
Bernie Innocenti41b82c42019-06-05 22:38:25 +090041#include <openssl/base64.h>
Luke Huang94b10b92018-11-21 20:13:38 +080042#include <poll.h> /* poll */
Bernie Innocenti41b82c42019-06-05 22:38:25 +090043#include <private/android_filesystem_config.h>
Luke Huang94b10b92018-11-21 20:13:38 +080044#include <resolv.h>
Ken Chenb9fa2062018-11-13 21:51:13 +080045#include <stdarg.h>
Ken Chenb9fa2062018-11-13 21:51:13 +080046#include <stdlib.h>
Luke Huang94b10b92018-11-21 20:13:38 +080047#include <sys/socket.h>
48#include <sys/un.h>
Ken Chenb9fa2062018-11-13 21:51:13 +080049#include <unistd.h>
50
51#include <algorithm>
52#include <chrono>
53#include <iterator>
54#include <numeric>
55#include <thread>
56
Bernie Innocenti41b82c42019-06-05 22:38:25 +090057#include "NetdClient.h"
Bernie Innocenti41b82c42019-06-05 22:38:25 +090058#include "ResolverStats.h"
59#include "android/net/IDnsResolver.h"
60#include "binder/IServiceManager.h"
Bernie Innocenti41b82c42019-06-05 22:38:25 +090061#include "netd_resolv/params.h" // MAXNS
chenbruceb43ec752019-07-24 20:19:41 +080062#include "netid_client.h" // NETID_UNSET
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +090063#include "test_utils.h"
Hungming Chene8f970c2019-04-10 17:34:06 +080064#include "tests/dns_metrics_listener/dns_metrics_listener.h"
chenbruceb43ec752019-07-24 20:19:41 +080065#include "tests/dns_responder/dns_responder.h"
66#include "tests/dns_responder/dns_responder_client.h"
67#include "tests/dns_responder/dns_tls_frontend.h"
Luke Huangfde82482019-06-04 01:04:53 +080068#include "tests/resolv_test_utils.h"
Ken Chenb9fa2062018-11-13 21:51:13 +080069
Luke Huang0d592bc2019-05-25 18:24:03 +080070// Valid VPN netId range is 100 ~ 65535
71constexpr int TEST_VPN_NETID = 65502;
Luke Huang94b10b92018-11-21 20:13:38 +080072constexpr int MAXPACKET = (8 * 1024);
Ken Chenb9fa2062018-11-13 21:51:13 +080073
Sehee Park2c118782019-05-07 13:02:45 +090074// Use maximum reserved appId for applications to avoid conflict with existing uids.
75static const int TEST_UID = 99999;
76
waynema0e73c2e2019-07-31 15:04:08 +080077// Currently the hostname of TLS server must match the CN filed on the server's certificate.
78// Inject a test CA whose hostname is "example.com" for DNS-OVER-TLS tests.
79static const std::string kDefaultPrivateDnsHostName = "example.com";
80static const std::string kDefaultIncorrectPrivateDnsHostName = "www.example.com";
81
Ken Chenb9fa2062018-11-13 21:51:13 +080082// Semi-public Bionic hook used by the NDK (frameworks/base/native/android/net.c)
83// Tested here for convenience.
84extern "C" int android_getaddrinfofornet(const char* hostname, const char* servname,
85 const addrinfo* hints, unsigned netid, unsigned mark,
86 struct addrinfo** result);
87
Luke Huang9807e6b2019-05-20 16:17:12 +080088using android::base::ParseInt;
Ken Chenb9fa2062018-11-13 21:51:13 +080089using android::base::StringPrintf;
Luke Huang9807e6b2019-05-20 16:17:12 +080090using android::base::unique_fd;
Sehee Park2c118782019-05-07 13:02:45 +090091using android::net::INetd;
Mike Yu40e67072019-10-09 21:14:09 +080092using android::net::ResolverParamsParcel;
Ken Chenb9fa2062018-11-13 21:51:13 +080093using android::net::ResolverStats;
Hungming Chene8f970c2019-04-10 17:34:06 +080094using android::net::metrics::DnsMetricsListener;
Ken Chenb9fa2062018-11-13 21:51:13 +080095using android::netdutils::enableSockopt;
Hungming Chen63779052019-10-30 15:06:13 +080096using android::netdutils::makeSlice;
Luke Huang9807e6b2019-05-20 16:17:12 +080097using android::netdutils::ResponseCode;
Luke Huang9d2d25b2019-06-14 00:34:05 +080098using android::netdutils::ScopedAddrinfo;
Mike Yu40e67072019-10-09 21:14:09 +080099using android::netdutils::Stopwatch;
Hungming Chen63779052019-10-30 15:06:13 +0800100using android::netdutils::toHex;
Ken Chenb9fa2062018-11-13 21:51:13 +0800101
102// TODO: move into libnetdutils?
103namespace {
Luke Huangfde82482019-06-04 01:04:53 +0800104
Ken Chenb9fa2062018-11-13 21:51:13 +0800105ScopedAddrinfo safe_getaddrinfo(const char* node, const char* service,
106 const struct addrinfo* hints) {
107 addrinfo* result = nullptr;
108 if (getaddrinfo(node, service, hints, &result) != 0) {
109 result = nullptr; // Should already be the case, but...
110 }
111 return ScopedAddrinfo(result);
112}
Luke Huangfde82482019-06-04 01:04:53 +0800113
Mike Yu40e67072019-10-09 21:14:09 +0800114std::pair<ScopedAddrinfo, int> safe_getaddrinfo_time_taken(const char* node, const char* service,
115 const addrinfo& hints) {
116 Stopwatch s;
117 ScopedAddrinfo result = safe_getaddrinfo(node, service, &hints);
118 return {std::move(result), s.timeTakenUs() / 1000};
119}
120
Ken Chenb9fa2062018-11-13 21:51:13 +0800121} // namespace
122
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900123class ResolverTest : public ::testing::Test {
Hungming Chene8f970c2019-04-10 17:34:06 +0800124 public:
Hungming Chen5bf09772019-04-25 11:16:13 +0800125 static void SetUpTestCase() {
126 // Get binder service.
127 // Note that |mDnsClient| is not used for getting binder service in this static function.
128 // The reason is that wants to keep |mDnsClient| as a non-static data member. |mDnsClient|
129 // which sets up device network configuration could be independent from every test.
Hungming Chen9e6185a2019-06-04 16:09:19 +0800130 // TODO: Perhaps add a static function in resolv_test_utils.{cpp,h} to get binder service.
Hungming Chen5bf09772019-04-25 11:16:13 +0800131 auto resolvBinder =
132 android::defaultServiceManager()->getService(android::String16("dnsresolver"));
133 auto resolvService = android::interface_cast<android::net::IDnsResolver>(resolvBinder);
134 ASSERT_NE(nullptr, resolvService.get());
135
136 // Subscribe the death recipient to the service IDnsResolver for detecting Netd death.
137 sResolvDeathRecipient = new ResolvDeathRecipient();
138 ASSERT_EQ(android::NO_ERROR, resolvBinder->linkToDeath(sResolvDeathRecipient));
139
140 // Subscribe the DNS listener for verifying DNS metrics event contents.
141 sDnsMetricsListener = new DnsMetricsListener(TEST_NETID /*monitor specific network*/);
142 ASSERT_TRUE(resolvService->registerEventListener(sDnsMetricsListener).isOk());
143
144 // Start the binder thread pool for listening DNS metrics events and receiving death
145 // recipient.
146 android::ProcessState::self()->startThreadPool();
Hungming Chene8f970c2019-04-10 17:34:06 +0800147 }
148
Ken Chenb9fa2062018-11-13 21:51:13 +0800149 protected:
Xiao Ma09b71022018-12-11 17:56:32 +0900150 struct DnsRecord {
151 std::string host_name; // host name
152 ns_type type; // record type
153 std::string addr; // ipv4/v6 address
154 };
155
Hungming Chen5bf09772019-04-25 11:16:13 +0800156 class ResolvDeathRecipient : public android::IBinder::DeathRecipient {
157 public:
158 ~ResolvDeathRecipient() override = default;
Hungming Chene8f970c2019-04-10 17:34:06 +0800159
Hungming Chen5bf09772019-04-25 11:16:13 +0800160 // GTEST assertion macros are not invoked for generating a test failure in the death
161 // recipient because the macros can't indicate failed test if Netd died between tests.
162 // Moreover, continuing testing may have no meaningful after Netd death. Therefore, the
163 // death recipient aborts process by GTEST_LOG_(FATAL) once Netd died.
164 void binderDied(const android::wp<android::IBinder>& /*who*/) override {
Hungming Chen9e6185a2019-06-04 16:09:19 +0800165 constexpr char errorMessage[] = "Netd died";
Hungming Chen5bf09772019-04-25 11:16:13 +0800166 LOG(ERROR) << errorMessage;
167 GTEST_LOG_(FATAL) << errorMessage;
168 }
169 };
Hungming Chene8f970c2019-04-10 17:34:06 +0800170
Hungming Chen5bf09772019-04-25 11:16:13 +0800171 void SetUp() { mDnsClient.SetUp(); }
Hungming Chene8f970c2019-04-10 17:34:06 +0800172 void TearDown() { mDnsClient.TearDown(); }
nuccachena26cc2a2018-07-17 18:07:23 +0800173
Xiao Ma09b71022018-12-11 17:56:32 +0900174 void StartDns(test::DNSResponder& dns, const std::vector<DnsRecord>& records) {
175 for (const auto& r : records) {
176 dns.addMapping(r.host_name, r.type, r.addr);
177 }
178
179 ASSERT_TRUE(dns.startServer());
180 dns.clearQueries();
181 }
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900182
Hungming Chene8f970c2019-04-10 17:34:06 +0800183 bool WaitForNat64Prefix(ExpectNat64PrefixStatus status,
184 std::chrono::milliseconds timeout = std::chrono::milliseconds(1000)) {
Hungming Chen5bf09772019-04-25 11:16:13 +0800185 return sDnsMetricsListener->waitForNat64Prefix(status, timeout);
Hungming Chene8f970c2019-04-10 17:34:06 +0800186 }
187
Mike Yu724f77d2019-08-16 11:14:50 +0800188 bool WaitForPrivateDnsValidation(std::string serverAddr, bool validated) {
189 return sDnsMetricsListener->waitForPrivateDnsValidation(serverAddr, validated);
190 }
191
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900192 DnsResponderClient mDnsClient;
Xiao Ma09b71022018-12-11 17:56:32 +0900193
Hungming Chen5bf09772019-04-25 11:16:13 +0800194 // Use a shared static DNS listener for all tests to avoid registering lots of listeners
195 // which may be released late until process terminated. Currently, registered DNS listener
196 // is removed by binder death notification which is fired when the process hosting an
197 // IBinder has gone away. If every test in ResolverTest registers its DNS listener, Netd
198 // may temporarily hold lots of dead listeners until the unit test process terminates.
199 // TODO: Perhaps add an unregistering listener binder call or fork a listener process which
200 // could be terminated earlier.
201 static android::sp<DnsMetricsListener> sDnsMetricsListener; // Initialized in SetUpTestCase.
202
203 // Use a shared static death recipient to monitor the service death. The static death
204 // recipient could monitor the death not only during the test but also between tests.
205 static android::sp<ResolvDeathRecipient>
206 sResolvDeathRecipient; // Initialized in SetUpTestCase.
Ken Chenb9fa2062018-11-13 21:51:13 +0800207};
208
Hungming Chen5bf09772019-04-25 11:16:13 +0800209// Initialize static member of class.
210android::sp<DnsMetricsListener> ResolverTest::sDnsMetricsListener;
211android::sp<ResolverTest::ResolvDeathRecipient> ResolverTest::sResolvDeathRecipient;
212
Ken Chenb9fa2062018-11-13 21:51:13 +0800213TEST_F(ResolverTest, GetHostByName) {
Xiao Ma09b71022018-12-11 17:56:32 +0900214 constexpr char nonexistent_host_name[] = "nonexistent.example.com.";
215
216 test::DNSResponder dns;
217 StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.3"}});
218 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800219
220 const hostent* result;
Ken Chenb9fa2062018-11-13 21:51:13 +0800221 result = gethostbyname("nonexistent");
222 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, nonexistent_host_name));
223 ASSERT_TRUE(result == nullptr);
224 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
225
226 dns.clearQueries();
227 result = gethostbyname("hello");
Xiao Ma09b71022018-12-11 17:56:32 +0900228 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, kHelloExampleCom));
Ken Chenb9fa2062018-11-13 21:51:13 +0800229 ASSERT_FALSE(result == nullptr);
230 ASSERT_EQ(4, result->h_length);
231 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
232 EXPECT_EQ("1.2.3.3", ToString(result));
233 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800234}
235
lifr4e4a2e02019-01-29 16:53:51 +0800236TEST_F(ResolverTest, GetHostByName_cnames) {
237 constexpr char host_name[] = "host.example.com.";
238 size_t cnamecount = 0;
239 test::DNSResponder dns;
240
241 const std::vector<DnsRecord> records = {
242 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
243 {"a.example.com.", ns_type::ns_t_cname, "b.example.com."},
244 {"b.example.com.", ns_type::ns_t_cname, "c.example.com."},
245 {"c.example.com.", ns_type::ns_t_cname, "d.example.com."},
246 {"d.example.com.", ns_type::ns_t_cname, "e.example.com."},
247 {"e.example.com.", ns_type::ns_t_cname, host_name},
248 {host_name, ns_type::ns_t_a, "1.2.3.3"},
249 {host_name, ns_type::ns_t_aaaa, "2001:db8::42"},
250 };
251 StartDns(dns, records);
252 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
253
254 // using gethostbyname2() to resolve ipv4 hello.example.com. to 1.2.3.3
255 // Ensure the v4 address and cnames are correct
256 const hostent* result;
257 result = gethostbyname2("hello", AF_INET);
258 ASSERT_FALSE(result == nullptr);
259
260 for (int i = 0; result != nullptr && result->h_aliases[i] != nullptr; i++) {
261 std::string domain_name = records[i].host_name.substr(0, records[i].host_name.size() - 1);
262 EXPECT_EQ(result->h_aliases[i], domain_name);
263 cnamecount++;
264 }
265 // The size of "Non-cname type" record in DNS records is 2
266 ASSERT_EQ(cnamecount, records.size() - 2);
267 ASSERT_EQ(4, result->h_length);
268 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
269 EXPECT_EQ("1.2.3.3", ToString(result));
270 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
271 EXPECT_EQ(1U, dns.queries().size()) << dns.dumpQueries();
272
273 // using gethostbyname2() to resolve ipv6 hello.example.com. to 2001:db8::42
274 // Ensure the v6 address and cnames are correct
275 cnamecount = 0;
276 dns.clearQueries();
277 result = gethostbyname2("hello", AF_INET6);
278 for (unsigned i = 0; result != nullptr && result->h_aliases[i] != nullptr; i++) {
279 std::string domain_name = records[i].host_name.substr(0, records[i].host_name.size() - 1);
280 EXPECT_EQ(result->h_aliases[i], domain_name);
281 cnamecount++;
282 }
283 // The size of "Non-cname type" DNS record in records is 2
284 ASSERT_EQ(cnamecount, records.size() - 2);
285 ASSERT_FALSE(result == nullptr);
286 ASSERT_EQ(16, result->h_length);
287 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
288 EXPECT_EQ("2001:db8::42", ToString(result));
289 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
290}
291
292TEST_F(ResolverTest, GetHostByName_cnamesInfiniteLoop) {
293 test::DNSResponder dns;
294 const std::vector<DnsRecord> records = {
295 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
296 {"a.example.com.", ns_type::ns_t_cname, kHelloExampleCom},
297 };
298 StartDns(dns, records);
299 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
300
301 const hostent* result;
302 result = gethostbyname2("hello", AF_INET);
303 ASSERT_TRUE(result == nullptr);
304
305 dns.clearQueries();
306 result = gethostbyname2("hello", AF_INET6);
307 ASSERT_TRUE(result == nullptr);
308}
309
Ken Chenb9fa2062018-11-13 21:51:13 +0800310TEST_F(ResolverTest, GetHostByName_localhost) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800311 constexpr char name_camelcase[] = "LocalHost";
Ken Chenb9fa2062018-11-13 21:51:13 +0800312 constexpr char name_ip6_dot[] = "ip6-localhost.";
313 constexpr char name_ip6_fqdn[] = "ip6-localhost.example.com.";
314
315 // Add a dummy nameserver which shouldn't receive any queries
Xiao Ma09b71022018-12-11 17:56:32 +0900316 test::DNSResponder dns;
317 StartDns(dns, {});
318 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800319
320 // Expect no DNS queries; localhost is resolved via /etc/hosts
Xiao Ma09b71022018-12-11 17:56:32 +0900321 const hostent* result = gethostbyname(kLocalHost);
Ken Chenb9fa2062018-11-13 21:51:13 +0800322 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
323 ASSERT_FALSE(result == nullptr);
324 ASSERT_EQ(4, result->h_length);
325 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
Xiao Ma09b71022018-12-11 17:56:32 +0900326 EXPECT_EQ(kLocalHostAddr, ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +0800327 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
328
329 // Ensure the hosts file resolver ignores case of hostnames
330 result = gethostbyname(name_camelcase);
331 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
332 ASSERT_FALSE(result == nullptr);
333 ASSERT_EQ(4, result->h_length);
334 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
Xiao Ma09b71022018-12-11 17:56:32 +0900335 EXPECT_EQ(kLocalHostAddr, ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +0800336 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
337
338 // The hosts file also contains ip6-localhost, but gethostbyname() won't
chenbruce018fdb22019-06-12 18:08:04 +0800339 // return it. This would be easy to
Ken Chenb9fa2062018-11-13 21:51:13 +0800340 // change, but there's no point in changing the legacy behavior; new code
341 // should be calling getaddrinfo() anyway.
342 // So we check the legacy behavior, which results in amusing A-record
343 // lookups for ip6-localhost, with and without search domains appended.
344 dns.clearQueries();
Xiao Ma09b71022018-12-11 17:56:32 +0900345 result = gethostbyname(kIp6LocalHost);
Sehee Parkbbca0202018-11-16 10:53:16 +0900346 EXPECT_EQ(2U, dns.queries().size()) << dns.dumpQueries();
347 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, name_ip6_dot)) << dns.dumpQueries();
348 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, name_ip6_fqdn)) << dns.dumpQueries();
Ken Chenb9fa2062018-11-13 21:51:13 +0800349 ASSERT_TRUE(result == nullptr);
350
351 // Finally, use gethostbyname2() to resolve ip6-localhost to ::1 from
352 // the hosts file.
353 dns.clearQueries();
Xiao Ma09b71022018-12-11 17:56:32 +0900354 result = gethostbyname2(kIp6LocalHost, AF_INET6);
Ken Chenb9fa2062018-11-13 21:51:13 +0800355 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
356 ASSERT_FALSE(result == nullptr);
357 ASSERT_EQ(16, result->h_length);
358 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
Xiao Ma09b71022018-12-11 17:56:32 +0900359 EXPECT_EQ(kIp6LocalHostAddr, ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +0800360 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800361}
362
363TEST_F(ResolverTest, GetHostByName_numeric) {
364 // Add a dummy nameserver which shouldn't receive any queries
Xiao Ma09b71022018-12-11 17:56:32 +0900365 test::DNSResponder dns;
366 StartDns(dns, {});
367 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800368
369 // Numeric v4 address: expect no DNS queries
370 constexpr char numeric_v4[] = "192.168.0.1";
Ken Chenb9fa2062018-11-13 21:51:13 +0800371 const hostent* result = gethostbyname(numeric_v4);
Sehee Parkbbca0202018-11-16 10:53:16 +0900372 EXPECT_EQ(0U, dns.queries().size());
Ken Chenb9fa2062018-11-13 21:51:13 +0800373 ASSERT_FALSE(result == nullptr);
374 ASSERT_EQ(4, result->h_length); // v4
375 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
376 EXPECT_EQ(numeric_v4, ToString(result));
377 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
378
379 // gethostbyname() recognizes a v6 address, and fails with no DNS queries
380 constexpr char numeric_v6[] = "2001:db8::42";
381 dns.clearQueries();
382 result = gethostbyname(numeric_v6);
Sehee Parkbbca0202018-11-16 10:53:16 +0900383 EXPECT_EQ(0U, dns.queries().size());
Ken Chenb9fa2062018-11-13 21:51:13 +0800384 EXPECT_TRUE(result == nullptr);
385
386 // Numeric v6 address with gethostbyname2(): succeeds with no DNS queries
387 dns.clearQueries();
388 result = gethostbyname2(numeric_v6, AF_INET6);
Sehee Parkbbca0202018-11-16 10:53:16 +0900389 EXPECT_EQ(0U, dns.queries().size());
Ken Chenb9fa2062018-11-13 21:51:13 +0800390 ASSERT_FALSE(result == nullptr);
391 ASSERT_EQ(16, result->h_length); // v6
392 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
393 EXPECT_EQ(numeric_v6, ToString(result));
394 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
395
396 // Numeric v6 address with scope work with getaddrinfo(),
397 // but gethostbyname2() does not understand them; it issues two dns
398 // queries, then fails. This hardly ever happens, there's no point
399 // in fixing this. This test simply verifies the current (bogus)
400 // behavior to avoid further regressions (like crashes, or leaks).
401 constexpr char numeric_v6_scope[] = "fe80::1%lo";
402 dns.clearQueries();
403 result = gethostbyname2(numeric_v6_scope, AF_INET6);
Sehee Parkbbca0202018-11-16 10:53:16 +0900404 EXPECT_EQ(2U, dns.queries().size()); // OUCH!
Ken Chenb9fa2062018-11-13 21:51:13 +0800405 ASSERT_TRUE(result == nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800406}
407
408TEST_F(ResolverTest, BinderSerialization) {
Luke Huang5bd827c2019-03-14 16:10:04 +0800409 using android::net::IDnsResolver;
Ken Chenb9fa2062018-11-13 21:51:13 +0800410 std::vector<int> params_offsets = {
Luke Huang5bd827c2019-03-14 16:10:04 +0800411 IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY,
412 IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD,
413 IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES,
414 IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES,
415 IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC,
416 IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT,
Ken Chenb9fa2062018-11-13 21:51:13 +0800417 };
Bernie Innocentib102dd22018-12-04 14:57:48 +0900418 const int size = static_cast<int>(params_offsets.size());
Luke Huang5bd827c2019-03-14 16:10:04 +0800419 EXPECT_EQ(size, IDnsResolver::RESOLVER_PARAMS_COUNT);
Ken Chenb9fa2062018-11-13 21:51:13 +0800420 std::sort(params_offsets.begin(), params_offsets.end());
Bernie Innocentib102dd22018-12-04 14:57:48 +0900421 for (int i = 0; i < size; ++i) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800422 EXPECT_EQ(params_offsets[i], i);
423 }
424}
425
426TEST_F(ResolverTest, GetHostByName_Binder) {
Luke Huang5bd827c2019-03-14 16:10:04 +0800427 using android::net::IDnsResolver;
Ken Chenb9fa2062018-11-13 21:51:13 +0800428
429 std::vector<std::string> domains = { "example.com" };
430 std::vector<std::unique_ptr<test::DNSResponder>> dns;
431 std::vector<std::string> servers;
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900432 std::vector<DnsResponderClient::Mapping> mappings;
433 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(1, domains, &mappings));
434 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(4, mappings, &dns, &servers));
Ken Chenb9fa2062018-11-13 21:51:13 +0800435 ASSERT_EQ(1U, mappings.size());
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900436 const DnsResponderClient::Mapping& mapping = mappings[0];
Ken Chenb9fa2062018-11-13 21:51:13 +0800437
Xiao Ma09b71022018-12-11 17:56:32 +0900438 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains, kDefaultParams));
Ken Chenb9fa2062018-11-13 21:51:13 +0800439
440 const hostent* result = gethostbyname(mapping.host.c_str());
Bernie Innocentib102dd22018-12-04 14:57:48 +0900441 const size_t total_queries =
Luke Huangfde82482019-06-04 01:04:53 +0800442 std::accumulate(dns.begin(), dns.end(), 0, [&mapping](size_t total, auto& d) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800443 return total + GetNumQueriesForType(*d, ns_type::ns_t_a, mapping.entry.c_str());
444 });
445
446 EXPECT_LE(1U, total_queries);
447 ASSERT_FALSE(result == nullptr);
448 ASSERT_EQ(4, result->h_length);
449 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
450 EXPECT_EQ(mapping.ip4, ToString(result));
451 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
452
453 std::vector<std::string> res_servers;
454 std::vector<std::string> res_domains;
Mike Yu0a1c53d2018-11-26 13:26:21 +0900455 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +0900456 res_params res_params;
Ken Chenb9fa2062018-11-13 21:51:13 +0800457 std::vector<ResolverStats> res_stats;
Ken Chen92bed612018-12-22 21:46:55 +0800458 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +0800459 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
460 &res_tls_servers, &res_params, &res_stats,
461 &wait_for_pending_req_timeout_count));
Ken Chenb9fa2062018-11-13 21:51:13 +0800462 EXPECT_EQ(servers.size(), res_servers.size());
463 EXPECT_EQ(domains.size(), res_domains.size());
Mike Yu0a1c53d2018-11-26 13:26:21 +0900464 EXPECT_EQ(0U, res_tls_servers.size());
Luke Huang5bd827c2019-03-14 16:10:04 +0800465 ASSERT_EQ(static_cast<size_t>(IDnsResolver::RESOLVER_PARAMS_COUNT), kDefaultParams.size());
466 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY],
467 res_params.sample_validity);
468 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD],
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900469 res_params.success_threshold);
Luke Huang5bd827c2019-03-14 16:10:04 +0800470 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES], res_params.min_samples);
471 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES], res_params.max_samples);
472 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
Ken Chenb9fa2062018-11-13 21:51:13 +0800473 res_params.base_timeout_msec);
474 EXPECT_EQ(servers.size(), res_stats.size());
475
Bernie Innocenti0c067e42019-04-01 15:33:16 +0900476 EXPECT_THAT(res_servers, testing::UnorderedElementsAreArray(servers));
477 EXPECT_THAT(res_domains, testing::UnorderedElementsAreArray(domains));
Ken Chenb9fa2062018-11-13 21:51:13 +0800478}
479
480TEST_F(ResolverTest, GetAddrInfo) {
Xiao Ma09b71022018-12-11 17:56:32 +0900481 constexpr char listen_addr[] = "127.0.0.4";
482 constexpr char listen_addr2[] = "127.0.0.5";
483 constexpr char host_name[] = "howdy.example.com.";
Ken Chenb9fa2062018-11-13 21:51:13 +0800484
Xiao Ma09b71022018-12-11 17:56:32 +0900485 const std::vector<DnsRecord> records = {
486 {host_name, ns_type::ns_t_a, "1.2.3.4"},
487 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
488 };
489 test::DNSResponder dns(listen_addr);
490 test::DNSResponder dns2(listen_addr2);
491 StartDns(dns, records);
492 StartDns(dns2, records);
Ken Chenb9fa2062018-11-13 21:51:13 +0800493
Xiao Ma09b71022018-12-11 17:56:32 +0900494 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr}));
Ken Chenb9fa2062018-11-13 21:51:13 +0800495 dns.clearQueries();
496 dns2.clearQueries();
497
498 ScopedAddrinfo result = safe_getaddrinfo("howdy", nullptr, nullptr);
499 EXPECT_TRUE(result != nullptr);
500 size_t found = GetNumQueries(dns, host_name);
501 EXPECT_LE(1U, found);
502 // Could be A or AAAA
503 std::string result_str = ToString(result);
504 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
505 << ", result_str='" << result_str << "'";
506
507 // Verify that the name is cached.
508 size_t old_found = found;
509 result = safe_getaddrinfo("howdy", nullptr, nullptr);
510 EXPECT_TRUE(result != nullptr);
511 found = GetNumQueries(dns, host_name);
512 EXPECT_LE(1U, found);
513 EXPECT_EQ(old_found, found);
514 result_str = ToString(result);
515 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
516 << result_str;
517
518 // Change the DNS resolver, ensure that queries are still cached.
Xiao Ma09b71022018-12-11 17:56:32 +0900519 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr2}));
Ken Chenb9fa2062018-11-13 21:51:13 +0800520 dns.clearQueries();
521 dns2.clearQueries();
522
523 result = safe_getaddrinfo("howdy", nullptr, nullptr);
524 EXPECT_TRUE(result != nullptr);
525 found = GetNumQueries(dns, host_name);
526 size_t found2 = GetNumQueries(dns2, host_name);
527 EXPECT_EQ(0U, found);
528 EXPECT_LE(0U, found2);
529
530 // Could be A or AAAA
531 result_str = ToString(result);
532 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
533 << ", result_str='" << result_str << "'";
Ken Chenb9fa2062018-11-13 21:51:13 +0800534}
535
536TEST_F(ResolverTest, GetAddrInfoV4) {
Xiao Ma09b71022018-12-11 17:56:32 +0900537 test::DNSResponder dns;
538 StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.5"}});
539 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800540
Xiao Ma09b71022018-12-11 17:56:32 +0900541 const addrinfo hints = {.ai_family = AF_INET};
542 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
Ken Chenb9fa2062018-11-13 21:51:13 +0800543 EXPECT_TRUE(result != nullptr);
Xiao Ma09b71022018-12-11 17:56:32 +0900544 EXPECT_EQ(1U, GetNumQueries(dns, kHelloExampleCom));
Ken Chenb9fa2062018-11-13 21:51:13 +0800545 EXPECT_EQ("1.2.3.5", ToString(result));
546}
547
548TEST_F(ResolverTest, GetAddrInfo_localhost) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800549 // Add a dummy nameserver which shouldn't receive any queries
Xiao Ma09b71022018-12-11 17:56:32 +0900550 test::DNSResponder dns;
551 StartDns(dns, {});
552 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800553
Xiao Ma09b71022018-12-11 17:56:32 +0900554 ScopedAddrinfo result = safe_getaddrinfo(kLocalHost, nullptr, nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800555 EXPECT_TRUE(result != nullptr);
556 // Expect no DNS queries; localhost is resolved via /etc/hosts
557 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
Xiao Ma09b71022018-12-11 17:56:32 +0900558 EXPECT_EQ(kLocalHostAddr, ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +0800559
Xiao Ma09b71022018-12-11 17:56:32 +0900560 result = safe_getaddrinfo(kIp6LocalHost, nullptr, nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800561 EXPECT_TRUE(result != nullptr);
562 // Expect no DNS queries; ip6-localhost is resolved via /etc/hosts
563 EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
Xiao Ma09b71022018-12-11 17:56:32 +0900564 EXPECT_EQ(kIp6LocalHostAddr, ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +0800565}
566
Luke Huangd8ac4752019-06-18 17:05:47 +0800567TEST_F(ResolverTest, GetAddrInfo_InvalidSocketType) {
568 test::DNSResponder dns;
569 StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.5"}});
570 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
571
572 // TODO: Test other invalid socket types.
573 const addrinfo hints = {
574 .ai_family = AF_UNSPEC,
Luke Huangd8ac4752019-06-18 17:05:47 +0800575 .ai_socktype = SOCK_PACKET,
Nick Desaulnierscd6395a2019-10-11 09:15:24 -0700576 .ai_protocol = ANY,
Luke Huangd8ac4752019-06-18 17:05:47 +0800577 };
578 addrinfo* result = nullptr;
579 // This is a valid hint, but the query won't be sent because the socket type is
580 // not supported.
581 EXPECT_EQ(EAI_NODATA, getaddrinfo("hello", nullptr, &hints, &result));
582 ScopedAddrinfo result_cleanup(result);
583 EXPECT_EQ(nullptr, result);
584}
585
Ken Chen92bed612018-12-22 21:46:55 +0800586// Verify if the resolver correctly handle multiple queries simultaneously
587// step 1: set dns server#1 into deferred responding mode.
588// step 2: thread#1 query "hello.example.com." --> resolver send query to server#1.
589// step 3: thread#2 query "hello.example.com." --> resolver hold the request and wait for
590// response of previous pending query sent by thread#1.
591// step 4: thread#3 query "konbanha.example.com." --> resolver send query to server#3. Server
592// respond to resolver immediately.
593// step 5: check if server#1 get 1 query by thread#1, server#2 get 0 query, server#3 get 1 query.
594// step 6: resume dns server#1 to respond dns query in step#2.
595// step 7: thread#1 and #2 should get returned from DNS query after step#6. Also, check the
596// number of queries in server#2 is 0 to ensure thread#2 does not wake up unexpectedly
597// before signaled by thread#1.
598TEST_F(ResolverTest, GetAddrInfoV4_deferred_resp) {
599 const char* listen_addr1 = "127.0.0.9";
600 const char* listen_addr2 = "127.0.0.10";
601 const char* listen_addr3 = "127.0.0.11";
602 const char* listen_srv = "53";
603 const char* host_name_deferred = "hello.example.com.";
604 const char* host_name_normal = "konbanha.example.com.";
Mike Yufc125e42019-05-15 20:41:28 +0800605 test::DNSResponder dns1(listen_addr1, listen_srv, ns_rcode::ns_r_servfail);
606 test::DNSResponder dns2(listen_addr2, listen_srv, ns_rcode::ns_r_servfail);
607 test::DNSResponder dns3(listen_addr3, listen_srv, ns_rcode::ns_r_servfail);
Ken Chen92bed612018-12-22 21:46:55 +0800608 dns1.addMapping(host_name_deferred, ns_type::ns_t_a, "1.2.3.4");
609 dns2.addMapping(host_name_deferred, ns_type::ns_t_a, "1.2.3.4");
610 dns3.addMapping(host_name_normal, ns_type::ns_t_a, "1.2.3.5");
611 ASSERT_TRUE(dns1.startServer());
612 ASSERT_TRUE(dns2.startServer());
613 ASSERT_TRUE(dns3.startServer());
614 const std::vector<std::string> servers_for_t1 = {listen_addr1};
615 const std::vector<std::string> servers_for_t2 = {listen_addr2};
616 const std::vector<std::string> servers_for_t3 = {listen_addr3};
617 addrinfo hints = {.ai_family = AF_INET};
618 const std::vector<int> params = {300, 25, 8, 8, 5000};
619 bool t3_task_done = false;
620
621 dns1.setDeferredResp(true);
622 std::thread t1([&, this]() {
623 ASSERT_TRUE(
624 mDnsClient.SetResolversForNetwork(servers_for_t1, kDefaultSearchDomains, params));
625 ScopedAddrinfo result = safe_getaddrinfo(host_name_deferred, nullptr, &hints);
626 // t3's dns query should got returned first
627 EXPECT_TRUE(t3_task_done);
628 EXPECT_EQ(1U, GetNumQueries(dns1, host_name_deferred));
629 EXPECT_TRUE(result != nullptr);
630 EXPECT_EQ("1.2.3.4", ToString(result));
631 });
632
633 // ensuring t1 and t2 handler functions are processed in order
634 usleep(100 * 1000);
635 std::thread t2([&, this]() {
636 ASSERT_TRUE(
637 mDnsClient.SetResolversForNetwork(servers_for_t2, kDefaultSearchDomains, params));
638 ScopedAddrinfo result = safe_getaddrinfo(host_name_deferred, nullptr, &hints);
639 EXPECT_TRUE(t3_task_done);
640 EXPECT_EQ(0U, GetNumQueries(dns2, host_name_deferred));
641 EXPECT_TRUE(result != nullptr);
642 EXPECT_EQ("1.2.3.4", ToString(result));
643
644 std::vector<std::string> res_servers;
645 std::vector<std::string> res_domains;
646 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +0900647 res_params res_params;
Ken Chen92bed612018-12-22 21:46:55 +0800648 std::vector<ResolverStats> res_stats;
649 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +0800650 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers,
651 &res_domains, &res_tls_servers, &res_params, &res_stats,
652 &wait_for_pending_req_timeout_count));
Ken Chen92bed612018-12-22 21:46:55 +0800653 EXPECT_EQ(0, wait_for_pending_req_timeout_count);
654 });
655
656 // ensuring t2 and t3 handler functions are processed in order
657 usleep(100 * 1000);
658 std::thread t3([&, this]() {
659 ASSERT_TRUE(
660 mDnsClient.SetResolversForNetwork(servers_for_t3, kDefaultSearchDomains, params));
661 ScopedAddrinfo result = safe_getaddrinfo(host_name_normal, nullptr, &hints);
662 EXPECT_EQ(1U, GetNumQueries(dns1, host_name_deferred));
663 EXPECT_EQ(0U, GetNumQueries(dns2, host_name_deferred));
664 EXPECT_EQ(1U, GetNumQueries(dns3, host_name_normal));
665 EXPECT_TRUE(result != nullptr);
666 EXPECT_EQ("1.2.3.5", ToString(result));
667
668 t3_task_done = true;
669 dns1.setDeferredResp(false);
670 });
671 t3.join();
672 t1.join();
673 t2.join();
674}
675
lifr4e4a2e02019-01-29 16:53:51 +0800676TEST_F(ResolverTest, GetAddrInfo_cnames) {
677 constexpr char host_name[] = "host.example.com.";
678 test::DNSResponder dns;
679 const std::vector<DnsRecord> records = {
680 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
681 {"a.example.com.", ns_type::ns_t_cname, "b.example.com."},
682 {"b.example.com.", ns_type::ns_t_cname, "c.example.com."},
683 {"c.example.com.", ns_type::ns_t_cname, "d.example.com."},
684 {"d.example.com.", ns_type::ns_t_cname, "e.example.com."},
685 {"e.example.com.", ns_type::ns_t_cname, host_name},
686 {host_name, ns_type::ns_t_a, "1.2.3.3"},
687 {host_name, ns_type::ns_t_aaaa, "2001:db8::42"},
688 };
689 StartDns(dns, records);
690 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
691
692 addrinfo hints = {.ai_family = AF_INET};
693 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
694 EXPECT_TRUE(result != nullptr);
695 EXPECT_EQ("1.2.3.3", ToString(result));
696
697 dns.clearQueries();
698 hints = {.ai_family = AF_INET6};
699 result = safe_getaddrinfo("hello", nullptr, &hints);
700 EXPECT_TRUE(result != nullptr);
701 EXPECT_EQ("2001:db8::42", ToString(result));
702}
703
704TEST_F(ResolverTest, GetAddrInfo_cnamesNoIpAddress) {
705 test::DNSResponder dns;
706 const std::vector<DnsRecord> records = {
707 {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
708 };
709 StartDns(dns, records);
710 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
711
712 addrinfo hints = {.ai_family = AF_INET};
713 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
714 EXPECT_TRUE(result == nullptr);
715
716 dns.clearQueries();
717 hints = {.ai_family = AF_INET6};
718 result = safe_getaddrinfo("hello", nullptr, &hints);
719 EXPECT_TRUE(result == nullptr);
720}
721
722TEST_F(ResolverTest, GetAddrInfo_cnamesIllegalRdata) {
723 test::DNSResponder dns;
724 const std::vector<DnsRecord> records = {
725 {kHelloExampleCom, ns_type::ns_t_cname, ".!#?"},
726 };
727 StartDns(dns, records);
728 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
729
730 addrinfo hints = {.ai_family = AF_INET};
731 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
732 EXPECT_TRUE(result == nullptr);
733
734 dns.clearQueries();
735 hints = {.ai_family = AF_INET6};
736 result = safe_getaddrinfo("hello", nullptr, &hints);
737 EXPECT_TRUE(result == nullptr);
738}
739
Ken Chenb9fa2062018-11-13 21:51:13 +0800740TEST_F(ResolverTest, MultidomainResolution) {
Xiao Ma09b71022018-12-11 17:56:32 +0900741 constexpr char host_name[] = "nihao.example2.com.";
Ken Chenb9fa2062018-11-13 21:51:13 +0800742 std::vector<std::string> searchDomains = { "example1.com", "example2.com", "example3.com" };
Ken Chenb9fa2062018-11-13 21:51:13 +0800743
Xiao Ma09b71022018-12-11 17:56:32 +0900744 test::DNSResponder dns("127.0.0.6");
745 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.3"}});
746 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({"127.0.0.6"}, searchDomains));
747
Ken Chenb9fa2062018-11-13 21:51:13 +0800748 const hostent* result = gethostbyname("nihao");
Xiao Ma09b71022018-12-11 17:56:32 +0900749
Ken Chenb9fa2062018-11-13 21:51:13 +0800750 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
751 ASSERT_FALSE(result == nullptr);
752 ASSERT_EQ(4, result->h_length);
753 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
754 EXPECT_EQ("1.2.3.3", ToString(result));
755 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
Ken Chenb9fa2062018-11-13 21:51:13 +0800756}
757
758TEST_F(ResolverTest, GetAddrInfoV6_numeric) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800759 constexpr char host_name[] = "ohayou.example.com.";
760 constexpr char numeric_addr[] = "fe80::1%lo";
761
Xiao Ma09b71022018-12-11 17:56:32 +0900762 test::DNSResponder dns;
Ken Chenb9fa2062018-11-13 21:51:13 +0800763 dns.setResponseProbability(0.0);
Xiao Ma09b71022018-12-11 17:56:32 +0900764 StartDns(dns, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
765 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +0800766
767 addrinfo hints = {.ai_family = AF_INET6};
768 ScopedAddrinfo result = safe_getaddrinfo(numeric_addr, nullptr, &hints);
769 EXPECT_TRUE(result != nullptr);
770 EXPECT_EQ(numeric_addr, ToString(result));
771 EXPECT_TRUE(dns.queries().empty()); // Ensure no DNS queries were sent out
772
773 // Now try a non-numeric hostname query with the AI_NUMERICHOST flag set.
774 // We should fail without sending out a DNS query.
775 hints.ai_flags |= AI_NUMERICHOST;
776 result = safe_getaddrinfo(host_name, nullptr, &hints);
777 EXPECT_TRUE(result == nullptr);
778 EXPECT_TRUE(dns.queries().empty()); // Ensure no DNS queries were sent out
779}
780
781TEST_F(ResolverTest, GetAddrInfoV6_failing) {
Xiao Ma09b71022018-12-11 17:56:32 +0900782 constexpr char listen_addr0[] = "127.0.0.7";
783 constexpr char listen_addr1[] = "127.0.0.8";
Ken Chenb9fa2062018-11-13 21:51:13 +0800784 const char* host_name = "ohayou.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +0900785
786 test::DNSResponder dns0(listen_addr0);
787 test::DNSResponder dns1(listen_addr1);
Ken Chenb9fa2062018-11-13 21:51:13 +0800788 dns0.setResponseProbability(0.0);
Xiao Ma09b71022018-12-11 17:56:32 +0900789 StartDns(dns0, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
790 StartDns(dns1, {{host_name, ns_type::ns_t_aaaa, "2001:db8::6"}});
791
Ken Chenb9fa2062018-11-13 21:51:13 +0800792 std::vector<std::string> servers = { listen_addr0, listen_addr1 };
793 // <sample validity in s> <success threshold in percent> <min samples> <max samples>
794 int sample_count = 8;
795 const std::vector<int> params = { 300, 25, sample_count, sample_count };
Xiao Ma09b71022018-12-11 17:56:32 +0900796 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, kDefaultSearchDomains, params));
Ken Chenb9fa2062018-11-13 21:51:13 +0800797
798 // Repeatedly perform resolutions for non-existing domains until MAXNSSAMPLES resolutions have
799 // reached the dns0, which is set to fail. No more requests should then arrive at that server
800 // for the next sample_lifetime seconds.
801 // TODO: This approach is implementation-dependent, change once metrics reporting is available.
Xiao Ma09b71022018-12-11 17:56:32 +0900802 const addrinfo hints = {.ai_family = AF_INET6};
Bernie Innocentib102dd22018-12-04 14:57:48 +0900803 for (int i = 0; i < sample_count; ++i) {
Ken Chenb9fa2062018-11-13 21:51:13 +0800804 std::string domain = StringPrintf("nonexistent%d", i);
805 ScopedAddrinfo result = safe_getaddrinfo(domain.c_str(), nullptr, &hints);
806 }
807 // Due to 100% errors for all possible samples, the server should be ignored from now on and
808 // only the second one used for all following queries, until NSSAMPLE_VALIDITY is reached.
809 dns0.clearQueries();
810 dns1.clearQueries();
811 ScopedAddrinfo result = safe_getaddrinfo("ohayou", nullptr, &hints);
812 EXPECT_TRUE(result != nullptr);
813 EXPECT_EQ(0U, GetNumQueries(dns0, host_name));
814 EXPECT_EQ(1U, GetNumQueries(dns1, host_name));
815}
816
817TEST_F(ResolverTest, GetAddrInfoV6_nonresponsive) {
Xiao Ma09b71022018-12-11 17:56:32 +0900818 constexpr char listen_addr0[] = "127.0.0.7";
819 constexpr char listen_addr1[] = "127.0.0.8";
820 constexpr char listen_srv[] = "53";
821 constexpr char host_name1[] = "ohayou.example.com.";
822 constexpr char host_name2[] = "ciao.example.com.";
Luke Huang483cf332019-06-03 17:24:51 +0800823 const std::vector<std::string> defaultSearchDomain = {"example.com"};
824 // The minimal timeout is 1000ms, so we can't decrease timeout
825 // So reduce retry count.
826 const std::vector<int> reduceRetryParams = {
827 300, // sample validity in seconds
828 25, // success threshod in percent
829 8, 8, // {MIN,MAX}_SAMPLES
830 1000, // BASE_TIMEOUT_MSEC
831 1, // retry count
832 };
Xiao Ma09b71022018-12-11 17:56:32 +0900833 const std::vector<DnsRecord> records0 = {
834 {host_name1, ns_type::ns_t_aaaa, "2001:db8::5"},
835 {host_name2, ns_type::ns_t_aaaa, "2001:db8::5"},
836 };
837 const std::vector<DnsRecord> records1 = {
838 {host_name1, ns_type::ns_t_aaaa, "2001:db8::6"},
839 {host_name2, ns_type::ns_t_aaaa, "2001:db8::6"},
840 };
Ken Chenb9fa2062018-11-13 21:51:13 +0800841
842 // dns0 does not respond with 100% probability, while
843 // dns1 responds normally, at least initially.
Mike Yufc125e42019-05-15 20:41:28 +0800844 test::DNSResponder dns0(listen_addr0, listen_srv, static_cast<ns_rcode>(-1));
845 test::DNSResponder dns1(listen_addr1, listen_srv, static_cast<ns_rcode>(-1));
Ken Chenb9fa2062018-11-13 21:51:13 +0800846 dns0.setResponseProbability(0.0);
Xiao Ma09b71022018-12-11 17:56:32 +0900847 StartDns(dns0, records0);
848 StartDns(dns1, records1);
Luke Huang483cf332019-06-03 17:24:51 +0800849 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr0, listen_addr1}, defaultSearchDomain,
850 reduceRetryParams));
Ken Chenb9fa2062018-11-13 21:51:13 +0800851
Luke Huang483cf332019-06-03 17:24:51 +0800852 // Specify ai_socktype to make getaddrinfo will only query 1 time
853 const addrinfo hints = {.ai_family = AF_INET6, .ai_socktype = SOCK_STREAM};
Ken Chenb9fa2062018-11-13 21:51:13 +0800854
855 // dns0 will ignore the request, and we'll fallback to dns1 after the first
856 // retry.
857 ScopedAddrinfo result = safe_getaddrinfo(host_name1, nullptr, &hints);
858 EXPECT_TRUE(result != nullptr);
859 EXPECT_EQ(1U, GetNumQueries(dns0, host_name1));
860 EXPECT_EQ(1U, GetNumQueries(dns1, host_name1));
861
862 // Now make dns1 also ignore 100% requests... The resolve should alternate
Luke Huang483cf332019-06-03 17:24:51 +0800863 // queries between the nameservers and fail
Ken Chenb9fa2062018-11-13 21:51:13 +0800864 dns1.setResponseProbability(0.0);
865 addrinfo* result2 = nullptr;
866 EXPECT_EQ(EAI_NODATA, getaddrinfo(host_name2, nullptr, &hints, &result2));
867 EXPECT_EQ(nullptr, result2);
Luke Huang483cf332019-06-03 17:24:51 +0800868 EXPECT_EQ(1U, GetNumQueries(dns0, host_name2));
869 EXPECT_EQ(1U, GetNumQueries(dns1, host_name2));
Ken Chenb9fa2062018-11-13 21:51:13 +0800870}
871
872TEST_F(ResolverTest, GetAddrInfoV6_concurrent) {
Xiao Ma09b71022018-12-11 17:56:32 +0900873 constexpr char listen_addr0[] = "127.0.0.9";
874 constexpr char listen_addr1[] = "127.0.0.10";
875 constexpr char listen_addr2[] = "127.0.0.11";
876 constexpr char host_name[] = "konbanha.example.com.";
877
878 test::DNSResponder dns0(listen_addr0);
879 test::DNSResponder dns1(listen_addr1);
880 test::DNSResponder dns2(listen_addr2);
881 StartDns(dns0, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
882 StartDns(dns1, {{host_name, ns_type::ns_t_aaaa, "2001:db8::6"}});
883 StartDns(dns2, {{host_name, ns_type::ns_t_aaaa, "2001:db8::7"}});
884
Ken Chenb9fa2062018-11-13 21:51:13 +0800885 const std::vector<std::string> servers = { listen_addr0, listen_addr1, listen_addr2 };
886 std::vector<std::thread> threads(10);
887 for (std::thread& thread : threads) {
888 thread = std::thread([this, &servers]() {
889 unsigned delay = arc4random_uniform(1*1000*1000); // <= 1s
890 usleep(delay);
891 std::vector<std::string> serverSubset;
892 for (const auto& server : servers) {
893 if (arc4random_uniform(2)) {
894 serverSubset.push_back(server);
895 }
896 }
897 if (serverSubset.empty()) serverSubset = servers;
Xiao Ma09b71022018-12-11 17:56:32 +0900898 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(serverSubset));
899 const addrinfo hints = {.ai_family = AF_INET6};
Ken Chenb9fa2062018-11-13 21:51:13 +0800900 addrinfo* result = nullptr;
901 int rv = getaddrinfo("konbanha", nullptr, &hints, &result);
902 EXPECT_EQ(0, rv) << "error [" << rv << "] " << gai_strerror(rv);
903 if (result) {
904 freeaddrinfo(result);
905 result = nullptr;
906 }
907 });
908 }
909 for (std::thread& thread : threads) {
910 thread.join();
911 }
Ken Chen92bed612018-12-22 21:46:55 +0800912
913 std::vector<std::string> res_servers;
914 std::vector<std::string> res_domains;
915 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +0900916 res_params res_params;
Ken Chen92bed612018-12-22 21:46:55 +0800917 std::vector<ResolverStats> res_stats;
918 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +0800919 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
920 &res_tls_servers, &res_params, &res_stats,
921 &wait_for_pending_req_timeout_count));
Ken Chen92bed612018-12-22 21:46:55 +0800922 EXPECT_EQ(0, wait_for_pending_req_timeout_count);
Ken Chenb9fa2062018-11-13 21:51:13 +0800923}
924
Ken Chenb9fa2062018-11-13 21:51:13 +0800925TEST_F(ResolverTest, EmptySetup) {
Luke Huang5bd827c2019-03-14 16:10:04 +0800926 using android::net::IDnsResolver;
Ken Chenb9fa2062018-11-13 21:51:13 +0800927 std::vector<std::string> servers;
928 std::vector<std::string> domains;
Xiao Ma09b71022018-12-11 17:56:32 +0900929 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
Ken Chenb9fa2062018-11-13 21:51:13 +0800930 std::vector<std::string> res_servers;
931 std::vector<std::string> res_domains;
Mike Yu0a1c53d2018-11-26 13:26:21 +0900932 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +0900933 res_params res_params;
Ken Chenb9fa2062018-11-13 21:51:13 +0800934 std::vector<ResolverStats> res_stats;
Ken Chen92bed612018-12-22 21:46:55 +0800935 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +0800936 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
937 &res_tls_servers, &res_params, &res_stats,
938 &wait_for_pending_req_timeout_count));
Ken Chenb9fa2062018-11-13 21:51:13 +0800939 EXPECT_EQ(0U, res_servers.size());
940 EXPECT_EQ(0U, res_domains.size());
Mike Yu0a1c53d2018-11-26 13:26:21 +0900941 EXPECT_EQ(0U, res_tls_servers.size());
Luke Huang5bd827c2019-03-14 16:10:04 +0800942 ASSERT_EQ(static_cast<size_t>(IDnsResolver::RESOLVER_PARAMS_COUNT), kDefaultParams.size());
943 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY],
944 res_params.sample_validity);
945 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD],
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +0900946 res_params.success_threshold);
Luke Huang5bd827c2019-03-14 16:10:04 +0800947 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES], res_params.min_samples);
948 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES], res_params.max_samples);
949 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
Ken Chenb9fa2062018-11-13 21:51:13 +0800950 res_params.base_timeout_msec);
Luke Huang5bd827c2019-03-14 16:10:04 +0800951 EXPECT_EQ(kDefaultParams[IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT], res_params.retry_count);
Ken Chenb9fa2062018-11-13 21:51:13 +0800952}
953
954TEST_F(ResolverTest, SearchPathChange) {
Xiao Ma09b71022018-12-11 17:56:32 +0900955 constexpr char listen_addr[] = "127.0.0.13";
956 constexpr char host_name1[] = "test13.domain1.org.";
957 constexpr char host_name2[] = "test13.domain2.org.";
Ken Chenb9fa2062018-11-13 21:51:13 +0800958 std::vector<std::string> servers = { listen_addr };
959 std::vector<std::string> domains = { "domain1.org" };
Xiao Ma09b71022018-12-11 17:56:32 +0900960
961 const std::vector<DnsRecord> records = {
962 {host_name1, ns_type::ns_t_aaaa, "2001:db8::13"},
963 {host_name2, ns_type::ns_t_aaaa, "2001:db8::1:13"},
964 };
965 test::DNSResponder dns(listen_addr);
966 StartDns(dns, records);
967 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
Ken Chenb9fa2062018-11-13 21:51:13 +0800968
969 const addrinfo hints = {.ai_family = AF_INET6};
970 ScopedAddrinfo 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_name1));
974 EXPECT_EQ("2001:db8::13", ToString(result));
975
976 // Test that changing the domain search path on its own works.
977 domains = { "domain2.org" };
Xiao Ma09b71022018-12-11 17:56:32 +0900978 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
Ken Chenb9fa2062018-11-13 21:51:13 +0800979 dns.clearQueries();
980
981 result = safe_getaddrinfo("test13", nullptr, &hints);
982 EXPECT_TRUE(result != nullptr);
983 EXPECT_EQ(1U, dns.queries().size());
984 EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
985 EXPECT_EQ("2001:db8::1:13", ToString(result));
986}
987
Luke Huang2dac4382019-06-24 13:28:44 +0800988namespace {
989
990std::vector<std::string> getResolverDomains(android::net::IDnsResolver* dnsResolverService,
991 unsigned netId) {
992 std::vector<std::string> res_servers;
993 std::vector<std::string> res_domains;
994 std::vector<std::string> res_tls_servers;
995 res_params res_params;
996 std::vector<ResolverStats> res_stats;
997 int wait_for_pending_req_timeout_count;
998 GetResolverInfo(dnsResolverService, netId, &res_servers, &res_domains, &res_tls_servers,
999 &res_params, &res_stats, &wait_for_pending_req_timeout_count);
1000 return res_domains;
1001}
1002
1003} // namespace
1004
1005TEST_F(ResolverTest, SearchPathPrune) {
1006 constexpr size_t DUPLICATED_DOMAIN_NUM = 3;
1007 constexpr char listen_addr[] = "127.0.0.13";
1008 constexpr char domian_name1[] = "domain13.org.";
1009 constexpr char domian_name2[] = "domain14.org.";
1010 constexpr char host_name1[] = "test13.domain13.org.";
1011 constexpr char host_name2[] = "test14.domain14.org.";
1012 std::vector<std::string> servers = {listen_addr};
1013
1014 std::vector<std::string> testDomains1;
1015 std::vector<std::string> testDomains2;
1016 // Domain length should be <= 255
1017 // Max number of domains in search path is 6
1018 for (size_t i = 0; i < MAXDNSRCH + 1; i++) {
1019 // Fill up with invalid domain
1020 testDomains1.push_back(std::string(300, i + '0'));
1021 // Fill up with valid but duplicated domain
1022 testDomains2.push_back(StringPrintf("domain%zu.org", i % DUPLICATED_DOMAIN_NUM));
1023 }
1024
1025 // Add valid domain used for query.
1026 testDomains1.push_back(domian_name1);
1027
1028 // Add valid domain twice used for query.
1029 testDomains2.push_back(domian_name2);
1030 testDomains2.push_back(domian_name2);
1031
1032 const std::vector<DnsRecord> records = {
1033 {host_name1, ns_type::ns_t_aaaa, "2001:db8::13"},
1034 {host_name2, ns_type::ns_t_aaaa, "2001:db8::1:13"},
1035 };
1036 test::DNSResponder dns(listen_addr);
1037 StartDns(dns, records);
1038 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, testDomains1));
1039
1040 const addrinfo hints = {.ai_family = AF_INET6};
1041 ScopedAddrinfo result = safe_getaddrinfo("test13", nullptr, &hints);
1042
1043 EXPECT_TRUE(result != nullptr);
1044
1045 EXPECT_EQ(1U, dns.queries().size());
1046 EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
1047 EXPECT_EQ("2001:db8::13", ToString(result));
1048
1049 const auto& res_domains1 = getResolverDomains(mDnsClient.resolvService(), TEST_NETID);
1050 // Expect 1 valid domain, invalid domains are removed.
1051 ASSERT_EQ(1U, res_domains1.size());
1052 EXPECT_EQ(domian_name1, res_domains1[0]);
1053
1054 dns.clearQueries();
1055
1056 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, testDomains2));
1057
1058 result = safe_getaddrinfo("test14", nullptr, &hints);
1059 EXPECT_TRUE(result != nullptr);
1060
1061 // (3 domains * 2 retries) + 1 success query = 7
1062 EXPECT_EQ(7U, dns.queries().size());
1063 EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
1064 EXPECT_EQ("2001:db8::1:13", ToString(result));
1065
1066 const auto& res_domains2 = getResolverDomains(mDnsClient.resolvService(), TEST_NETID);
1067 // Expect 4 valid domain, duplicate domains are removed.
1068 EXPECT_EQ(DUPLICATED_DOMAIN_NUM + 1U, res_domains2.size());
1069 EXPECT_THAT(
1070 std::vector<std::string>({"domain0.org", "domain1.org", "domain2.org", domian_name2}),
1071 testing::ElementsAreArray(res_domains2));
1072}
1073
Mike Yu0a1c53d2018-11-26 13:26:21 +09001074// If we move this function to dns_responder_client, it will complicate the dependency need of
1075// dns_tls_frontend.h.
1076static void setupTlsServers(const std::vector<std::string>& servers,
waynema0e73c2e2019-07-31 15:04:08 +08001077 std::vector<std::unique_ptr<test::DnsTlsFrontend>>* tls) {
Xiao Ma09b71022018-12-11 17:56:32 +09001078 constexpr char listen_udp[] = "53";
1079 constexpr char listen_tls[] = "853";
Mike Yu0a1c53d2018-11-26 13:26:21 +09001080
1081 for (const auto& server : servers) {
1082 auto t = std::make_unique<test::DnsTlsFrontend>(server, listen_tls, server, listen_udp);
1083 t = std::make_unique<test::DnsTlsFrontend>(server, listen_tls, server, listen_udp);
1084 t->startServer();
Mike Yu0a1c53d2018-11-26 13:26:21 +09001085 tls->push_back(std::move(t));
1086 }
1087}
1088
Mike Yu0a1c53d2018-11-26 13:26:21 +09001089TEST_F(ResolverTest, MaxServerPrune_Binder) {
Mike Yu0a1c53d2018-11-26 13:26:21 +09001090 std::vector<std::string> domains;
1091 std::vector<std::unique_ptr<test::DNSResponder>> dns;
1092 std::vector<std::unique_ptr<test::DnsTlsFrontend>> tls;
1093 std::vector<std::string> servers;
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001094 std::vector<DnsResponderClient::Mapping> mappings;
Mike Yu0a1c53d2018-11-26 13:26:21 +09001095
1096 for (unsigned i = 0; i < MAXDNSRCH + 1; i++) {
1097 domains.push_back(StringPrintf("example%u.com", i));
1098 }
Bernie Innocentia5c7b7b2019-01-17 21:28:24 +09001099 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(1, domains, &mappings));
1100 ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(MAXNS + 1, mappings, &dns, &servers));
waynema0e73c2e2019-07-31 15:04:08 +08001101 ASSERT_NO_FATAL_FAILURE(setupTlsServers(servers, &tls));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001102
waynema0e73c2e2019-07-31 15:04:08 +08001103 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, domains, kDefaultParams,
1104 kDefaultPrivateDnsHostName));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001105
Mike Yu383855b2019-01-15 17:53:27 +08001106 // If the private DNS validation hasn't completed yet before backend DNS servers stop,
1107 // TLS servers will get stuck in handleOneRequest(), which causes this test stuck in
1108 // ~DnsTlsFrontend() because the TLS server loop threads can't be terminated.
1109 // So, wait for private DNS validation done before stopping backend DNS servers.
1110 for (int i = 0; i < MAXNS; i++) {
chenbruceaff85842019-05-31 15:46:42 +08001111 LOG(INFO) << "Waiting for private DNS validation on " << tls[i]->listen_address() << ".";
Mike Yu724f77d2019-08-16 11:14:50 +08001112 EXPECT_TRUE(WaitForPrivateDnsValidation(tls[i]->listen_address(), true));
chenbruceaff85842019-05-31 15:46:42 +08001113 LOG(INFO) << "private DNS validation on " << tls[i]->listen_address() << " done.";
Mike Yu383855b2019-01-15 17:53:27 +08001114 }
1115
Mike Yu0a1c53d2018-11-26 13:26:21 +09001116 std::vector<std::string> res_servers;
1117 std::vector<std::string> res_domains;
1118 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +09001119 res_params res_params;
Mike Yu0a1c53d2018-11-26 13:26:21 +09001120 std::vector<ResolverStats> res_stats;
Ken Chen92bed612018-12-22 21:46:55 +08001121 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +08001122 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
1123 &res_tls_servers, &res_params, &res_stats,
1124 &wait_for_pending_req_timeout_count));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001125
1126 // Check the size of the stats and its contents.
1127 EXPECT_EQ(static_cast<size_t>(MAXNS), res_servers.size());
1128 EXPECT_EQ(static_cast<size_t>(MAXNS), res_tls_servers.size());
1129 EXPECT_EQ(static_cast<size_t>(MAXDNSRCH), res_domains.size());
1130 EXPECT_TRUE(std::equal(servers.begin(), servers.begin() + MAXNS, res_servers.begin()));
1131 EXPECT_TRUE(std::equal(servers.begin(), servers.begin() + MAXNS, res_tls_servers.begin()));
1132 EXPECT_TRUE(std::equal(domains.begin(), domains.begin() + MAXDNSRCH, res_domains.begin()));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001133}
1134
1135TEST_F(ResolverTest, ResolverStats) {
Xiao Ma09b71022018-12-11 17:56:32 +09001136 constexpr char listen_addr1[] = "127.0.0.4";
1137 constexpr char listen_addr2[] = "127.0.0.5";
1138 constexpr char listen_addr3[] = "127.0.0.6";
Mike Yu0a1c53d2018-11-26 13:26:21 +09001139
1140 // Set server 1 timeout.
Mike Yufc125e42019-05-15 20:41:28 +08001141 test::DNSResponder dns1(listen_addr1, "53", static_cast<ns_rcode>(-1));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001142 dns1.setResponseProbability(0.0);
1143 ASSERT_TRUE(dns1.startServer());
1144
1145 // Set server 2 responding server failure.
Xiao Ma09b71022018-12-11 17:56:32 +09001146 test::DNSResponder dns2(listen_addr2);
Mike Yu0a1c53d2018-11-26 13:26:21 +09001147 dns2.setResponseProbability(0.0);
1148 ASSERT_TRUE(dns2.startServer());
1149
1150 // Set server 3 workable.
Xiao Ma09b71022018-12-11 17:56:32 +09001151 test::DNSResponder dns3(listen_addr3);
1152 dns3.addMapping(kHelloExampleCom, ns_type::ns_t_a, "1.2.3.4");
Mike Yu0a1c53d2018-11-26 13:26:21 +09001153 ASSERT_TRUE(dns3.startServer());
1154
1155 std::vector<std::string> servers = {listen_addr1, listen_addr2, listen_addr3};
Xiao Ma09b71022018-12-11 17:56:32 +09001156 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001157
1158 dns3.clearQueries();
Xiao Ma09b71022018-12-11 17:56:32 +09001159 const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
Mike Yu0a1c53d2018-11-26 13:26:21 +09001160 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
Xiao Ma09b71022018-12-11 17:56:32 +09001161 size_t found = GetNumQueries(dns3, kHelloExampleCom);
Mike Yu0a1c53d2018-11-26 13:26:21 +09001162 EXPECT_LE(1U, found);
1163 std::string result_str = ToString(result);
1164 EXPECT_TRUE(result_str == "1.2.3.4") << ", result_str='" << result_str << "'";
1165
1166 std::vector<std::string> res_servers;
1167 std::vector<std::string> res_domains;
1168 std::vector<std::string> res_tls_servers;
Bernie Innocenti758005f2019-02-19 18:08:36 +09001169 res_params res_params;
Mike Yu0a1c53d2018-11-26 13:26:21 +09001170 std::vector<ResolverStats> res_stats;
Ken Chen92bed612018-12-22 21:46:55 +08001171 int wait_for_pending_req_timeout_count;
Luke Huangfde82482019-06-04 01:04:53 +08001172 ASSERT_TRUE(GetResolverInfo(mDnsClient.resolvService(), TEST_NETID, &res_servers, &res_domains,
1173 &res_tls_servers, &res_params, &res_stats,
1174 &wait_for_pending_req_timeout_count));
Mike Yu0a1c53d2018-11-26 13:26:21 +09001175
1176 EXPECT_EQ(1, res_stats[0].timeouts);
1177 EXPECT_EQ(1, res_stats[1].errors);
1178 EXPECT_EQ(1, res_stats[2].successes);
Mike Yu0a1c53d2018-11-26 13:26:21 +09001179}
1180
Ken Chenb9fa2062018-11-13 21:51:13 +08001181// Test what happens if the specified TLS server is nonexistent.
1182TEST_F(ResolverTest, GetHostByName_TlsMissing) {
Xiao Ma09b71022018-12-11 17:56:32 +09001183 constexpr char listen_addr[] = "127.0.0.3";
1184 constexpr char host_name[] = "tlsmissing.example.com.";
1185
1186 test::DNSResponder dns;
1187 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.3"}});
Ken Chenb9fa2062018-11-13 21:51:13 +08001188 std::vector<std::string> servers = { listen_addr };
1189
1190 // There's nothing listening on this address, so validation will either fail or
1191 /// hang. Either way, queries will continue to flow to the DNSResponder.
waynema0e73c2e2019-07-31 15:04:08 +08001192 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
Ken Chenb9fa2062018-11-13 21:51:13 +08001193
1194 const hostent* result;
1195
1196 result = gethostbyname("tlsmissing");
1197 ASSERT_FALSE(result == nullptr);
1198 EXPECT_EQ("1.2.3.3", ToString(result));
1199
1200 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001201 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001202}
1203
1204// Test what happens if the specified TLS server replies with garbage.
1205TEST_F(ResolverTest, GetHostByName_TlsBroken) {
Xiao Ma09b71022018-12-11 17:56:32 +09001206 constexpr char listen_addr[] = "127.0.0.3";
1207 constexpr char host_name1[] = "tlsbroken1.example.com.";
1208 constexpr char host_name2[] = "tlsbroken2.example.com.";
1209 const std::vector<DnsRecord> records = {
1210 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1211 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1212 };
1213
1214 test::DNSResponder dns;
1215 StartDns(dns, records);
Ken Chenb9fa2062018-11-13 21:51:13 +08001216 std::vector<std::string> servers = { listen_addr };
1217
1218 // Bind the specified private DNS socket but don't respond to any client sockets yet.
1219 int s = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP);
1220 ASSERT_TRUE(s >= 0);
1221 struct sockaddr_in tlsServer = {
1222 .sin_family = AF_INET,
1223 .sin_port = htons(853),
1224 };
1225 ASSERT_TRUE(inet_pton(AF_INET, listen_addr, &tlsServer.sin_addr));
1226 ASSERT_TRUE(enableSockopt(s, SOL_SOCKET, SO_REUSEPORT).ok());
1227 ASSERT_TRUE(enableSockopt(s, SOL_SOCKET, SO_REUSEADDR).ok());
1228 ASSERT_FALSE(bind(s, reinterpret_cast<struct sockaddr*>(&tlsServer), sizeof(tlsServer)));
1229 ASSERT_FALSE(listen(s, 1));
1230
1231 // Trigger TLS validation.
waynema0e73c2e2019-07-31 15:04:08 +08001232 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
Ken Chenb9fa2062018-11-13 21:51:13 +08001233
1234 struct sockaddr_storage cliaddr;
1235 socklen_t sin_size = sizeof(cliaddr);
1236 int new_fd = accept4(s, reinterpret_cast<struct sockaddr *>(&cliaddr), &sin_size, SOCK_CLOEXEC);
1237 ASSERT_TRUE(new_fd > 0);
1238
1239 // We've received the new file descriptor but not written to it or closed, so the
1240 // validation is still pending. Queries should still flow correctly because the
1241 // server is not used until validation succeeds.
1242 const hostent* result;
1243 result = gethostbyname("tlsbroken1");
1244 ASSERT_FALSE(result == nullptr);
1245 EXPECT_EQ("1.2.3.1", ToString(result));
1246
1247 // Now we cause the validation to fail.
1248 std::string garbage = "definitely not a valid TLS ServerHello";
1249 write(new_fd, garbage.data(), garbage.size());
1250 close(new_fd);
1251
1252 // Validation failure shouldn't interfere with lookups, because lookups won't be sent
1253 // to the TLS server unless validation succeeds.
1254 result = gethostbyname("tlsbroken2");
1255 ASSERT_FALSE(result == nullptr);
1256 EXPECT_EQ("1.2.3.2", ToString(result));
1257
1258 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001259 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001260 close(s);
1261}
1262
1263TEST_F(ResolverTest, GetHostByName_Tls) {
Xiao Ma09b71022018-12-11 17:56:32 +09001264 constexpr char listen_addr[] = "127.0.0.3";
1265 constexpr char listen_udp[] = "53";
1266 constexpr char listen_tls[] = "853";
1267 constexpr char host_name1[] = "tls1.example.com.";
1268 constexpr char host_name2[] = "tls2.example.com.";
1269 constexpr char host_name3[] = "tls3.example.com.";
1270 const std::vector<DnsRecord> records = {
1271 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1272 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1273 {host_name3, ns_type::ns_t_a, "1.2.3.3"},
1274 };
1275
1276 test::DNSResponder dns;
1277 StartDns(dns, records);
Ken Chenb9fa2062018-11-13 21:51:13 +08001278 std::vector<std::string> servers = { listen_addr };
1279
1280 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1281 ASSERT_TRUE(tls.startServer());
waynema0e73c2e2019-07-31 15:04:08 +08001282 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
Mike Yu724f77d2019-08-16 11:14:50 +08001283 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
Ken Chenb9fa2062018-11-13 21:51:13 +08001284
Mike Yu724f77d2019-08-16 11:14:50 +08001285 const hostent* result = gethostbyname("tls1");
Ken Chenb9fa2062018-11-13 21:51:13 +08001286 ASSERT_FALSE(result == nullptr);
1287 EXPECT_EQ("1.2.3.1", ToString(result));
1288
1289 // Wait for query to get counted.
1290 EXPECT_TRUE(tls.waitForQueries(2, 5000));
1291
1292 // Stop the TLS server. Since we're in opportunistic mode, queries will
1293 // fall back to the locally-assigned (clear text) nameservers.
1294 tls.stopServer();
1295
1296 dns.clearQueries();
1297 result = gethostbyname("tls2");
1298 EXPECT_FALSE(result == nullptr);
1299 EXPECT_EQ("1.2.3.2", ToString(result));
1300 const auto queries = dns.queries();
1301 EXPECT_EQ(1U, queries.size());
1302 EXPECT_EQ("tls2.example.com.", queries[0].first);
1303 EXPECT_EQ(ns_t_a, queries[0].second);
1304
1305 // Reset the resolvers without enabling TLS. Queries should still be routed
1306 // to the UDP endpoint.
Xiao Ma09b71022018-12-11 17:56:32 +09001307 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001308
1309 result = gethostbyname("tls3");
1310 ASSERT_FALSE(result == nullptr);
1311 EXPECT_EQ("1.2.3.3", ToString(result));
Ken Chenb9fa2062018-11-13 21:51:13 +08001312}
1313
Ken Chenb9fa2062018-11-13 21:51:13 +08001314TEST_F(ResolverTest, GetHostByName_TlsFailover) {
Xiao Ma09b71022018-12-11 17:56:32 +09001315 constexpr char listen_addr1[] = "127.0.0.3";
1316 constexpr char listen_addr2[] = "127.0.0.4";
1317 constexpr char listen_udp[] = "53";
1318 constexpr char listen_tls[] = "853";
1319 constexpr char host_name1[] = "tlsfailover1.example.com.";
1320 constexpr char host_name2[] = "tlsfailover2.example.com.";
1321 const std::vector<DnsRecord> records1 = {
1322 {host_name1, ns_type::ns_t_a, "1.2.3.1"},
1323 {host_name2, ns_type::ns_t_a, "1.2.3.2"},
1324 };
1325 const std::vector<DnsRecord> records2 = {
1326 {host_name1, ns_type::ns_t_a, "1.2.3.3"},
1327 {host_name2, ns_type::ns_t_a, "1.2.3.4"},
1328 };
1329
1330 test::DNSResponder dns1(listen_addr1);
1331 test::DNSResponder dns2(listen_addr2);
1332 StartDns(dns1, records1);
1333 StartDns(dns2, records2);
1334
Ken Chenb9fa2062018-11-13 21:51:13 +08001335 std::vector<std::string> servers = { listen_addr1, listen_addr2 };
1336
1337 test::DnsTlsFrontend tls1(listen_addr1, listen_tls, listen_addr1, listen_udp);
1338 test::DnsTlsFrontend tls2(listen_addr2, listen_tls, listen_addr2, listen_udp);
1339 ASSERT_TRUE(tls1.startServer());
1340 ASSERT_TRUE(tls2.startServer());
waynema0e73c2e2019-07-31 15:04:08 +08001341 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
1342 kDefaultPrivateDnsHostName));
Mike Yu724f77d2019-08-16 11:14:50 +08001343 EXPECT_TRUE(WaitForPrivateDnsValidation(tls1.listen_address(), true));
1344 EXPECT_TRUE(WaitForPrivateDnsValidation(tls2.listen_address(), true));
Ken Chenb9fa2062018-11-13 21:51:13 +08001345
Mike Yu724f77d2019-08-16 11:14:50 +08001346 const hostent* result = gethostbyname("tlsfailover1");
Ken Chenb9fa2062018-11-13 21:51:13 +08001347 ASSERT_FALSE(result == nullptr);
1348 EXPECT_EQ("1.2.3.1", ToString(result));
1349
1350 // Wait for query to get counted.
1351 EXPECT_TRUE(tls1.waitForQueries(2, 5000));
1352 // No new queries should have reached tls2.
1353 EXPECT_EQ(1, tls2.queries());
1354
1355 // Stop tls1. Subsequent queries should attempt to reach tls1, fail, and retry to tls2.
1356 tls1.stopServer();
1357
1358 result = gethostbyname("tlsfailover2");
1359 EXPECT_EQ("1.2.3.4", ToString(result));
1360
1361 // Wait for query to get counted.
1362 EXPECT_TRUE(tls2.waitForQueries(2, 5000));
1363
1364 // No additional queries should have reached the insecure servers.
1365 EXPECT_EQ(2U, dns1.queries().size());
1366 EXPECT_EQ(2U, dns2.queries().size());
1367
1368 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001369 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Ken Chenb9fa2062018-11-13 21:51:13 +08001370}
1371
1372TEST_F(ResolverTest, GetHostByName_BadTlsName) {
Xiao Ma09b71022018-12-11 17:56:32 +09001373 constexpr char listen_addr[] = "127.0.0.3";
1374 constexpr char listen_udp[] = "53";
1375 constexpr char listen_tls[] = "853";
1376 constexpr char host_name[] = "badtlsname.example.com.";
1377
1378 test::DNSResponder dns;
1379 StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.1"}});
Ken Chenb9fa2062018-11-13 21:51:13 +08001380 std::vector<std::string> servers = { listen_addr };
1381
1382 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1383 ASSERT_TRUE(tls.startServer());
Xiao Ma09b71022018-12-11 17:56:32 +09001384 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
waynema0e73c2e2019-07-31 15:04:08 +08001385 kDefaultIncorrectPrivateDnsHostName));
Ken Chenb9fa2062018-11-13 21:51:13 +08001386
waynema0e73c2e2019-07-31 15:04:08 +08001387 // The TLS handshake would fail because the name of TLS server doesn't
1388 // match with TLS server's certificate.
Mike Yu724f77d2019-08-16 11:14:50 +08001389 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), false));
Ken Chenb9fa2062018-11-13 21:51:13 +08001390
1391 // The query should fail hard, because a name was specified.
1392 EXPECT_EQ(nullptr, gethostbyname("badtlsname"));
1393
1394 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001395 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001396}
1397
1398TEST_F(ResolverTest, GetAddrInfo_Tls) {
Xiao Ma09b71022018-12-11 17:56:32 +09001399 constexpr char listen_addr[] = "127.0.0.3";
1400 constexpr char listen_udp[] = "53";
1401 constexpr char listen_tls[] = "853";
1402 constexpr char host_name[] = "addrinfotls.example.com.";
1403 const std::vector<DnsRecord> records = {
1404 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1405 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1406 };
1407
1408 test::DNSResponder dns;
1409 StartDns(dns, records);
Ken Chenb9fa2062018-11-13 21:51:13 +08001410 std::vector<std::string> servers = { listen_addr };
1411
1412 test::DnsTlsFrontend tls(listen_addr, listen_tls, listen_addr, listen_udp);
1413 ASSERT_TRUE(tls.startServer());
waynema0e73c2e2019-07-31 15:04:08 +08001414 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
1415 kDefaultPrivateDnsHostName));
Mike Yu724f77d2019-08-16 11:14:50 +08001416 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
Ken Chenb9fa2062018-11-13 21:51:13 +08001417
1418 dns.clearQueries();
1419 ScopedAddrinfo result = safe_getaddrinfo("addrinfotls", nullptr, nullptr);
1420 EXPECT_TRUE(result != nullptr);
1421 size_t found = GetNumQueries(dns, host_name);
1422 EXPECT_LE(1U, found);
1423 // Could be A or AAAA
1424 std::string result_str = ToString(result);
1425 EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
1426 << ", result_str='" << result_str << "'";
1427 // Wait for both A and AAAA queries to get counted.
1428 EXPECT_TRUE(tls.waitForQueries(3, 5000));
1429
1430 // Clear TLS bit.
Xiao Ma09b71022018-12-11 17:56:32 +09001431 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
Ken Chenb9fa2062018-11-13 21:51:13 +08001432}
1433
1434TEST_F(ResolverTest, TlsBypass) {
1435 const char OFF[] = "off";
1436 const char OPPORTUNISTIC[] = "opportunistic";
1437 const char STRICT[] = "strict";
1438
1439 const char GETHOSTBYNAME[] = "gethostbyname";
1440 const char GETADDRINFO[] = "getaddrinfo";
1441 const char GETADDRINFOFORNET[] = "getaddrinfofornet";
1442
1443 const unsigned BYPASS_NETID = NETID_USE_LOCAL_NAMESERVERS | TEST_NETID;
1444
Ken Chenb9fa2062018-11-13 21:51:13 +08001445 const char ADDR4[] = "192.0.2.1";
1446 const char ADDR6[] = "2001:db8::1";
1447
1448 const char cleartext_addr[] = "127.0.0.53";
1449 const char cleartext_port[] = "53";
1450 const char tls_port[] = "853";
1451 const std::vector<std::string> servers = { cleartext_addr };
1452
Xiao Ma09b71022018-12-11 17:56:32 +09001453 test::DNSResponder dns(cleartext_addr);
Ken Chenb9fa2062018-11-13 21:51:13 +08001454 ASSERT_TRUE(dns.startServer());
1455
1456 test::DnsTlsFrontend tls(cleartext_addr, tls_port, cleartext_addr, cleartext_port);
Mike Yudd4ac2d2019-05-31 16:52:11 +08001457 ASSERT_TRUE(tls.startServer());
Ken Chenb9fa2062018-11-13 21:51:13 +08001458
1459 struct TestConfig {
1460 const std::string mode;
1461 const bool withWorkingTLS;
1462 const std::string method;
1463
1464 std::string asHostName() const {
1465 return StringPrintf("%s.%s.%s.",
1466 mode.c_str(),
1467 withWorkingTLS ? "tlsOn" : "tlsOff",
1468 method.c_str());
1469 }
1470 } testConfigs[]{
Ken Chenb9fa2062018-11-13 21:51:13 +08001471 {OFF, true, GETHOSTBYNAME},
1472 {OPPORTUNISTIC, true, GETHOSTBYNAME},
1473 {STRICT, true, GETHOSTBYNAME},
Ken Chenb9fa2062018-11-13 21:51:13 +08001474 {OFF, true, GETADDRINFO},
1475 {OPPORTUNISTIC, true, GETADDRINFO},
1476 {STRICT, true, GETADDRINFO},
Ken Chenb9fa2062018-11-13 21:51:13 +08001477 {OFF, true, GETADDRINFOFORNET},
1478 {OPPORTUNISTIC, true, GETADDRINFOFORNET},
1479 {STRICT, true, GETADDRINFOFORNET},
Mike Yudd4ac2d2019-05-31 16:52:11 +08001480 {OFF, false, GETHOSTBYNAME},
1481 {OPPORTUNISTIC, false, GETHOSTBYNAME},
1482 {STRICT, false, GETHOSTBYNAME},
1483 {OFF, false, GETADDRINFO},
1484 {OPPORTUNISTIC, false, GETADDRINFO},
1485 {STRICT, false, GETADDRINFO},
1486 {OFF, false, GETADDRINFOFORNET},
1487 {OPPORTUNISTIC, false, GETADDRINFOFORNET},
1488 {STRICT, false, GETADDRINFOFORNET},
Ken Chenb9fa2062018-11-13 21:51:13 +08001489 };
1490
1491 for (const auto& config : testConfigs) {
1492 const std::string testHostName = config.asHostName();
1493 SCOPED_TRACE(testHostName);
1494
1495 // Don't tempt test bugs due to caching.
1496 const char* host_name = testHostName.c_str();
1497 dns.addMapping(host_name, ns_type::ns_t_a, ADDR4);
1498 dns.addMapping(host_name, ns_type::ns_t_aaaa, ADDR6);
1499
Mike Yudd4ac2d2019-05-31 16:52:11 +08001500 if (config.withWorkingTLS) {
1501 if (!tls.running()) {
1502 ASSERT_TRUE(tls.startServer());
1503 }
1504 } else {
1505 if (tls.running()) {
1506 ASSERT_TRUE(tls.stopServer());
1507 }
1508 }
Ken Chenb9fa2062018-11-13 21:51:13 +08001509
1510 if (config.mode == OFF) {
Xiao Ma09b71022018-12-11 17:56:32 +09001511 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, kDefaultSearchDomains,
1512 kDefaultParams));
Ken Chenb9fa2062018-11-13 21:51:13 +08001513 } else if (config.mode == OPPORTUNISTIC) {
Xiao Ma09b71022018-12-11 17:56:32 +09001514 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
waynema0e73c2e2019-07-31 15:04:08 +08001515 kDefaultParams, ""));
Mike Yu724f77d2019-08-16 11:14:50 +08001516
1517 // Wait for the validation event. If the server is running, the validation should
1518 // be successful; otherwise, the validation should be failed.
1519 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), config.withWorkingTLS));
Ken Chenb9fa2062018-11-13 21:51:13 +08001520 } else if (config.mode == STRICT) {
Xiao Ma09b71022018-12-11 17:56:32 +09001521 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
waynema0e73c2e2019-07-31 15:04:08 +08001522 kDefaultParams, kDefaultPrivateDnsHostName));
Mike Yu724f77d2019-08-16 11:14:50 +08001523
1524 // Wait for the validation event.
1525 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), config.withWorkingTLS));
Ken Chenb9fa2062018-11-13 21:51:13 +08001526 }
Mike Yudd4ac2d2019-05-31 16:52:11 +08001527 tls.clearQueries();
Ken Chenb9fa2062018-11-13 21:51:13 +08001528
1529 const hostent* h_result = nullptr;
1530 ScopedAddrinfo ai_result;
1531
1532 if (config.method == GETHOSTBYNAME) {
1533 ASSERT_EQ(0, setNetworkForResolv(BYPASS_NETID));
1534 h_result = gethostbyname(host_name);
1535
1536 EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
1537 ASSERT_FALSE(h_result == nullptr);
1538 ASSERT_EQ(4, h_result->h_length);
1539 ASSERT_FALSE(h_result->h_addr_list[0] == nullptr);
1540 EXPECT_EQ(ADDR4, ToString(h_result));
1541 EXPECT_TRUE(h_result->h_addr_list[1] == nullptr);
1542 } else if (config.method == GETADDRINFO) {
1543 ASSERT_EQ(0, setNetworkForResolv(BYPASS_NETID));
1544 ai_result = safe_getaddrinfo(host_name, nullptr, nullptr);
1545 EXPECT_TRUE(ai_result != nullptr);
1546
1547 EXPECT_LE(1U, GetNumQueries(dns, host_name));
1548 // Could be A or AAAA
1549 const std::string result_str = ToString(ai_result);
1550 EXPECT_TRUE(result_str == ADDR4 || result_str == ADDR6)
1551 << ", result_str='" << result_str << "'";
1552 } else if (config.method == GETADDRINFOFORNET) {
1553 addrinfo* raw_ai_result = nullptr;
1554 EXPECT_EQ(0, android_getaddrinfofornet(host_name, /*servname=*/nullptr,
1555 /*hints=*/nullptr, BYPASS_NETID, MARK_UNSET,
1556 &raw_ai_result));
1557 ai_result.reset(raw_ai_result);
1558
1559 EXPECT_LE(1U, GetNumQueries(dns, host_name));
1560 // Could be A or AAAA
1561 const std::string result_str = ToString(ai_result);
1562 EXPECT_TRUE(result_str == ADDR4 || result_str == ADDR6)
1563 << ", result_str='" << result_str << "'";
Ken Chenb9fa2062018-11-13 21:51:13 +08001564 }
1565
Mike Yudd4ac2d2019-05-31 16:52:11 +08001566 EXPECT_EQ(0, tls.queries());
Ken Chenb9fa2062018-11-13 21:51:13 +08001567
1568 // Clear per-process resolv netid.
1569 ASSERT_EQ(0, setNetworkForResolv(NETID_UNSET));
Ken Chenb9fa2062018-11-13 21:51:13 +08001570 dns.clearQueries();
1571 }
Ken Chenb9fa2062018-11-13 21:51:13 +08001572}
1573
1574TEST_F(ResolverTest, StrictMode_NoTlsServers) {
Xiao Ma09b71022018-12-11 17:56:32 +09001575 constexpr char cleartext_addr[] = "127.0.0.53";
Ken Chenb9fa2062018-11-13 21:51:13 +08001576 const std::vector<std::string> servers = { cleartext_addr };
Xiao Ma09b71022018-12-11 17:56:32 +09001577 constexpr char host_name[] = "strictmode.notlsips.example.com.";
1578 const std::vector<DnsRecord> records = {
1579 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1580 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1581 };
Ken Chenb9fa2062018-11-13 21:51:13 +08001582
Xiao Ma09b71022018-12-11 17:56:32 +09001583 test::DNSResponder dns(cleartext_addr);
1584 StartDns(dns, records);
Ken Chenb9fa2062018-11-13 21:51:13 +08001585
waynema0e73c2e2019-07-31 15:04:08 +08001586 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
1587 kDefaultIncorrectPrivateDnsHostName));
Ken Chenb9fa2062018-11-13 21:51:13 +08001588
1589 addrinfo* ai_result = nullptr;
1590 EXPECT_NE(0, getaddrinfo(host_name, nullptr, nullptr, &ai_result));
1591 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
1592}
Luke Huang94b10b92018-11-21 20:13:38 +08001593
1594namespace {
1595
Luke Huang70931aa2019-01-31 11:57:41 +08001596int getAsyncResponse(int fd, int* rcode, uint8_t* buf, int bufLen) {
Luke Huang94b10b92018-11-21 20:13:38 +08001597 struct pollfd wait_fd[1];
1598 wait_fd[0].fd = fd;
1599 wait_fd[0].events = POLLIN;
1600 short revents;
1601 int ret;
1602
1603 ret = poll(wait_fd, 1, -1);
1604 revents = wait_fd[0].revents;
1605 if (revents & POLLIN) {
1606 int n = resNetworkResult(fd, rcode, buf, bufLen);
Luke Huangba7bef92018-12-26 16:53:03 +08001607 // Verify that resNetworkResult() closed the fd
1608 char dummy;
1609 EXPECT_EQ(-1, read(fd, &dummy, sizeof dummy));
1610 EXPECT_EQ(EBADF, errno);
Luke Huang94b10b92018-11-21 20:13:38 +08001611 return n;
1612 }
1613 return -1;
1614}
1615
Luke Huang70931aa2019-01-31 11:57:41 +08001616std::string toString(uint8_t* buf, int bufLen, int ipType) {
Luke Huang94b10b92018-11-21 20:13:38 +08001617 ns_msg handle;
1618 int ancount, n = 0;
1619 ns_rr rr;
1620
1621 if (ns_initparse((const uint8_t*) buf, bufLen, &handle) >= 0) {
1622 ancount = ns_msg_count(handle, ns_s_an);
1623 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
Luke Huang70931aa2019-01-31 11:57:41 +08001624 const uint8_t* rdata = ns_rr_rdata(rr);
Luke Huang94b10b92018-11-21 20:13:38 +08001625 char buffer[INET6_ADDRSTRLEN];
1626 if (inet_ntop(ipType, (const char*) rdata, buffer, sizeof(buffer))) {
1627 return buffer;
1628 }
1629 }
1630 }
1631 return "";
1632}
1633
1634int dns_open_proxy() {
1635 int s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
1636 if (s == -1) {
1637 return -1;
1638 }
1639 const int one = 1;
1640 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
1641
1642 static const struct sockaddr_un proxy_addr = {
1643 .sun_family = AF_UNIX,
1644 .sun_path = "/dev/socket/dnsproxyd",
1645 };
1646
1647 if (TEMP_FAILURE_RETRY(connect(s, (const struct sockaddr*) &proxy_addr, sizeof(proxy_addr))) !=
1648 0) {
1649 close(s);
1650 return -1;
1651 }
1652
1653 return s;
1654}
1655
Luke Huangba7bef92018-12-26 16:53:03 +08001656void expectAnswersValid(int fd, int ipType, const std::string& expectedAnswer) {
1657 int rcode = -1;
1658 uint8_t buf[MAXPACKET] = {};
1659
1660 int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
1661 EXPECT_GT(res, 0);
1662 EXPECT_EQ(expectedAnswer, toString(buf, res, ipType));
1663}
1664
1665void expectAnswersNotValid(int fd, int expectedErrno) {
1666 int rcode = -1;
1667 uint8_t buf[MAXPACKET] = {};
1668
1669 int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
1670 EXPECT_EQ(expectedErrno, res);
1671}
1672
Luke Huang94b10b92018-11-21 20:13:38 +08001673} // namespace
1674
1675TEST_F(ResolverTest, Async_NormalQueryV4V6) {
Xiao Ma09b71022018-12-11 17:56:32 +09001676 constexpr char listen_addr[] = "127.0.0.4";
1677 constexpr char host_name[] = "howdy.example.com.";
1678 const std::vector<DnsRecord> records = {
1679 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1680 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1681 };
1682
1683 test::DNSResponder dns(listen_addr);
1684 StartDns(dns, records);
Luke Huang94b10b92018-11-21 20:13:38 +08001685 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09001686 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huang94b10b92018-11-21 20:13:38 +08001687
Luke Huangba7bef92018-12-26 16:53:03 +08001688 int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1689 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001690 EXPECT_TRUE(fd1 != -1);
1691 EXPECT_TRUE(fd2 != -1);
1692
Luke Huang70931aa2019-01-31 11:57:41 +08001693 uint8_t buf[MAXPACKET] = {};
Luke Huang94b10b92018-11-21 20:13:38 +08001694 int rcode;
1695 int res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
1696 EXPECT_GT(res, 0);
1697 EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
1698
1699 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
1700 EXPECT_GT(res, 0);
1701 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
1702
1703 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
1704
1705 // Re-query verify cache works
Luke Huangba7bef92018-12-26 16:53:03 +08001706 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1707 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001708
1709 EXPECT_TRUE(fd1 != -1);
1710 EXPECT_TRUE(fd2 != -1);
1711
1712 res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
1713 EXPECT_GT(res, 0);
1714 EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
1715
1716 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
1717 EXPECT_GT(res, 0);
1718 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
1719
1720 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
1721}
1722
1723TEST_F(ResolverTest, Async_BadQuery) {
Xiao Ma09b71022018-12-11 17:56:32 +09001724 constexpr char listen_addr[] = "127.0.0.4";
1725 constexpr char host_name[] = "howdy.example.com.";
1726 const std::vector<DnsRecord> records = {
1727 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1728 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1729 };
1730
1731 test::DNSResponder dns(listen_addr);
1732 StartDns(dns, records);
Luke Huang94b10b92018-11-21 20:13:38 +08001733 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09001734 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huang94b10b92018-11-21 20:13:38 +08001735
1736 static struct {
1737 int fd;
1738 const char* dname;
1739 const int queryType;
1740 const int expectRcode;
1741 } kTestData[] = {
Luke Huangba7bef92018-12-26 16:53:03 +08001742 {-1, "", ns_t_aaaa, 0},
1743 {-1, "as65ass46", ns_t_aaaa, 0},
1744 {-1, "454564564564", ns_t_aaaa, 0},
1745 {-1, "h645235", ns_t_a, 0},
1746 {-1, "www.google.com", ns_t_a, 0},
Luke Huang94b10b92018-11-21 20:13:38 +08001747 };
1748
1749 for (auto& td : kTestData) {
1750 SCOPED_TRACE(td.dname);
Luke Huangba7bef92018-12-26 16:53:03 +08001751 td.fd = resNetworkQuery(TEST_NETID, td.dname, ns_c_in, td.queryType, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001752 EXPECT_TRUE(td.fd != -1);
1753 }
1754
1755 // dns_responder return empty resp(packet only contains query part) with no error currently
1756 for (const auto& td : kTestData) {
Luke Huang70931aa2019-01-31 11:57:41 +08001757 uint8_t buf[MAXPACKET] = {};
Luke Huang94b10b92018-11-21 20:13:38 +08001758 int rcode;
1759 SCOPED_TRACE(td.dname);
1760 int res = getAsyncResponse(td.fd, &rcode, buf, MAXPACKET);
1761 EXPECT_GT(res, 0);
1762 EXPECT_EQ(rcode, td.expectRcode);
1763 }
1764}
1765
1766TEST_F(ResolverTest, Async_EmptyAnswer) {
Xiao Ma09b71022018-12-11 17:56:32 +09001767 constexpr char listen_addr[] = "127.0.0.4";
1768 constexpr char host_name[] = "howdy.example.com.";
1769 const std::vector<DnsRecord> records = {
1770 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1771 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1772 };
1773
1774 test::DNSResponder dns(listen_addr);
1775 StartDns(dns, records);
Luke Huang94b10b92018-11-21 20:13:38 +08001776 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09001777 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huang94b10b92018-11-21 20:13:38 +08001778
Luke Huang9c264bb2018-12-18 16:44:41 +08001779 // TODO: Disable retry to make this test explicit.
1780 auto& cv = dns.getCv();
1781 auto& cvMutex = dns.getCvMutex();
1782 int fd1;
1783 // Wait on the condition variable to ensure that the DNS server has handled our first query.
1784 {
1785 std::unique_lock lk(cvMutex);
Luke Huangba7bef92018-12-26 16:53:03 +08001786 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
Luke Huang9c264bb2018-12-18 16:44:41 +08001787 EXPECT_TRUE(fd1 != -1);
1788 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lk, std::chrono::seconds(1)));
1789 }
Luke Huang94b10b92018-11-21 20:13:38 +08001790
Luke Huang94b10b92018-11-21 20:13:38 +08001791 dns.setResponseProbability(0.0);
Luke Huang94b10b92018-11-21 20:13:38 +08001792
Luke Huangba7bef92018-12-26 16:53:03 +08001793 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001794 EXPECT_TRUE(fd2 != -1);
1795
Luke Huangba7bef92018-12-26 16:53:03 +08001796 int fd3 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001797 EXPECT_TRUE(fd3 != -1);
1798
Luke Huang9c264bb2018-12-18 16:44:41 +08001799 uint8_t buf[MAXPACKET] = {};
Luke Huang94b10b92018-11-21 20:13:38 +08001800 int rcode;
1801
Luke Huang9c264bb2018-12-18 16:44:41 +08001802 // expect no response
1803 int res = getAsyncResponse(fd3, &rcode, buf, MAXPACKET);
1804 EXPECT_EQ(-ETIMEDOUT, res);
Luke Huang94b10b92018-11-21 20:13:38 +08001805
Luke Huang9c264bb2018-12-18 16:44:41 +08001806 // expect no response
Luke Huang94b10b92018-11-21 20:13:38 +08001807 memset(buf, 0, MAXPACKET);
Luke Huang9c264bb2018-12-18 16:44:41 +08001808 res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
1809 EXPECT_EQ(-ETIMEDOUT, res);
Luke Huang94b10b92018-11-21 20:13:38 +08001810
Luke Huang94b10b92018-11-21 20:13:38 +08001811 dns.setResponseProbability(1.0);
Luke Huang94b10b92018-11-21 20:13:38 +08001812
Luke Huangba7bef92018-12-26 16:53:03 +08001813 int fd4 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
Luke Huang94b10b92018-11-21 20:13:38 +08001814 EXPECT_TRUE(fd4 != -1);
1815
1816 memset(buf, 0, MAXPACKET);
1817 res = getAsyncResponse(fd4, &rcode, buf, MAXPACKET);
1818 EXPECT_GT(res, 0);
1819 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
1820
1821 memset(buf, 0, MAXPACKET);
1822 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
1823 EXPECT_GT(res, 0);
1824 EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
1825}
1826
1827TEST_F(ResolverTest, Async_MalformedQuery) {
Xiao Ma09b71022018-12-11 17:56:32 +09001828 constexpr char listen_addr[] = "127.0.0.4";
1829 constexpr char host_name[] = "howdy.example.com.";
1830 const std::vector<DnsRecord> records = {
1831 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1832 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1833 };
1834
1835 test::DNSResponder dns(listen_addr);
1836 StartDns(dns, records);
Luke Huang94b10b92018-11-21 20:13:38 +08001837 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09001838 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huang94b10b92018-11-21 20:13:38 +08001839
1840 int fd = dns_open_proxy();
1841 EXPECT_TRUE(fd > 0);
1842
1843 const std::string badMsg = "16-52512#";
Xiao Ma09b71022018-12-11 17:56:32 +09001844 static const struct {
Luke Huang94b10b92018-11-21 20:13:38 +08001845 const std::string cmd;
1846 const int expectErr;
1847 } kTestData[] = {
Luke Huangba7bef92018-12-26 16:53:03 +08001848 // Too few arguments
Luke Huang94b10b92018-11-21 20:13:38 +08001849 {"resnsend " + badMsg + '\0', -EINVAL},
1850 // Bad netId
Luke Huangba7bef92018-12-26 16:53:03 +08001851 {"resnsend badnetId 0 " + badMsg + '\0', -EINVAL},
Luke Huang94b10b92018-11-21 20:13:38 +08001852 // Bad raw data
Luke Huangba7bef92018-12-26 16:53:03 +08001853 {"resnsend " + std::to_string(TEST_NETID) + " 0 " + badMsg + '\0', -EILSEQ},
Luke Huang94b10b92018-11-21 20:13:38 +08001854 };
1855
1856 for (unsigned int i = 0; i < std::size(kTestData); i++) {
1857 auto& td = kTestData[i];
1858 SCOPED_TRACE(td.cmd);
1859 ssize_t rc = TEMP_FAILURE_RETRY(write(fd, td.cmd.c_str(), td.cmd.size()));
1860 EXPECT_EQ(rc, static_cast<ssize_t>(td.cmd.size()));
1861
1862 int32_t tmp;
1863 rc = TEMP_FAILURE_RETRY(read(fd, &tmp, sizeof(tmp)));
1864 EXPECT_TRUE(rc > 0);
1865 EXPECT_EQ(static_cast<int>(ntohl(tmp)), td.expectErr);
1866 }
1867 // Normal query with answer buffer
1868 // This is raw data of query "howdy.example.com" type 1 class 1
1869 std::string query = "81sBAAABAAAAAAAABWhvd2R5B2V4YW1wbGUDY29tAAABAAE=";
Luke Huangba7bef92018-12-26 16:53:03 +08001870 std::string cmd = "resnsend " + std::to_string(TEST_NETID) + " 0 " + query + '\0';
Luke Huang94b10b92018-11-21 20:13:38 +08001871 ssize_t rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
1872 EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
1873
Luke Huang70931aa2019-01-31 11:57:41 +08001874 uint8_t smallBuf[1] = {};
Luke Huang94b10b92018-11-21 20:13:38 +08001875 int rcode;
1876 rc = getAsyncResponse(fd, &rcode, smallBuf, 1);
Luke Huangba7bef92018-12-26 16:53:03 +08001877 EXPECT_EQ(-EMSGSIZE, rc);
Luke Huang94b10b92018-11-21 20:13:38 +08001878
1879 // Do the normal test with large buffer again
1880 fd = dns_open_proxy();
1881 EXPECT_TRUE(fd > 0);
1882 rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
1883 EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
Luke Huang70931aa2019-01-31 11:57:41 +08001884 uint8_t buf[MAXPACKET] = {};
Luke Huang94b10b92018-11-21 20:13:38 +08001885 rc = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
1886 EXPECT_EQ("1.2.3.4", toString(buf, rc, AF_INET));
Mike Yu4f3747b2018-12-02 17:54:29 +09001887}
1888
Luke Huangba7bef92018-12-26 16:53:03 +08001889TEST_F(ResolverTest, Async_CacheFlags) {
Xiao Ma09b71022018-12-11 17:56:32 +09001890 constexpr char listen_addr[] = "127.0.0.4";
1891 constexpr char host_name[] = "howdy.example.com.";
Luke Huang40f5f492019-05-09 19:37:35 +08001892 constexpr char another_host_name[] = "howdy.example2.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09001893 const std::vector<DnsRecord> records = {
1894 {host_name, ns_type::ns_t_a, "1.2.3.4"},
1895 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
Luke Huang40f5f492019-05-09 19:37:35 +08001896 {another_host_name, ns_type::ns_t_a, "1.2.3.5"},
1897 {another_host_name, ns_type::ns_t_aaaa, "::1.2.3.5"},
Xiao Ma09b71022018-12-11 17:56:32 +09001898 };
1899
1900 test::DNSResponder dns(listen_addr);
1901 StartDns(dns, records);
Luke Huangba7bef92018-12-26 16:53:03 +08001902 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09001903 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Luke Huangba7bef92018-12-26 16:53:03 +08001904
1905 // ANDROID_RESOLV_NO_CACHE_STORE
1906 int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1907 ANDROID_RESOLV_NO_CACHE_STORE);
1908 EXPECT_TRUE(fd1 != -1);
1909 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1910 ANDROID_RESOLV_NO_CACHE_STORE);
1911 EXPECT_TRUE(fd2 != -1);
1912 int fd3 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1913 ANDROID_RESOLV_NO_CACHE_STORE);
1914 EXPECT_TRUE(fd3 != -1);
1915
1916 expectAnswersValid(fd3, AF_INET, "1.2.3.4");
1917 expectAnswersValid(fd2, AF_INET, "1.2.3.4");
1918 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
1919
1920 // No cache exists, expect 3 queries
1921 EXPECT_EQ(3U, GetNumQueries(dns, host_name));
1922
1923 // Re-query and cache
1924 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
1925
1926 EXPECT_TRUE(fd1 != -1);
1927
1928 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
1929
1930 // Now we have cache, expect 4 queries
1931 EXPECT_EQ(4U, GetNumQueries(dns, host_name));
1932
1933 // ANDROID_RESOLV_NO_CACHE_LOOKUP
1934 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1935 ANDROID_RESOLV_NO_CACHE_LOOKUP);
1936 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1937 ANDROID_RESOLV_NO_CACHE_LOOKUP);
1938
1939 EXPECT_TRUE(fd1 != -1);
1940 EXPECT_TRUE(fd2 != -1);
1941
1942 expectAnswersValid(fd2, AF_INET, "1.2.3.4");
1943 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
1944
1945 // Skip cache, expect 6 queries
1946 EXPECT_EQ(6U, GetNumQueries(dns, host_name));
1947
1948 // Re-query verify cache works
1949 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
1950 ANDROID_RESOLV_NO_CACHE_STORE);
1951 EXPECT_TRUE(fd1 != -1);
1952 expectAnswersValid(fd1, AF_INET, "1.2.3.4");
1953
1954 // Cache hits, expect still 6 queries
1955 EXPECT_EQ(6U, GetNumQueries(dns, host_name));
Luke Huanga1d74182019-03-19 17:30:36 +08001956
1957 // Start to verify if ANDROID_RESOLV_NO_CACHE_LOOKUP does write response into cache
1958 dns.clearQueries();
1959
1960 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa,
1961 ANDROID_RESOLV_NO_CACHE_LOOKUP);
1962 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa,
1963 ANDROID_RESOLV_NO_CACHE_LOOKUP);
1964
1965 EXPECT_TRUE(fd1 != -1);
1966 EXPECT_TRUE(fd2 != -1);
1967
1968 expectAnswersValid(fd2, AF_INET6, "::1.2.3.4");
1969 expectAnswersValid(fd1, AF_INET6, "::1.2.3.4");
1970
1971 // Skip cache, expect 2 queries
1972 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
1973
1974 // Re-query without flags
1975 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
1976 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
1977
1978 EXPECT_TRUE(fd1 != -1);
1979 EXPECT_TRUE(fd2 != -1);
1980
1981 expectAnswersValid(fd2, AF_INET6, "::1.2.3.4");
1982 expectAnswersValid(fd1, AF_INET6, "::1.2.3.4");
1983
1984 // Cache hits, expect still 2 queries
1985 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
Luke Huang40f5f492019-05-09 19:37:35 +08001986
1987 // Test both ANDROID_RESOLV_NO_CACHE_STORE and ANDROID_RESOLV_NO_CACHE_LOOKUP are set
1988 dns.clearQueries();
1989
1990 // Make sure that the cache of "howdy.example2.com" exists.
1991 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa, 0);
1992 EXPECT_TRUE(fd1 != -1);
1993 expectAnswersValid(fd1, AF_INET6, "::1.2.3.5");
1994 EXPECT_EQ(1U, GetNumQueries(dns, another_host_name));
1995
1996 // Re-query with testFlags
1997 const int testFlag = ANDROID_RESOLV_NO_CACHE_STORE | ANDROID_RESOLV_NO_CACHE_LOOKUP;
1998 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa, testFlag);
1999 EXPECT_TRUE(fd1 != -1);
2000 expectAnswersValid(fd1, AF_INET6, "::1.2.3.5");
2001 // Expect cache lookup is skipped.
2002 EXPECT_EQ(2U, GetNumQueries(dns, another_host_name));
2003
2004 // Do another query with testFlags
2005 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_a, testFlag);
2006 EXPECT_TRUE(fd1 != -1);
2007 expectAnswersValid(fd1, AF_INET, "1.2.3.5");
2008 // Expect cache lookup is skipped.
2009 EXPECT_EQ(3U, GetNumQueries(dns, another_host_name));
2010
2011 // Re-query with no flags
2012 fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_a, 0);
2013 EXPECT_TRUE(fd1 != -1);
2014 expectAnswersValid(fd1, AF_INET, "1.2.3.5");
2015 // Expect no cache hit because cache storing is also skipped in previous query.
2016 EXPECT_EQ(4U, GetNumQueries(dns, another_host_name));
Luke Huangba7bef92018-12-26 16:53:03 +08002017}
2018
2019TEST_F(ResolverTest, Async_NoRetryFlag) {
Luke Huang70931aa2019-01-31 11:57:41 +08002020 constexpr char listen_addr0[] = "127.0.0.4";
2021 constexpr char listen_addr1[] = "127.0.0.6";
Xiao Ma09b71022018-12-11 17:56:32 +09002022 constexpr char host_name[] = "howdy.example.com.";
2023 const std::vector<DnsRecord> records = {
2024 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2025 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2026 };
2027
Luke Huang70931aa2019-01-31 11:57:41 +08002028 test::DNSResponder dns0(listen_addr0);
2029 test::DNSResponder dns1(listen_addr1);
2030 StartDns(dns0, records);
2031 StartDns(dns1, records);
2032 ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr0, listen_addr1}));
Luke Huangba7bef92018-12-26 16:53:03 +08002033
Luke Huang70931aa2019-01-31 11:57:41 +08002034 dns0.clearQueries();
2035 dns1.clearQueries();
2036
2037 dns0.setResponseProbability(0.0);
2038 dns1.setResponseProbability(0.0);
Luke Huangba7bef92018-12-26 16:53:03 +08002039
2040 int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2041 ANDROID_RESOLV_NO_RETRY);
2042 EXPECT_TRUE(fd1 != -1);
2043
2044 int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa,
2045 ANDROID_RESOLV_NO_RETRY);
2046 EXPECT_TRUE(fd2 != -1);
2047
2048 // expect no response
2049 expectAnswersNotValid(fd1, -ETIMEDOUT);
2050 expectAnswersNotValid(fd2, -ETIMEDOUT);
2051
Luke Huang70931aa2019-01-31 11:57:41 +08002052 // No retry case, expect total 2 queries. The server is selected randomly.
2053 EXPECT_EQ(2U, GetNumQueries(dns0, host_name) + GetNumQueries(dns1, host_name));
Luke Huangba7bef92018-12-26 16:53:03 +08002054
Luke Huang70931aa2019-01-31 11:57:41 +08002055 dns0.clearQueries();
2056 dns1.clearQueries();
Luke Huangba7bef92018-12-26 16:53:03 +08002057
2058 fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2059 EXPECT_TRUE(fd1 != -1);
2060
2061 fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2062 EXPECT_TRUE(fd2 != -1);
2063
2064 // expect no response
2065 expectAnswersNotValid(fd1, -ETIMEDOUT);
2066 expectAnswersNotValid(fd2, -ETIMEDOUT);
2067
2068 // Retry case, expect 4 queries
Luke Huang70931aa2019-01-31 11:57:41 +08002069 EXPECT_EQ(4U, GetNumQueries(dns0, host_name));
2070 EXPECT_EQ(4U, GetNumQueries(dns1, host_name));
2071}
2072
2073TEST_F(ResolverTest, Async_VerifyQueryID) {
2074 constexpr char listen_addr[] = "127.0.0.4";
2075 constexpr char host_name[] = "howdy.example.com.";
2076 const std::vector<DnsRecord> records = {
2077 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2078 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2079 };
2080
2081 test::DNSResponder dns(listen_addr);
2082 StartDns(dns, records);
2083 std::vector<std::string> servers = {listen_addr};
2084 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2085
2086 const uint8_t queryBuf1[] = {
2087 /* Header */
2088 0x55, 0x66, /* Transaction ID */
2089 0x01, 0x00, /* Flags */
2090 0x00, 0x01, /* Questions */
2091 0x00, 0x00, /* Answer RRs */
2092 0x00, 0x00, /* Authority RRs */
2093 0x00, 0x00, /* Additional RRs */
2094 /* Queries */
2095 0x05, 0x68, 0x6f, 0x77, 0x64, 0x79, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
2096 0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */
2097 0x00, 0x01, /* Type */
2098 0x00, 0x01 /* Class */
2099 };
2100
2101 int fd = resNetworkSend(TEST_NETID, queryBuf1, sizeof(queryBuf1), 0);
2102 EXPECT_TRUE(fd != -1);
2103
2104 uint8_t buf[MAXPACKET] = {};
2105 int rcode;
2106
2107 int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2108 EXPECT_GT(res, 0);
2109 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2110
2111 auto hp = reinterpret_cast<HEADER*>(buf);
2112 EXPECT_EQ(21862U, htons(hp->id));
2113
2114 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2115
2116 const uint8_t queryBuf2[] = {
2117 /* Header */
2118 0x00, 0x53, /* Transaction ID */
2119 0x01, 0x00, /* Flags */
2120 0x00, 0x01, /* Questions */
2121 0x00, 0x00, /* Answer RRs */
2122 0x00, 0x00, /* Authority RRs */
2123 0x00, 0x00, /* Additional RRs */
2124 /* Queries */
2125 0x05, 0x68, 0x6f, 0x77, 0x64, 0x79, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
2126 0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */
2127 0x00, 0x01, /* Type */
2128 0x00, 0x01 /* Class */
2129 };
2130
2131 // Re-query verify cache works and query id is correct
2132 fd = resNetworkSend(TEST_NETID, queryBuf2, sizeof(queryBuf2), 0);
2133
2134 EXPECT_TRUE(fd != -1);
2135
2136 res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2137 EXPECT_GT(res, 0);
2138 EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2139
2140 EXPECT_EQ(0x0053U, htons(hp->id));
2141
2142 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
Luke Huangba7bef92018-12-26 16:53:03 +08002143}
2144
Mike Yu4f3747b2018-12-02 17:54:29 +09002145// This test checks that the resolver should not generate the request containing OPT RR when using
Ken Chen0a015532019-01-02 14:59:38 +08002146// cleartext DNS. If we query the DNS server not supporting EDNS0 and it reponds with
2147// FORMERR_ON_EDNS, we will fallback to no EDNS0 and try again. If the server does no response, we
2148// won't retry so that we get no answer.
Mike Yu4f3747b2018-12-02 17:54:29 +09002149TEST_F(ResolverTest, BrokenEdns) {
2150 typedef test::DNSResponder::Edns Edns;
2151 enum ExpectResult { EXPECT_FAILURE, EXPECT_SUCCESS };
2152
2153 const char OFF[] = "off";
2154 const char OPPORTUNISTIC_UDP[] = "opportunistic_udp";
2155 const char OPPORTUNISTIC_TLS[] = "opportunistic_tls";
2156 const char STRICT[] = "strict";
2157 const char GETHOSTBYNAME[] = "gethostbyname";
2158 const char GETADDRINFO[] = "getaddrinfo";
Mike Yu4f3747b2018-12-02 17:54:29 +09002159 const char ADDR4[] = "192.0.2.1";
2160 const char CLEARTEXT_ADDR[] = "127.0.0.53";
2161 const char CLEARTEXT_PORT[] = "53";
2162 const char TLS_PORT[] = "853";
2163 const std::vector<std::string> servers = { CLEARTEXT_ADDR };
2164
Mike Yufc125e42019-05-15 20:41:28 +08002165 test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, ns_rcode::ns_r_servfail);
Mike Yu4f3747b2018-12-02 17:54:29 +09002166 ASSERT_TRUE(dns.startServer());
2167
2168 test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2169
2170 static const struct TestConfig {
2171 std::string mode;
2172 std::string method;
2173 Edns edns;
2174 ExpectResult expectResult;
2175
2176 std::string asHostName() const {
2177 const char* ednsString;
2178 switch (edns) {
2179 case Edns::ON:
2180 ednsString = "ednsOn";
2181 break;
Ken Chen0a015532019-01-02 14:59:38 +08002182 case Edns::FORMERR_ON_EDNS:
Mike Yu4f3747b2018-12-02 17:54:29 +09002183 ednsString = "ednsFormerr";
2184 break;
2185 case Edns::DROP:
2186 ednsString = "ednsDrop";
2187 break;
2188 default:
2189 ednsString = "";
2190 break;
2191 }
2192 return StringPrintf("%s.%s.%s.", mode.c_str(), method.c_str(), ednsString);
2193 }
2194 } testConfigs[] = {
2195 // In OPPORTUNISTIC_TLS, we get no answer if the DNS server supports TLS but not EDNS0.
2196 // Could such server exist? if so, we might need to fallback to query cleartext DNS.
2197 // Another thing is that {OPPORTUNISTIC_TLS, Edns::DROP} and {STRICT, Edns::DROP} are
2198 // commented out since TLS timeout is not configurable.
2199 // TODO: Uncomment them after TLS timeout is configurable.
2200 {OFF, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
2201 {OPPORTUNISTIC_UDP, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
2202 {OPPORTUNISTIC_TLS, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
2203 {STRICT, GETHOSTBYNAME, Edns::ON, EXPECT_SUCCESS},
Ken Chen0a015532019-01-02 14:59:38 +08002204 {OFF, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2205 {OPPORTUNISTIC_UDP, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2206 {OPPORTUNISTIC_TLS, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
2207 {STRICT, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
Mike Yu4f3747b2018-12-02 17:54:29 +09002208 {OFF, GETHOSTBYNAME, Edns::DROP, EXPECT_SUCCESS},
2209 {OPPORTUNISTIC_UDP, GETHOSTBYNAME, Edns::DROP, EXPECT_SUCCESS},
2210 //{OPPORTUNISTIC_TLS, GETHOSTBYNAME, Edns::DROP, EXPECT_FAILURE},
2211 //{STRICT, GETHOSTBYNAME, Edns::DROP, EXPECT_FAILURE},
2212 {OFF, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
2213 {OPPORTUNISTIC_UDP, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
2214 {OPPORTUNISTIC_TLS, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
2215 {STRICT, GETADDRINFO, Edns::ON, EXPECT_SUCCESS},
Ken Chen0a015532019-01-02 14:59:38 +08002216 {OFF, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2217 {OPPORTUNISTIC_UDP, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
2218 {OPPORTUNISTIC_TLS, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
2219 {STRICT, GETADDRINFO, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
Mike Yu4f3747b2018-12-02 17:54:29 +09002220 {OFF, GETADDRINFO, Edns::DROP, EXPECT_SUCCESS},
2221 {OPPORTUNISTIC_UDP, GETADDRINFO, Edns::DROP, EXPECT_SUCCESS},
2222 //{OPPORTUNISTIC_TLS, GETADDRINFO, Edns::DROP, EXPECT_FAILURE},
2223 //{STRICT, GETADDRINFO, Edns::DROP, EXPECT_FAILURE},
2224 };
2225
2226 for (const auto& config : testConfigs) {
2227 const std::string testHostName = config.asHostName();
2228 SCOPED_TRACE(testHostName);
2229
2230 const char* host_name = testHostName.c_str();
2231 dns.addMapping(host_name, ns_type::ns_t_a, ADDR4);
2232 dns.setEdns(config.edns);
2233
2234 if (config.mode == OFF) {
Mike Yu0f20cdd2019-06-11 11:52:37 +08002235 if (tls.running()) {
2236 ASSERT_TRUE(tls.stopServer());
2237 }
Xiao Ma09b71022018-12-11 17:56:32 +09002238 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
Mike Yu4f3747b2018-12-02 17:54:29 +09002239 } else if (config.mode == OPPORTUNISTIC_UDP) {
Mike Yu0f20cdd2019-06-11 11:52:37 +08002240 if (tls.running()) {
2241 ASSERT_TRUE(tls.stopServer());
2242 }
Xiao Ma09b71022018-12-11 17:56:32 +09002243 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
waynema0e73c2e2019-07-31 15:04:08 +08002244 kDefaultParams, ""));
Mike Yu724f77d2019-08-16 11:14:50 +08002245 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), false));
Mike Yu4f3747b2018-12-02 17:54:29 +09002246 } else if (config.mode == OPPORTUNISTIC_TLS) {
Mike Yu0f20cdd2019-06-11 11:52:37 +08002247 if (!tls.running()) {
2248 ASSERT_TRUE(tls.startServer());
2249 }
Xiao Ma09b71022018-12-11 17:56:32 +09002250 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
waynema0e73c2e2019-07-31 15:04:08 +08002251 kDefaultParams, ""));
Mike Yu724f77d2019-08-16 11:14:50 +08002252 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
Mike Yu4f3747b2018-12-02 17:54:29 +09002253 } else if (config.mode == STRICT) {
Mike Yu0f20cdd2019-06-11 11:52:37 +08002254 if (!tls.running()) {
2255 ASSERT_TRUE(tls.startServer());
2256 }
Xiao Ma09b71022018-12-11 17:56:32 +09002257 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains,
waynema0e73c2e2019-07-31 15:04:08 +08002258 kDefaultParams, kDefaultPrivateDnsHostName));
Mike Yu724f77d2019-08-16 11:14:50 +08002259 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
Mike Yu4f3747b2018-12-02 17:54:29 +09002260 }
2261
2262 if (config.method == GETHOSTBYNAME) {
2263 const hostent* h_result = gethostbyname(host_name);
2264 if (config.expectResult == EXPECT_SUCCESS) {
2265 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2266 ASSERT_TRUE(h_result != nullptr);
2267 ASSERT_EQ(4, h_result->h_length);
2268 ASSERT_FALSE(h_result->h_addr_list[0] == nullptr);
2269 EXPECT_EQ(ADDR4, ToString(h_result));
2270 EXPECT_TRUE(h_result->h_addr_list[1] == nullptr);
2271 } else {
2272 EXPECT_EQ(0U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
2273 ASSERT_TRUE(h_result == nullptr);
2274 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2275 }
2276 } else if (config.method == GETADDRINFO) {
2277 ScopedAddrinfo ai_result;
2278 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2279 ai_result = safe_getaddrinfo(host_name, nullptr, &hints);
2280 if (config.expectResult == EXPECT_SUCCESS) {
2281 EXPECT_TRUE(ai_result != nullptr);
2282 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2283 const std::string result_str = ToString(ai_result);
2284 EXPECT_EQ(ADDR4, result_str);
2285 } else {
2286 EXPECT_TRUE(ai_result == nullptr);
2287 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
2288 }
2289 } else {
2290 FAIL() << "Unsupported query method: " << config.method;
2291 }
2292
Mike Yudd4ac2d2019-05-31 16:52:11 +08002293 tls.clearQueries();
Mike Yu4f3747b2018-12-02 17:54:29 +09002294 dns.clearQueries();
2295 }
Mike Yu4f3747b2018-12-02 17:54:29 +09002296}
nuccachena26cc2a2018-07-17 18:07:23 +08002297
Ken Chen0a015532019-01-02 14:59:38 +08002298// DNS-over-TLS validation success, but server does not respond to TLS query after a while.
2299// Resolver should have a reasonable number of retries instead of spinning forever. We don't have
2300// an efficient way to know if resolver is stuck in an infinite loop. However, test case will be
2301// failed due to timeout.
2302TEST_F(ResolverTest, UnstableTls) {
2303 const char CLEARTEXT_ADDR[] = "127.0.0.53";
2304 const char CLEARTEXT_PORT[] = "53";
2305 const char TLS_PORT[] = "853";
2306 const char* host_name1 = "nonexistent1.example.com.";
2307 const char* host_name2 = "nonexistent2.example.com.";
2308 const std::vector<std::string> servers = {CLEARTEXT_ADDR};
2309
Mike Yufc125e42019-05-15 20:41:28 +08002310 test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, ns_rcode::ns_r_servfail);
Ken Chen0a015532019-01-02 14:59:38 +08002311 ASSERT_TRUE(dns.startServer());
2312 dns.setEdns(test::DNSResponder::Edns::FORMERR_ON_EDNS);
2313 test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2314 ASSERT_TRUE(tls.startServer());
waynema0e73c2e2019-07-31 15:04:08 +08002315 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
Mike Yu724f77d2019-08-16 11:14:50 +08002316 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
2317
Ken Chen0a015532019-01-02 14:59:38 +08002318 // Shutdown TLS server to get an error. It's similar to no response case but without waiting.
2319 tls.stopServer();
2320
2321 const hostent* h_result = gethostbyname(host_name1);
2322 EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
2323 ASSERT_TRUE(h_result == nullptr);
2324 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2325
2326 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2327 ScopedAddrinfo ai_result = safe_getaddrinfo(host_name2, nullptr, &hints);
2328 EXPECT_TRUE(ai_result == nullptr);
2329 EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
2330}
2331
2332// DNS-over-TLS validation success, but server does not respond to TLS query after a while.
2333// Moreover, server responds RCODE=FORMERR even on non-EDNS query.
2334TEST_F(ResolverTest, BogusDnsServer) {
2335 const char CLEARTEXT_ADDR[] = "127.0.0.53";
2336 const char CLEARTEXT_PORT[] = "53";
2337 const char TLS_PORT[] = "853";
2338 const char* host_name1 = "nonexistent1.example.com.";
2339 const char* host_name2 = "nonexistent2.example.com.";
2340 const std::vector<std::string> servers = {CLEARTEXT_ADDR};
2341
Mike Yufc125e42019-05-15 20:41:28 +08002342 test::DNSResponder dns(CLEARTEXT_ADDR, CLEARTEXT_PORT, ns_rcode::ns_r_servfail);
Ken Chen0a015532019-01-02 14:59:38 +08002343 ASSERT_TRUE(dns.startServer());
2344 test::DnsTlsFrontend tls(CLEARTEXT_ADDR, TLS_PORT, CLEARTEXT_ADDR, CLEARTEXT_PORT);
2345 ASSERT_TRUE(tls.startServer());
waynema0e73c2e2019-07-31 15:04:08 +08002346 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
Mike Yu724f77d2019-08-16 11:14:50 +08002347 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
2348
Ken Chen0a015532019-01-02 14:59:38 +08002349 // Shutdown TLS server to get an error. It's similar to no response case but without waiting.
2350 tls.stopServer();
2351 dns.setEdns(test::DNSResponder::Edns::FORMERR_UNCOND);
2352
2353 const hostent* h_result = gethostbyname(host_name1);
2354 EXPECT_EQ(0U, GetNumQueries(dns, host_name1));
2355 ASSERT_TRUE(h_result == nullptr);
2356 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
2357
2358 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
2359 ScopedAddrinfo ai_result = safe_getaddrinfo(host_name2, nullptr, &hints);
2360 EXPECT_TRUE(ai_result == nullptr);
2361 EXPECT_EQ(0U, GetNumQueries(dns, host_name2));
2362}
2363
nuccachena26cc2a2018-07-17 18:07:23 +08002364TEST_F(ResolverTest, GetAddrInfo_Dns64Synthesize) {
2365 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002366 constexpr char dns64_name[] = "ipv4only.arpa.";
2367 constexpr char host_name[] = "v4only.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09002368 const std::vector<DnsRecord> records = {
2369 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2370 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2371 };
nuccachena26cc2a2018-07-17 18:07:23 +08002372
Xiao Ma09b71022018-12-11 17:56:32 +09002373 test::DNSResponder dns(listen_addr);
Xiao Ma09b71022018-12-11 17:56:32 +09002374 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002375
2376 std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002377 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002378
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002379 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002380 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002381 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002382
2383 // hints are necessary in order to let netd know which type of addresses the caller is
2384 // interested in.
Xiao Ma09b71022018-12-11 17:56:32 +09002385 const addrinfo hints = {.ai_family = AF_UNSPEC};
nuccachena26cc2a2018-07-17 18:07:23 +08002386 ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, &hints);
2387 EXPECT_TRUE(result != nullptr);
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002388 // TODO: BUG: there should only be two queries, one AAAA (which returns no records) and one A
2389 // (which returns 1.2.3.4). But there is an extra AAAA.
2390 EXPECT_EQ(3U, GetNumQueries(dns, host_name));
nuccachena26cc2a2018-07-17 18:07:23 +08002391
2392 std::string result_str = ToString(result);
2393 EXPECT_EQ(result_str, "64:ff9b::102:304");
2394
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002395 // Stopping NAT64 prefix discovery disables synthesis.
Luke Huang5bd827c2019-03-14 16:10:04 +08002396 EXPECT_TRUE(mDnsClient.resolvService()->stopPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002397 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_NOT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002398
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002399 dns.clearQueries();
nuccachena26cc2a2018-07-17 18:07:23 +08002400
2401 result = safe_getaddrinfo("v4only", nullptr, &hints);
2402 EXPECT_TRUE(result != nullptr);
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002403 // TODO: BUG: there should only be one query, an AAAA (which returns no records), because the
2404 // A is already cached. But there is an extra AAAA.
2405 EXPECT_EQ(2U, GetNumQueries(dns, host_name));
nuccachena26cc2a2018-07-17 18:07:23 +08002406
2407 result_str = ToString(result);
2408 EXPECT_EQ(result_str, "1.2.3.4");
2409}
2410
nuccachena26cc2a2018-07-17 18:07:23 +08002411TEST_F(ResolverTest, GetAddrInfo_Dns64QuerySpecified) {
2412 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002413 constexpr char dns64_name[] = "ipv4only.arpa.";
2414 constexpr char host_name[] = "v4only.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09002415 const std::vector<DnsRecord> records = {
2416 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2417 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2418 };
nuccachena26cc2a2018-07-17 18:07:23 +08002419
Xiao Ma09b71022018-12-11 17:56:32 +09002420 test::DNSResponder dns(listen_addr);
2421 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002422 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002423 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002424
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002425 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002426 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002427 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002428
2429 // Ensure to synthesize AAAA if AF_INET6 is specified, and not to synthesize AAAA
2430 // in AF_INET case.
2431 addrinfo hints;
2432 memset(&hints, 0, sizeof(hints));
2433 hints.ai_family = AF_INET6;
2434 ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, &hints);
2435 EXPECT_TRUE(result != nullptr);
2436 std::string result_str = ToString(result);
2437 EXPECT_EQ(result_str, "64:ff9b::102:304");
2438
2439 hints.ai_family = AF_INET;
2440 result = safe_getaddrinfo("v4only", nullptr, &hints);
2441 EXPECT_TRUE(result != nullptr);
2442 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2443 result_str = ToString(result);
2444 EXPECT_EQ(result_str, "1.2.3.4");
2445}
nuccachena26cc2a2018-07-17 18:07:23 +08002446
2447TEST_F(ResolverTest, GetAddrInfo_Dns64QueryUnspecifiedV6) {
2448 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002449 constexpr char dns64_name[] = "ipv4only.arpa.";
2450 constexpr char host_name[] = "v4v6.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09002451 const std::vector<DnsRecord> records = {
2452 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2453 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2454 {host_name, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
2455 };
nuccachena26cc2a2018-07-17 18:07:23 +08002456
Xiao Ma09b71022018-12-11 17:56:32 +09002457 test::DNSResponder dns(listen_addr);
2458 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002459 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002460 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002461
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002462 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002463 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002464 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002465
Xiao Ma09b71022018-12-11 17:56:32 +09002466 const addrinfo hints = {.ai_family = AF_UNSPEC};
nuccachena26cc2a2018-07-17 18:07:23 +08002467 ScopedAddrinfo result = safe_getaddrinfo("v4v6", nullptr, &hints);
2468 EXPECT_TRUE(result != nullptr);
2469 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2470
2471 // In AF_UNSPEC case, do not synthesize AAAA if there's at least one AAAA answer.
Xiao Ma09b71022018-12-11 17:56:32 +09002472 const std::vector<std::string> result_strs = ToStrings(result);
nuccachena26cc2a2018-07-17 18:07:23 +08002473 for (const auto& str : result_strs) {
2474 EXPECT_TRUE(str == "1.2.3.4" || str == "2001:db8::102:304")
2475 << ", result_str='" << str << "'";
2476 }
2477}
2478
2479TEST_F(ResolverTest, GetAddrInfo_Dns64QueryUnspecifiedNoV6) {
2480 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002481 constexpr char dns64_name[] = "ipv4only.arpa.";
2482 constexpr char host_name[] = "v4v6.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09002483 const std::vector<DnsRecord> records = {
2484 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2485 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2486 };
nuccachena26cc2a2018-07-17 18:07:23 +08002487
Xiao Ma09b71022018-12-11 17:56:32 +09002488 test::DNSResponder dns(listen_addr);
2489 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002490 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002491 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002492
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002493 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002494 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002495 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002496
Xiao Ma09b71022018-12-11 17:56:32 +09002497 const addrinfo hints = {.ai_family = AF_UNSPEC};
nuccachena26cc2a2018-07-17 18:07:23 +08002498 ScopedAddrinfo result = safe_getaddrinfo("v4v6", nullptr, &hints);
2499 EXPECT_TRUE(result != nullptr);
2500 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2501
2502 // In AF_UNSPEC case, synthesize AAAA if there's no AAAA answer.
2503 std::string result_str = ToString(result);
2504 EXPECT_EQ(result_str, "64:ff9b::102:304");
2505}
2506
2507TEST_F(ResolverTest, GetAddrInfo_Dns64QuerySpecialUseIPv4Addresses) {
2508 constexpr char THIS_NETWORK[] = "this_network";
2509 constexpr char LOOPBACK[] = "loopback";
2510 constexpr char LINK_LOCAL[] = "link_local";
2511 constexpr char MULTICAST[] = "multicast";
2512 constexpr char LIMITED_BROADCAST[] = "limited_broadcast";
2513
2514 constexpr char ADDR_THIS_NETWORK[] = "0.0.0.1";
2515 constexpr char ADDR_LOOPBACK[] = "127.0.0.1";
2516 constexpr char ADDR_LINK_LOCAL[] = "169.254.0.1";
2517 constexpr char ADDR_MULTICAST[] = "224.0.0.1";
2518 constexpr char ADDR_LIMITED_BROADCAST[] = "255.255.255.255";
2519
2520 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002521 constexpr char dns64_name[] = "ipv4only.arpa.";
2522
Xiao Ma09b71022018-12-11 17:56:32 +09002523 test::DNSResponder dns(listen_addr);
2524 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
nuccachena26cc2a2018-07-17 18:07:23 +08002525 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002526 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002527
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002528 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002529 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002530 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002531
2532 static const struct TestConfig {
2533 std::string name;
2534 std::string addr;
2535
2536 std::string asHostName() const { return StringPrintf("%s.example.com.", name.c_str()); }
2537 } testConfigs[]{
2538 {THIS_NETWORK, ADDR_THIS_NETWORK},
2539 {LOOPBACK, ADDR_LOOPBACK},
2540 {LINK_LOCAL, ADDR_LINK_LOCAL},
2541 {MULTICAST, ADDR_MULTICAST},
2542 {LIMITED_BROADCAST, ADDR_LIMITED_BROADCAST}
2543 };
2544
2545 for (const auto& config : testConfigs) {
2546 const std::string testHostName = config.asHostName();
2547 SCOPED_TRACE(testHostName);
2548
2549 const char* host_name = testHostName.c_str();
2550 dns.addMapping(host_name, ns_type::ns_t_a, config.addr.c_str());
2551
2552 addrinfo hints;
2553 memset(&hints, 0, sizeof(hints));
2554 hints.ai_family = AF_INET6;
2555 ScopedAddrinfo result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
2556 // In AF_INET6 case, don't return IPv4 answers
2557 EXPECT_TRUE(result == nullptr);
2558 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2559 dns.clearQueries();
2560
2561 memset(&hints, 0, sizeof(hints));
2562 hints.ai_family = AF_UNSPEC;
2563 result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
2564 EXPECT_TRUE(result != nullptr);
2565 // Expect IPv6 query only. IPv4 answer has been cached in previous query.
2566 EXPECT_LE(1U, GetNumQueries(dns, host_name));
2567 // In AF_UNSPEC case, don't synthesize special use IPv4 address.
2568 std::string result_str = ToString(result);
2569 EXPECT_EQ(result_str, config.addr.c_str());
2570 dns.clearQueries();
2571 }
2572}
2573
2574TEST_F(ResolverTest, GetAddrInfo_Dns64QueryWithNullArgumentHints) {
2575 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002576 constexpr char dns64_name[] = "ipv4only.arpa.";
2577 constexpr char host_name[] = "v4only.example.com.";
2578 constexpr char host_name2[] = "v4v6.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09002579 const std::vector<DnsRecord> records = {
2580 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2581 {host_name, ns_type::ns_t_a, "1.2.3.4"},
2582 {host_name2, ns_type::ns_t_a, "1.2.3.4"},
2583 {host_name2, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
2584 };
nuccachena26cc2a2018-07-17 18:07:23 +08002585
Xiao Ma09b71022018-12-11 17:56:32 +09002586 test::DNSResponder dns(listen_addr);
2587 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002588 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002589 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002590
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002591 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002592 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002593 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002594
2595 // Assign argument hints of getaddrinfo() as null is equivalent to set ai_family AF_UNSPEC.
2596 // In AF_UNSPEC case, synthesize AAAA if there has A answer only.
2597 ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, nullptr);
2598 EXPECT_TRUE(result != nullptr);
2599 EXPECT_LE(2U, GetNumQueries(dns, host_name));
2600 std::string result_str = ToString(result);
2601 EXPECT_EQ(result_str, "64:ff9b::102:304");
2602 dns.clearQueries();
2603
2604 // In AF_UNSPEC case, do not synthesize AAAA if there's at least one AAAA answer.
2605 result = safe_getaddrinfo("v4v6", nullptr, nullptr);
2606 EXPECT_TRUE(result != nullptr);
2607 EXPECT_LE(2U, GetNumQueries(dns, host_name2));
2608 std::vector<std::string> result_strs = ToStrings(result);
2609 for (const auto& str : result_strs) {
2610 EXPECT_TRUE(str == "1.2.3.4" || str == "2001:db8::102:304")
2611 << ", result_str='" << str << "'";
2612 }
2613}
2614
2615TEST_F(ResolverTest, GetAddrInfo_Dns64QueryNullArgumentNode) {
2616 constexpr char ADDR_ANYADDR_V4[] = "0.0.0.0";
2617 constexpr char ADDR_ANYADDR_V6[] = "::";
2618 constexpr char ADDR_LOCALHOST_V4[] = "127.0.0.1";
2619 constexpr char ADDR_LOCALHOST_V6[] = "::1";
2620
2621 constexpr char PORT_NAME_HTTP[] = "http";
2622 constexpr char PORT_NUMBER_HTTP[] = "80";
2623
2624 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002625 constexpr char dns64_name[] = "ipv4only.arpa.";
2626
Xiao Ma09b71022018-12-11 17:56:32 +09002627 test::DNSResponder dns(listen_addr);
2628 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
nuccachena26cc2a2018-07-17 18:07:23 +08002629 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002630 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002631
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002632 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002633 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002634 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002635
2636 // If node is null, return address is listed by libc/getaddrinfo.c as follows.
2637 // - passive socket -> anyaddr (0.0.0.0 or ::)
2638 // - non-passive socket -> localhost (127.0.0.1 or ::1)
2639 static const struct TestConfig {
2640 int flag;
2641 std::string addr_v4;
2642 std::string addr_v6;
2643
2644 std::string asParameters() const {
2645 return StringPrintf("flag=%d, addr_v4=%s, addr_v6=%s", flag, addr_v4.c_str(),
2646 addr_v6.c_str());
2647 }
2648 } testConfigs[]{
2649 {0 /* non-passive */, ADDR_LOCALHOST_V4, ADDR_LOCALHOST_V6},
2650 {AI_PASSIVE, ADDR_ANYADDR_V4, ADDR_ANYADDR_V6}
2651 };
2652
2653 for (const auto& config : testConfigs) {
2654 SCOPED_TRACE(config.asParameters());
2655
Xiao Ma09b71022018-12-11 17:56:32 +09002656 addrinfo hints = {
Nick Desaulnierscd6395a2019-10-11 09:15:24 -07002657 .ai_flags = config.flag,
Xiao Ma09b71022018-12-11 17:56:32 +09002658 .ai_family = AF_UNSPEC, // any address family
2659 .ai_socktype = 0, // any type
2660 .ai_protocol = 0, // any protocol
Xiao Ma09b71022018-12-11 17:56:32 +09002661 };
nuccachena26cc2a2018-07-17 18:07:23 +08002662
2663 // Assign hostname as null and service as port name.
2664 ScopedAddrinfo result = safe_getaddrinfo(nullptr, PORT_NAME_HTTP, &hints);
2665 ASSERT_TRUE(result != nullptr);
2666
2667 // Can't be synthesized because it should not get into Netd.
2668 std::vector<std::string> result_strs = ToStrings(result);
2669 for (const auto& str : result_strs) {
2670 EXPECT_TRUE(str == config.addr_v4 || str == config.addr_v6)
2671 << ", result_str='" << str << "'";
2672 }
2673
2674 // Assign hostname as null and service as numeric port number.
2675 hints.ai_flags = config.flag | AI_NUMERICSERV;
2676 result = safe_getaddrinfo(nullptr, PORT_NUMBER_HTTP, &hints);
2677 ASSERT_TRUE(result != nullptr);
2678
2679 // Can't be synthesized because it should not get into Netd.
2680 result_strs = ToStrings(result);
2681 for (const auto& str : result_strs) {
2682 EXPECT_TRUE(str == config.addr_v4 || str == config.addr_v6)
2683 << ", result_str='" << str << "'";
2684 }
2685 }
2686}
2687
2688TEST_F(ResolverTest, GetHostByAddr_ReverseDnsQueryWithHavingNat64Prefix) {
2689 struct hostent* result = nullptr;
2690 struct in_addr v4addr;
2691 struct in6_addr v6addr;
2692
2693 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002694 constexpr char dns64_name[] = "ipv4only.arpa.";
2695 constexpr char ptr_name[] = "v4v6.example.com.";
2696 // PTR record for IPv4 address 1.2.3.4
2697 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2698 // PTR record for IPv6 address 2001:db8::102:304
2699 constexpr char ptr_addr_v6[] =
2700 "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 +09002701 const std::vector<DnsRecord> records = {
2702 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2703 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2704 {ptr_addr_v6, ns_type::ns_t_ptr, ptr_name},
2705 };
nuccachena26cc2a2018-07-17 18:07:23 +08002706
Xiao Ma09b71022018-12-11 17:56:32 +09002707 test::DNSResponder dns(listen_addr);
2708 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002709 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002710 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002711
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002712 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002713 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002714 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002715
2716 // Reverse IPv4 DNS query. Prefix should have no effect on it.
2717 inet_pton(AF_INET, "1.2.3.4", &v4addr);
2718 result = gethostbyaddr(&v4addr, sizeof(v4addr), AF_INET);
2719 ASSERT_TRUE(result != nullptr);
2720 std::string result_str = result->h_name ? result->h_name : "null";
2721 EXPECT_EQ(result_str, "v4v6.example.com");
2722
2723 // Reverse IPv6 DNS query. Prefix should have no effect on it.
2724 inet_pton(AF_INET6, "2001:db8::102:304", &v6addr);
2725 result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2726 ASSERT_TRUE(result != nullptr);
2727 result_str = result->h_name ? result->h_name : "null";
2728 EXPECT_EQ(result_str, "v4v6.example.com");
2729}
2730
2731TEST_F(ResolverTest, GetHostByAddr_ReverseDns64Query) {
2732 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002733 constexpr char dns64_name[] = "ipv4only.arpa.";
2734 constexpr char ptr_name[] = "v4only.example.com.";
2735 // PTR record for IPv4 address 1.2.3.4
2736 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2737 // PTR record for IPv6 address 64:ff9b::1.2.3.4
2738 constexpr char ptr_addr_v6_nomapping[] =
2739 "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.";
2740 constexpr char ptr_name_v6_synthesis[] = "v6synthesis.example.com.";
2741 // PTR record for IPv6 address 64:ff9b::5.6.7.8
2742 constexpr char ptr_addr_v6_synthesis[] =
2743 "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 +09002744 const std::vector<DnsRecord> records = {
2745 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2746 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2747 {ptr_addr_v6_synthesis, ns_type::ns_t_ptr, ptr_name_v6_synthesis},
2748 };
nuccachena26cc2a2018-07-17 18:07:23 +08002749
Xiao Ma09b71022018-12-11 17:56:32 +09002750 test::DNSResponder dns(listen_addr);
2751 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002752 // "ptr_addr_v6_nomapping" is not mapped in DNS server
nuccachena26cc2a2018-07-17 18:07:23 +08002753 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002754 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002755
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002756 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002757 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002758 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002759
2760 // Synthesized PTR record doesn't exist on DNS server
2761 // Reverse IPv6 DNS64 query while DNS server doesn't have an answer for synthesized address.
2762 // After querying synthesized address failed, expect that prefix is removed from IPv6
2763 // synthesized address and do reverse IPv4 query instead.
2764 struct in6_addr v6addr;
2765 inet_pton(AF_INET6, "64:ff9b::1.2.3.4", &v6addr);
2766 struct hostent* result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2767 ASSERT_TRUE(result != nullptr);
2768 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_nomapping)); // PTR record not exist
2769 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4)); // PTR record exist
2770 std::string result_str = result->h_name ? result->h_name : "null";
2771 EXPECT_EQ(result_str, "v4only.example.com");
2772 // Check that return address has been mapped from IPv4 to IPv6 address because Netd
2773 // removes NAT64 prefix and does IPv4 DNS reverse lookup in this case. Then, Netd
2774 // fakes the return IPv4 address as original queried IPv6 address.
2775 result_str = ToString(result);
2776 EXPECT_EQ(result_str, "64:ff9b::102:304");
2777 dns.clearQueries();
2778
2779 // Synthesized PTR record exists on DNS server
2780 // Reverse IPv6 DNS64 query while DNS server has an answer for synthesized address.
2781 // Expect to Netd pass through synthesized address for DNS queries.
2782 inet_pton(AF_INET6, "64:ff9b::5.6.7.8", &v6addr);
2783 result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2784 ASSERT_TRUE(result != nullptr);
2785 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_synthesis));
2786 result_str = result->h_name ? result->h_name : "null";
2787 EXPECT_EQ(result_str, "v6synthesis.example.com");
2788}
2789
2790TEST_F(ResolverTest, GetHostByAddr_ReverseDns64QueryFromHostFile) {
2791 constexpr char dns64_name[] = "ipv4only.arpa.";
2792 constexpr char host_name[] = "localhost";
2793 // The address is synthesized by prefix64:localhost.
2794 constexpr char host_addr[] = "64:ff9b::7f00:1";
nuccachena26cc2a2018-07-17 18:07:23 +08002795 constexpr char listen_addr[] = "::1";
Xiao Ma09b71022018-12-11 17:56:32 +09002796
2797 test::DNSResponder dns(listen_addr);
2798 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
nuccachena26cc2a2018-07-17 18:07:23 +08002799 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002800 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002801
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002802 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002803 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002804 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002805
2806 // Using synthesized "localhost" address to be a trick for resolving host name
2807 // from host file /etc/hosts and "localhost" is the only name in /etc/hosts. Note that this is
2808 // not realistic: the code never synthesizes AAAA records for addresses in 127.0.0.0/8.
2809 struct in6_addr v6addr;
2810 inet_pton(AF_INET6, host_addr, &v6addr);
2811 struct hostent* result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
2812 ASSERT_TRUE(result != nullptr);
2813 // Expect no DNS queries; localhost is resolved via /etc/hosts.
2814 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
2815
2816 ASSERT_EQ(sizeof(in6_addr), (unsigned) result->h_length);
2817 ASSERT_EQ(AF_INET6, result->h_addrtype);
2818 std::string result_str = ToString(result);
2819 EXPECT_EQ(result_str, host_addr);
2820 result_str = result->h_name ? result->h_name : "null";
2821 EXPECT_EQ(result_str, host_name);
2822}
2823
Hungming Chen9e6185a2019-06-04 16:09:19 +08002824TEST_F(ResolverTest, GetHostByAddr_cnamesClasslessReverseDelegation) {
2825 // IPv4 addresses in the subnet with notation '/' or '-'.
2826 constexpr char addr_slash[] = "192.0.2.1";
2827 constexpr char addr_hyphen[] = "192.0.3.1";
2828
2829 // Used to verify DNS reverse query for classless reverse lookup zone. See detail in RFC 2317
2830 // section 4.
2831 const static std::vector<DnsRecord> records = {
2832 // The records for reverse querying "192.0.2.1" in the subnet with notation '/'.
2833 {"1.2.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0/25.2.0.192.in-addr.arpa."},
2834 {"1.0/25.2.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
2835
2836 // The records for reverse querying "192.0.3.1" in the subnet with notation '-'.
2837 {"1.3.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0-127.3.0.192.in-addr.arpa."},
2838 {"1.0-127.3.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
2839 };
2840
2841 test::DNSResponder dns;
2842 StartDns(dns, records);
2843 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
2844
2845 for (const auto& address : {addr_slash, addr_hyphen}) {
2846 SCOPED_TRACE(address);
2847
2848 in_addr v4addr;
2849 ASSERT_TRUE(inet_pton(AF_INET, address, &v4addr));
2850 hostent* result = gethostbyaddr(&v4addr, sizeof(v4addr), AF_INET);
2851 ASSERT_TRUE(result != nullptr);
2852 EXPECT_STREQ("hello.example.com", result->h_name);
2853 }
2854}
2855
nuccachena26cc2a2018-07-17 18:07:23 +08002856TEST_F(ResolverTest, GetNameInfo_ReverseDnsQueryWithHavingNat64Prefix) {
2857 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002858 constexpr char dns64_name[] = "ipv4only.arpa.";
2859 constexpr char ptr_name[] = "v4v6.example.com.";
2860 // PTR record for IPv4 address 1.2.3.4
2861 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2862 // PTR record for IPv6 address 2001:db8::102:304
2863 constexpr char ptr_addr_v6[] =
2864 "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 +09002865 const std::vector<DnsRecord> records = {
2866 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2867 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2868 {ptr_addr_v6, ns_type::ns_t_ptr, ptr_name},
2869 };
nuccachena26cc2a2018-07-17 18:07:23 +08002870
Xiao Ma09b71022018-12-11 17:56:32 +09002871 test::DNSResponder dns(listen_addr);
2872 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002873 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002874 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002875
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002876 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002877 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002878 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002879
2880 static const struct TestConfig {
2881 int flag;
2882 int family;
2883 std::string addr;
2884 std::string host;
2885
2886 std::string asParameters() const {
2887 return StringPrintf("flag=%d, family=%d, addr=%s, host=%s", flag, family, addr.c_str(),
2888 host.c_str());
2889 }
2890 } testConfigs[]{
2891 {NI_NAMEREQD, AF_INET, "1.2.3.4", "v4v6.example.com"},
2892 {NI_NUMERICHOST, AF_INET, "1.2.3.4", "1.2.3.4"},
2893 {0, AF_INET, "1.2.3.4", "v4v6.example.com"},
2894 {0, AF_INET, "5.6.7.8", "5.6.7.8"}, // unmapped
2895 {NI_NAMEREQD, AF_INET6, "2001:db8::102:304", "v4v6.example.com"},
2896 {NI_NUMERICHOST, AF_INET6, "2001:db8::102:304", "2001:db8::102:304"},
2897 {0, AF_INET6, "2001:db8::102:304", "v4v6.example.com"},
2898 {0, AF_INET6, "2001:db8::506:708", "2001:db8::506:708"}, // unmapped
2899 };
2900
2901 // Reverse IPv4/IPv6 DNS query. Prefix should have no effect on it.
2902 for (const auto& config : testConfigs) {
2903 SCOPED_TRACE(config.asParameters());
2904
2905 int rv;
2906 char host[NI_MAXHOST];
2907 struct sockaddr_in sin;
2908 struct sockaddr_in6 sin6;
2909 if (config.family == AF_INET) {
2910 memset(&sin, 0, sizeof(sin));
2911 sin.sin_family = AF_INET;
2912 inet_pton(AF_INET, config.addr.c_str(), &sin.sin_addr);
2913 rv = getnameinfo((const struct sockaddr*) &sin, sizeof(sin), host, sizeof(host),
2914 nullptr, 0, config.flag);
2915 if (config.flag == NI_NAMEREQD) EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4));
2916 } else if (config.family == AF_INET6) {
2917 memset(&sin6, 0, sizeof(sin6));
2918 sin6.sin6_family = AF_INET6;
2919 inet_pton(AF_INET6, config.addr.c_str(), &sin6.sin6_addr);
2920 rv = getnameinfo((const struct sockaddr*) &sin6, sizeof(sin6), host, sizeof(host),
2921 nullptr, 0, config.flag);
2922 if (config.flag == NI_NAMEREQD) EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6));
2923 }
2924 ASSERT_EQ(0, rv);
2925 std::string result_str = host;
2926 EXPECT_EQ(result_str, config.host);
2927 dns.clearQueries();
2928 }
2929}
2930
2931TEST_F(ResolverTest, GetNameInfo_ReverseDns64Query) {
2932 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08002933 constexpr char dns64_name[] = "ipv4only.arpa.";
2934 constexpr char ptr_name[] = "v4only.example.com.";
2935 // PTR record for IPv4 address 1.2.3.4
2936 constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
2937 // PTR record for IPv6 address 64:ff9b::1.2.3.4
2938 constexpr char ptr_addr_v6_nomapping[] =
2939 "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.";
2940 constexpr char ptr_name_v6_synthesis[] = "v6synthesis.example.com.";
2941 // PTR record for IPv6 address 64:ff9b::5.6.7.8
2942 constexpr char ptr_addr_v6_synthesis[] =
2943 "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 +09002944 const std::vector<DnsRecord> records = {
2945 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
2946 {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
2947 {ptr_addr_v6_synthesis, ns_type::ns_t_ptr, ptr_name_v6_synthesis},
2948 };
nuccachena26cc2a2018-07-17 18:07:23 +08002949
Xiao Ma09b71022018-12-11 17:56:32 +09002950 test::DNSResponder dns(listen_addr);
2951 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08002952 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09002953 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08002954
Lorenzo Colittid39345c2019-02-18 10:59:29 +09002955 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08002956 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08002957 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08002958
2959 static const struct TestConfig {
2960 bool hasSynthesizedPtrRecord;
2961 int flag;
2962 std::string addr;
2963 std::string host;
2964
2965 std::string asParameters() const {
2966 return StringPrintf("hasSynthesizedPtrRecord=%d, flag=%d, addr=%s, host=%s",
2967 hasSynthesizedPtrRecord, flag, addr.c_str(), host.c_str());
2968 }
2969 } testConfigs[]{
2970 {false, NI_NAMEREQD, "64:ff9b::102:304", "v4only.example.com"},
2971 {false, NI_NUMERICHOST, "64:ff9b::102:304", "64:ff9b::102:304"},
2972 {false, 0, "64:ff9b::102:304", "v4only.example.com"},
2973 {true, NI_NAMEREQD, "64:ff9b::506:708", "v6synthesis.example.com"},
2974 {true, NI_NUMERICHOST, "64:ff9b::506:708", "64:ff9b::506:708"},
2975 {true, 0, "64:ff9b::506:708", "v6synthesis.example.com"}
2976 };
2977
2978 // hasSynthesizedPtrRecord = false
2979 // Synthesized PTR record doesn't exist on DNS server
2980 // Reverse IPv6 DNS64 query while DNS server doesn't have an answer for synthesized address.
2981 // After querying synthesized address failed, expect that prefix is removed from IPv6
2982 // synthesized address and do reverse IPv4 query instead.
2983 //
2984 // hasSynthesizedPtrRecord = true
2985 // Synthesized PTR record exists on DNS server
2986 // Reverse IPv6 DNS64 query while DNS server has an answer for synthesized address.
2987 // Expect to just pass through synthesized address for DNS queries.
2988 for (const auto& config : testConfigs) {
2989 SCOPED_TRACE(config.asParameters());
2990
2991 char host[NI_MAXHOST];
2992 struct sockaddr_in6 sin6;
2993 memset(&sin6, 0, sizeof(sin6));
2994 sin6.sin6_family = AF_INET6;
2995 inet_pton(AF_INET6, config.addr.c_str(), &sin6.sin6_addr);
2996 int rv = getnameinfo((const struct sockaddr*) &sin6, sizeof(sin6), host, sizeof(host),
2997 nullptr, 0, config.flag);
2998 ASSERT_EQ(0, rv);
2999 if (config.flag == NI_NAMEREQD) {
3000 if (config.hasSynthesizedPtrRecord) {
3001 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_synthesis));
3002 } else {
3003 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_nomapping)); // PTR record not exist.
3004 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4)); // PTR record exist.
3005 }
3006 }
3007 std::string result_str = host;
3008 EXPECT_EQ(result_str, config.host);
3009 dns.clearQueries();
3010 }
3011}
3012
3013TEST_F(ResolverTest, GetNameInfo_ReverseDns64QueryFromHostFile) {
3014 constexpr char dns64_name[] = "ipv4only.arpa.";
3015 constexpr char host_name[] = "localhost";
3016 // The address is synthesized by prefix64:localhost.
3017 constexpr char host_addr[] = "64:ff9b::7f00:1";
nuccachena26cc2a2018-07-17 18:07:23 +08003018 constexpr char listen_addr[] = "::1";
Xiao Ma09b71022018-12-11 17:56:32 +09003019
3020 test::DNSResponder dns(listen_addr);
3021 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
nuccachena26cc2a2018-07-17 18:07:23 +08003022 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09003023 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08003024
Lorenzo Colittid39345c2019-02-18 10:59:29 +09003025 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08003026 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003027 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08003028
3029 // Using synthesized "localhost" address to be a trick for resolving host name
3030 // from host file /etc/hosts and "localhost" is the only name in /etc/hosts. Note that this is
3031 // not realistic: the code never synthesizes AAAA records for addresses in 127.0.0.0/8.
3032 char host[NI_MAXHOST];
Xiao Ma09b71022018-12-11 17:56:32 +09003033 struct sockaddr_in6 sin6 = {.sin6_family = AF_INET6};
nuccachena26cc2a2018-07-17 18:07:23 +08003034 inet_pton(AF_INET6, host_addr, &sin6.sin6_addr);
3035 int rv = getnameinfo((const struct sockaddr*) &sin6, sizeof(sin6), host, sizeof(host), nullptr,
3036 0, NI_NAMEREQD);
3037 ASSERT_EQ(0, rv);
3038 // Expect no DNS queries; localhost is resolved via /etc/hosts.
3039 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
3040
3041 std::string result_str = host;
3042 EXPECT_EQ(result_str, host_name);
3043}
3044
Hungming Chen9e6185a2019-06-04 16:09:19 +08003045TEST_F(ResolverTest, GetNameInfo_cnamesClasslessReverseDelegation) {
3046 // IPv4 addresses in the subnet with notation '/' or '-'.
3047 constexpr char addr_slash[] = "192.0.2.1";
3048 constexpr char addr_hyphen[] = "192.0.3.1";
3049
3050 // Used to verify DNS reverse query for classless reverse lookup zone. See detail in RFC 2317
3051 // section 4.
3052 const static std::vector<DnsRecord> records = {
3053 // The records for reverse querying "192.0.2.1" in the subnet with notation '/'.
3054 {"1.2.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0/25.2.0.192.in-addr.arpa."},
3055 {"1.0/25.2.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
3056
3057 // The records for reverse querying "192.0.3.1" in the subnet with notation '-'.
3058 {"1.3.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0-127.3.0.192.in-addr.arpa."},
3059 {"1.0-127.3.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
3060 };
3061
3062 test::DNSResponder dns;
3063 StartDns(dns, records);
3064 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
3065
3066 for (const auto& address : {addr_slash, addr_hyphen}) {
3067 SCOPED_TRACE(address);
3068
3069 char host[NI_MAXHOST];
3070 sockaddr_in sin = {.sin_family = AF_INET};
3071 ASSERT_TRUE(inet_pton(AF_INET, address, &sin.sin_addr));
3072 int rv = getnameinfo((const sockaddr*)&sin, sizeof(sin), host, sizeof(host), nullptr, 0,
3073 NI_NAMEREQD);
3074 ASSERT_EQ(0, rv);
3075 EXPECT_STREQ("hello.example.com", host);
3076 }
3077}
3078
nuccachena26cc2a2018-07-17 18:07:23 +08003079TEST_F(ResolverTest, GetHostByName2_Dns64Synthesize) {
Xiao Ma09b71022018-12-11 17:56:32 +09003080 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08003081 constexpr char dns64_name[] = "ipv4only.arpa.";
3082 constexpr char host_name[] = "ipv4only.example.com.";
Xiao Ma09b71022018-12-11 17:56:32 +09003083 const std::vector<DnsRecord> records = {
3084 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3085 {host_name, ns_type::ns_t_a, "1.2.3.4"},
3086 };
nuccachena26cc2a2018-07-17 18:07:23 +08003087
Xiao Ma09b71022018-12-11 17:56:32 +09003088 test::DNSResponder dns(listen_addr);
3089 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08003090 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09003091 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08003092
Lorenzo Colittid39345c2019-02-18 10:59:29 +09003093 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08003094 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003095 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08003096
3097 // Query an IPv4-only hostname. Expect that gets a synthesized address.
3098 struct hostent* result = gethostbyname2("ipv4only", AF_INET6);
3099 ASSERT_TRUE(result != nullptr);
3100 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3101 std::string result_str = ToString(result);
3102 EXPECT_EQ(result_str, "64:ff9b::102:304");
3103}
nuccachena26cc2a2018-07-17 18:07:23 +08003104
3105TEST_F(ResolverTest, GetHostByName2_DnsQueryWithHavingNat64Prefix) {
3106 constexpr char dns64_name[] = "ipv4only.arpa.";
3107 constexpr char host_name[] = "v4v6.example.com.";
nuccachena26cc2a2018-07-17 18:07:23 +08003108 constexpr char listen_addr[] = "::1";
Xiao Ma09b71022018-12-11 17:56:32 +09003109 const std::vector<DnsRecord> records = {
3110 {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
3111 {host_name, ns_type::ns_t_a, "1.2.3.4"},
3112 {host_name, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
3113 };
3114
3115 test::DNSResponder dns(listen_addr);
3116 StartDns(dns, records);
nuccachena26cc2a2018-07-17 18:07:23 +08003117 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09003118 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08003119
Lorenzo Colittid39345c2019-02-18 10:59:29 +09003120 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08003121 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003122 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08003123
3124 // IPv4 DNS query. Prefix should have no effect on it.
3125 struct hostent* result = gethostbyname2("v4v6", AF_INET);
3126 ASSERT_TRUE(result != nullptr);
3127 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3128 std::string result_str = ToString(result);
3129 EXPECT_EQ(result_str, "1.2.3.4");
3130 dns.clearQueries();
3131
3132 // IPv6 DNS query. Prefix should have no effect on it.
3133 result = gethostbyname2("v4v6", AF_INET6);
3134 ASSERT_TRUE(result != nullptr);
3135 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3136 result_str = ToString(result);
3137 EXPECT_EQ(result_str, "2001:db8::102:304");
3138}
3139
3140TEST_F(ResolverTest, GetHostByName2_Dns64QuerySpecialUseIPv4Addresses) {
3141 constexpr char THIS_NETWORK[] = "this_network";
3142 constexpr char LOOPBACK[] = "loopback";
3143 constexpr char LINK_LOCAL[] = "link_local";
3144 constexpr char MULTICAST[] = "multicast";
3145 constexpr char LIMITED_BROADCAST[] = "limited_broadcast";
3146
3147 constexpr char ADDR_THIS_NETWORK[] = "0.0.0.1";
3148 constexpr char ADDR_LOOPBACK[] = "127.0.0.1";
3149 constexpr char ADDR_LINK_LOCAL[] = "169.254.0.1";
3150 constexpr char ADDR_MULTICAST[] = "224.0.0.1";
3151 constexpr char ADDR_LIMITED_BROADCAST[] = "255.255.255.255";
3152
3153 constexpr char listen_addr[] = "::1";
nuccachena26cc2a2018-07-17 18:07:23 +08003154 constexpr char dns64_name[] = "ipv4only.arpa.";
3155
Xiao Ma09b71022018-12-11 17:56:32 +09003156 test::DNSResponder dns(listen_addr);
3157 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::"}});
nuccachena26cc2a2018-07-17 18:07:23 +08003158 const std::vector<std::string> servers = {listen_addr};
Xiao Ma09b71022018-12-11 17:56:32 +09003159 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
nuccachena26cc2a2018-07-17 18:07:23 +08003160
Lorenzo Colittid39345c2019-02-18 10:59:29 +09003161 // Start NAT64 prefix discovery and wait for it to complete.
Luke Huang5bd827c2019-03-14 16:10:04 +08003162 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003163 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
nuccachena26cc2a2018-07-17 18:07:23 +08003164
3165 static const struct TestConfig {
3166 std::string name;
3167 std::string addr;
3168
3169 std::string asHostName() const {
3170 return StringPrintf("%s.example.com.",
3171 name.c_str());
3172 }
3173 } testConfigs[]{
3174 {THIS_NETWORK, ADDR_THIS_NETWORK},
3175 {LOOPBACK, ADDR_LOOPBACK},
3176 {LINK_LOCAL, ADDR_LINK_LOCAL},
3177 {MULTICAST, ADDR_MULTICAST},
3178 {LIMITED_BROADCAST, ADDR_LIMITED_BROADCAST}
3179 };
3180
3181 for (const auto& config : testConfigs) {
3182 const std::string testHostName = config.asHostName();
3183 SCOPED_TRACE(testHostName);
3184
3185 const char* host_name = testHostName.c_str();
3186 dns.addMapping(host_name, ns_type::ns_t_a, config.addr.c_str());
3187
3188 struct hostent* result = gethostbyname2(config.name.c_str(), AF_INET6);
3189 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3190
3191 // In AF_INET6 case, don't synthesize special use IPv4 address.
3192 // Expect to have no answer
3193 EXPECT_EQ(nullptr, result);
3194
3195 dns.clearQueries();
3196 }
Bernie Innocenti2fef2b82018-12-20 15:56:40 +09003197}
Mike Yuf14e1a92019-05-10 13:54:58 +08003198
3199TEST_F(ResolverTest, PrefixDiscoveryBypassTls) {
3200 constexpr char listen_addr[] = "::1";
3201 constexpr char cleartext_port[] = "53";
3202 constexpr char tls_port[] = "853";
3203 constexpr char dns64_name[] = "ipv4only.arpa.";
3204 const std::vector<std::string> servers = {listen_addr};
3205
3206 test::DNSResponder dns(listen_addr);
3207 StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
3208 test::DnsTlsFrontend tls(listen_addr, tls_port, listen_addr, cleartext_port);
3209 ASSERT_TRUE(tls.startServer());
3210
3211 // Setup OPPORTUNISTIC mode and wait for the validation complete.
waynema0e73c2e2019-07-31 15:04:08 +08003212 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams, ""));
Mike Yu724f77d2019-08-16 11:14:50 +08003213 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
Mike Yuf14e1a92019-05-10 13:54:58 +08003214 tls.clearQueries();
3215
3216 // Start NAT64 prefix discovery and wait for it complete.
3217 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003218 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
Mike Yuf14e1a92019-05-10 13:54:58 +08003219
3220 // Verify it bypassed TLS even though there's a TLS server available.
3221 EXPECT_EQ(0, tls.queries());
3222 EXPECT_EQ(1U, GetNumQueries(dns, dns64_name));
3223
3224 // Restart the testing network to reset the cache.
3225 mDnsClient.TearDown();
3226 mDnsClient.SetUp();
3227 dns.clearQueries();
3228
3229 // Setup STRICT mode and wait for the validation complete.
waynema0e73c2e2019-07-31 15:04:08 +08003230 ASSERT_TRUE(mDnsClient.SetResolversWithTls(servers, kDefaultSearchDomains, kDefaultParams,
3231 kDefaultPrivateDnsHostName));
Mike Yu724f77d2019-08-16 11:14:50 +08003232 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
Mike Yuf14e1a92019-05-10 13:54:58 +08003233 tls.clearQueries();
3234
3235 // Start NAT64 prefix discovery and wait for it to complete.
3236 EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
Hungming Chene8f970c2019-04-10 17:34:06 +08003237 EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
Mike Yuf14e1a92019-05-10 13:54:58 +08003238
3239 // Verify it bypassed TLS despite STRICT mode.
3240 EXPECT_EQ(0, tls.queries());
3241 EXPECT_EQ(1U, GetNumQueries(dns, dns64_name));
3242}
Luke Huang9807e6b2019-05-20 16:17:12 +08003243
3244namespace {
3245
Luke Huang0d592bc2019-05-25 18:24:03 +08003246class ScopedSetNetworkForProcess {
3247 public:
3248 explicit ScopedSetNetworkForProcess(unsigned netId) {
3249 mStoredNetId = getNetworkForProcess();
3250 if (netId == mStoredNetId) return;
3251 EXPECT_EQ(0, setNetworkForProcess(netId));
3252 }
3253 ~ScopedSetNetworkForProcess() { EXPECT_EQ(0, setNetworkForProcess(mStoredNetId)); }
3254
3255 private:
3256 unsigned mStoredNetId;
3257};
3258
3259class ScopedSetNetworkForResolv {
3260 public:
3261 explicit ScopedSetNetworkForResolv(unsigned netId) { EXPECT_EQ(0, setNetworkForResolv(netId)); }
3262 ~ScopedSetNetworkForResolv() { EXPECT_EQ(0, setNetworkForResolv(NETID_UNSET)); }
3263};
3264
Luke Huang9807e6b2019-05-20 16:17:12 +08003265void sendCommand(int fd, const std::string& cmd) {
3266 ssize_t rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size() + 1));
3267 EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size() + 1));
3268}
3269
3270int32_t readBE32(int fd) {
3271 int32_t tmp;
3272 int n = TEMP_FAILURE_RETRY(read(fd, &tmp, sizeof(tmp)));
3273 EXPECT_TRUE(n > 0);
3274 return ntohl(tmp);
3275}
3276
Luke Huang0d592bc2019-05-25 18:24:03 +08003277int readResponseCode(int fd) {
Luke Huang9807e6b2019-05-20 16:17:12 +08003278 char buf[4];
3279 int n = TEMP_FAILURE_RETRY(read(fd, &buf, sizeof(buf)));
3280 EXPECT_TRUE(n > 0);
3281 // The format of response code is that 4 bytes for the code & null.
3282 buf[3] = '\0';
3283 int result;
3284 EXPECT_TRUE(ParseInt(buf, &result));
3285 return result;
3286}
3287
Luke Huang0d592bc2019-05-25 18:24:03 +08003288bool checkAndClearUseLocalNameserversFlag(unsigned* netid) {
3289 if (netid == nullptr || ((*netid) & NETID_USE_LOCAL_NAMESERVERS) == 0) {
3290 return false;
3291 }
3292 *netid = (*netid) & ~NETID_USE_LOCAL_NAMESERVERS;
3293 return true;
3294}
3295
3296android::net::UidRangeParcel makeUidRangeParcel(int start, int stop) {
3297 android::net::UidRangeParcel res;
3298 res.start = start;
3299 res.stop = stop;
3300
3301 return res;
3302}
3303
3304void expectNetIdWithLocalNameserversFlag(unsigned netId) {
3305 unsigned dnsNetId = 0;
3306 EXPECT_EQ(0, getNetworkForDns(&dnsNetId));
3307 EXPECT_TRUE(checkAndClearUseLocalNameserversFlag(&dnsNetId));
3308 EXPECT_EQ(netId, static_cast<unsigned>(dnsNetId));
3309}
3310
3311void expectDnsNetIdEquals(unsigned netId) {
3312 unsigned dnsNetId = 0;
3313 EXPECT_EQ(0, getNetworkForDns(&dnsNetId));
3314 EXPECT_EQ(netId, static_cast<unsigned>(dnsNetId));
3315}
3316
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +09003317void expectDnsNetIdIsDefaultNetwork(INetd* netdService) {
Luke Huang0d592bc2019-05-25 18:24:03 +08003318 int currentNetid;
3319 EXPECT_TRUE(netdService->networkGetDefault(&currentNetid).isOk());
3320 expectDnsNetIdEquals(currentNetid);
3321}
3322
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +09003323void expectDnsNetIdWithVpn(INetd* netdService, unsigned vpnNetId, unsigned expectedNetId) {
Luke Huang0d592bc2019-05-25 18:24:03 +08003324 EXPECT_TRUE(netdService->networkCreateVpn(vpnNetId, false /* secure */).isOk());
3325 uid_t uid = getuid();
3326 // Add uid to VPN
3327 EXPECT_TRUE(netdService->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3328 expectDnsNetIdEquals(expectedNetId);
3329 EXPECT_TRUE(netdService->networkDestroy(vpnNetId).isOk());
3330}
3331
Luke Huang9807e6b2019-05-20 16:17:12 +08003332} // namespace
3333
3334TEST_F(ResolverTest, getDnsNetId) {
3335 // We've called setNetworkForProcess in SetupOemNetwork, so reset to default first.
3336 setNetworkForProcess(NETID_UNSET);
Luke Huang0d592bc2019-05-25 18:24:03 +08003337
3338 expectDnsNetIdIsDefaultNetwork(mDnsClient.netdService());
3339 expectDnsNetIdWithVpn(mDnsClient.netdService(), TEST_VPN_NETID, TEST_VPN_NETID);
Luke Huang9807e6b2019-05-20 16:17:12 +08003340
3341 // Test with setNetworkForProcess
Luke Huang0d592bc2019-05-25 18:24:03 +08003342 {
3343 ScopedSetNetworkForProcess scopedSetNetworkForProcess(TEST_NETID);
3344 expectDnsNetIdEquals(TEST_NETID);
3345 }
3346
3347 // Test with setNetworkForProcess with NETID_USE_LOCAL_NAMESERVERS
3348 {
3349 ScopedSetNetworkForProcess scopedSetNetworkForProcess(TEST_NETID |
3350 NETID_USE_LOCAL_NAMESERVERS);
3351 expectNetIdWithLocalNameserversFlag(TEST_NETID);
3352 }
Luke Huang9807e6b2019-05-20 16:17:12 +08003353
3354 // Test with setNetworkForResolv
Luke Huang0d592bc2019-05-25 18:24:03 +08003355 {
3356 ScopedSetNetworkForResolv scopedSetNetworkForResolv(TEST_NETID);
3357 expectDnsNetIdEquals(TEST_NETID);
3358 }
3359
3360 // Test with setNetworkForResolv with NETID_USE_LOCAL_NAMESERVERS
3361 {
3362 ScopedSetNetworkForResolv scopedSetNetworkForResolv(TEST_NETID |
3363 NETID_USE_LOCAL_NAMESERVERS);
3364 expectNetIdWithLocalNameserversFlag(TEST_NETID);
3365 }
3366
3367 // Test with setNetworkForResolv under bypassable vpn
3368 {
3369 ScopedSetNetworkForResolv scopedSetNetworkForResolv(TEST_NETID);
3370 expectDnsNetIdWithVpn(mDnsClient.netdService(), TEST_VPN_NETID, TEST_NETID);
3371 }
Luke Huang9807e6b2019-05-20 16:17:12 +08003372
3373 // Create socket connected to DnsProxyListener
3374 int fd = dns_open_proxy();
3375 EXPECT_TRUE(fd > 0);
3376 unique_fd ufd(fd);
3377
3378 // Test command with wrong netId
3379 sendCommand(fd, "getdnsnetid abc");
Luke Huang0d592bc2019-05-25 18:24:03 +08003380 EXPECT_EQ(ResponseCode::DnsProxyQueryResult, readResponseCode(fd));
Luke Huang9807e6b2019-05-20 16:17:12 +08003381 EXPECT_EQ(-EINVAL, readBE32(fd));
3382
3383 // Test unsupported command
3384 sendCommand(fd, "getdnsnetidNotSupported");
3385 // Keep in sync with FrameworkListener.cpp (500, "Command not recognized")
Luke Huang0d592bc2019-05-25 18:24:03 +08003386 EXPECT_EQ(500, readResponseCode(fd));
Luke Huang9807e6b2019-05-20 16:17:12 +08003387}
Sehee Park2c118782019-05-07 13:02:45 +09003388
3389TEST_F(ResolverTest, BlockDnsQueryWithUidRule) {
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +09003390 // This test relies on blocking traffic on loopback, which xt_qtaguid does not do.
3391 // See aosp/358413 and b/34444781 for why.
3392 SKIP_IF_BPF_NOT_SUPPORTED;
3393
Sehee Park2c118782019-05-07 13:02:45 +09003394 constexpr char listen_addr1[] = "127.0.0.4";
3395 constexpr char listen_addr2[] = "::1";
3396 constexpr char host_name[] = "howdy.example.com.";
3397 const std::vector<DnsRecord> records = {
3398 {host_name, ns_type::ns_t_a, "1.2.3.4"},
3399 {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
3400 };
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +09003401 INetd* netdService = mDnsClient.netdService();
Sehee Park2c118782019-05-07 13:02:45 +09003402
3403 test::DNSResponder dns1(listen_addr1);
3404 test::DNSResponder dns2(listen_addr2);
3405 StartDns(dns1, records);
3406 StartDns(dns2, records);
3407
3408 std::vector<std::string> servers = {listen_addr1, listen_addr2};
3409 ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3410 dns1.clearQueries();
3411 dns2.clearQueries();
3412
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +09003413 // Add drop rule for TEST_UID. Also enable the standby chain because it might not be enabled.
3414 // Unfortunately we cannot use FIREWALL_CHAIN_NONE, or custom iptables rules, for this purpose
3415 // because netd calls fchown() on the DNS query sockets, and "iptables -m owner" matches the
3416 // UID of the socket creator, not the UID set by fchown().
3417 //
3418 // TODO: migrate FIREWALL_CHAIN_NONE to eBPF as well.
3419 EXPECT_TRUE(netdService->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true).isOk());
3420 EXPECT_TRUE(netdService
Sehee Park2c118782019-05-07 13:02:45 +09003421 ->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, TEST_UID,
3422 INetd::FIREWALL_RULE_DENY)
3423 .isOk());
3424
3425 // Save uid
3426 int suid = getuid();
3427
3428 // Switch to TEST_UID
3429 EXPECT_TRUE(seteuid(TEST_UID) == 0);
3430
3431 // Dns Query
3432 int fd1 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_a, 0);
3433 int fd2 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_aaaa, 0);
3434 EXPECT_TRUE(fd1 != -1);
3435 EXPECT_TRUE(fd2 != -1);
3436
3437 uint8_t buf[MAXPACKET] = {};
3438 int rcode;
3439 int res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
3440 EXPECT_EQ(-ECONNREFUSED, res);
3441
3442 memset(buf, 0, MAXPACKET);
3443 res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
3444 EXPECT_EQ(-ECONNREFUSED, res);
3445
3446 // Restore uid
3447 EXPECT_TRUE(seteuid(suid) == 0);
3448
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +09003449 // Remove drop rule for TEST_UID, and disable the standby chain.
3450 EXPECT_TRUE(netdService
Sehee Park2c118782019-05-07 13:02:45 +09003451 ->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, TEST_UID,
3452 INetd::FIREWALL_RULE_ALLOW)
3453 .isOk());
Lorenzo Colittieb9aeec2019-06-26 19:53:55 +09003454 EXPECT_TRUE(netdService->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false).isOk());
Sehee Park2c118782019-05-07 13:02:45 +09003455}
Mike Yua772c202019-09-23 17:47:21 +08003456
Mike Yu40e67072019-10-09 21:14:09 +08003457namespace {
3458
3459const std::string kDotConnectTimeoutMsFlag(
3460 "persist.device_config.netd_native.dot_connect_timeout_ms");
3461
3462class ScopedSystemProperties {
3463 public:
3464 explicit ScopedSystemProperties(const std::string& key, const std::string& value)
3465 : mStoredKey(key) {
3466 mStoredValue = android::base::GetProperty(key, "");
3467 android::base::SetProperty(key, value);
3468 }
3469 ~ScopedSystemProperties() { android::base::SetProperty(mStoredKey, mStoredValue); }
3470
3471 private:
3472 std::string mStoredKey;
3473 std::string mStoredValue;
3474};
3475
3476} // namespace
3477
Mike Yua772c202019-09-23 17:47:21 +08003478TEST_F(ResolverTest, ConnectTlsServerTimeout) {
Mike Yu40e67072019-10-09 21:14:09 +08003479 constexpr int expectedTimeout = 1000;
3480 constexpr char hostname1[] = "query1.example.com.";
3481 constexpr char hostname2[] = "query2.example.com.";
Mike Yua772c202019-09-23 17:47:21 +08003482 const std::vector<DnsRecord> records = {
Mike Yu40e67072019-10-09 21:14:09 +08003483 {hostname1, ns_type::ns_t_a, "1.2.3.4"},
3484 {hostname2, ns_type::ns_t_a, "1.2.3.5"},
Mike Yua772c202019-09-23 17:47:21 +08003485 };
3486
3487 test::DNSResponder dns;
3488 StartDns(dns, records);
Mike Yu40e67072019-10-09 21:14:09 +08003489 test::DnsTlsFrontend tls;
Mike Yua772c202019-09-23 17:47:21 +08003490 ASSERT_TRUE(tls.startServer());
3491
Mike Yu40e67072019-10-09 21:14:09 +08003492 // The resolver will adjust the timeout value to 1000ms since the value is too small.
3493 ScopedSystemProperties scopedSystemProperties(kDotConnectTimeoutMsFlag, "100");
Mike Yua772c202019-09-23 17:47:21 +08003494
Mike Yu40e67072019-10-09 21:14:09 +08003495 // Set up resolver to opportunistic mode with the default configuration.
3496 const ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
3497 ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
Mike Yua772c202019-09-23 17:47:21 +08003498 EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
3499 dns.clearQueries();
3500 tls.clearQueries();
3501
3502 // The server becomes unresponsive to the handshake request.
3503 tls.setHangOnHandshakeForTesting(true);
3504
3505 // Expect the things happening in getaddrinfo():
3506 // 1. Connect to the private DNS server.
3507 // 2. SSL handshake times out.
3508 // 3. Fallback to UDP transport, and then get the answer.
Mike Yu40e67072019-10-09 21:14:09 +08003509 const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
3510 auto [result, timeTakenMs] = safe_getaddrinfo_time_taken(hostname1, nullptr, hints);
Mike Yua772c202019-09-23 17:47:21 +08003511
Mike Yu40e67072019-10-09 21:14:09 +08003512 EXPECT_NE(nullptr, result);
Mike Yua772c202019-09-23 17:47:21 +08003513 EXPECT_EQ(0, tls.queries());
Mike Yu40e67072019-10-09 21:14:09 +08003514 EXPECT_EQ(1U, GetNumQueries(dns, hostname1));
3515 EXPECT_EQ(records.at(0).addr, ToString(result));
Mike Yua772c202019-09-23 17:47:21 +08003516
Mike Yu40e67072019-10-09 21:14:09 +08003517 // A loose upper bound is set by adding 2000ms buffer time. Theoretically, getaddrinfo()
3518 // should just take a bit more than expetTimeout milliseconds.
3519 EXPECT_GE(timeTakenMs, expectedTimeout);
3520 EXPECT_LE(timeTakenMs, expectedTimeout + 2000);
3521
3522 // Set the server to be responsive. Verify that the resolver will attempt to reconnect
3523 // to the server and then get the result within the timeout.
3524 tls.setHangOnHandshakeForTesting(false);
3525 std::tie(result, timeTakenMs) = safe_getaddrinfo_time_taken(hostname2, nullptr, hints);
3526
3527 EXPECT_NE(nullptr, result);
3528 EXPECT_EQ(1, tls.queries());
3529 EXPECT_EQ(1U, GetNumQueries(dns, hostname2));
3530 EXPECT_EQ(records.at(1).addr, ToString(result));
3531
3532 EXPECT_LE(timeTakenMs, expectedTimeout);
Mike Yua772c202019-09-23 17:47:21 +08003533}
Hungming Chenbb90ab32019-10-28 18:20:31 +08003534
3535// Parameterized tests.
3536// TODO: Merge the existing tests as parameterized test if possible.
3537// TODO: Perhaps move parameterized tests to an independent file.
3538enum class CallType { GETADDRINFO, GETHOSTBYNAME };
3539class ResolverParameterizedTest : public ResolverTest,
Hungming Chen63779052019-10-30 15:06:13 +08003540 public testing::WithParamInterface<CallType> {
3541 protected:
3542 void VerifyQueryHelloExampleComV4(const test::DNSResponder& dns, const CallType calltype) {
3543 if (calltype == CallType::GETADDRINFO) {
3544 const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
3545 ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
3546 ASSERT_TRUE(result != nullptr);
3547 EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
3548 } else if (calltype == CallType::GETHOSTBYNAME) {
3549 const hostent* result = gethostbyname("hello");
3550 ASSERT_TRUE(result != nullptr);
3551 ASSERT_EQ(4, result->h_length);
3552 ASSERT_FALSE(result->h_addr_list[0] == nullptr);
3553 EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
3554 EXPECT_TRUE(result->h_addr_list[1] == nullptr);
3555 } else {
3556 FAIL() << "Unsupported call type: " << static_cast<uint32_t>(calltype);
3557 }
3558 EXPECT_EQ(1U, GetNumQueries(dns, kHelloExampleCom));
3559 }
3560};
Hungming Chenbb90ab32019-10-28 18:20:31 +08003561
Hungming Chen63779052019-10-30 15:06:13 +08003562INSTANTIATE_TEST_SUITE_P(QueryCallTest, ResolverParameterizedTest,
Hungming Chenbb90ab32019-10-28 18:20:31 +08003563 testing::Values(CallType::GETADDRINFO, CallType::GETHOSTBYNAME),
3564 [](const testing::TestParamInfo<CallType>& info) {
Hungming Chenbb90ab32019-10-28 18:20:31 +08003565 switch (info.param) {
3566 case CallType::GETADDRINFO:
Hungming Chen63779052019-10-30 15:06:13 +08003567 return "GetAddrInfo";
Hungming Chenbb90ab32019-10-28 18:20:31 +08003568 case CallType::GETHOSTBYNAME:
Hungming Chen63779052019-10-30 15:06:13 +08003569 return "GetHostByName";
Hungming Chenbb90ab32019-10-28 18:20:31 +08003570 default:
Hungming Chen63779052019-10-30 15:06:13 +08003571 return "InvalidParameter"; // Should not happen.
Hungming Chenbb90ab32019-10-28 18:20:31 +08003572 }
Hungming Chenbb90ab32019-10-28 18:20:31 +08003573 });
3574
3575TEST_P(ResolverParameterizedTest, AuthoritySectionAndAdditionalSection) {
3576 // DNS response may have more information in authority section and additional section.
3577 // Currently, getanswer() of packages/modules/DnsResolver/getaddrinfo.cpp doesn't parse the
3578 // content of authority section and additional section. Test these sections if they crash
3579 // the resolver, just in case. See also RFC 1035 section 4.1.
3580 const auto& calltype = GetParam();
3581 test::DNSHeader header(kDefaultDnsHeader);
3582
3583 // Create a DNS response which has a authoritative nameserver record in authority
3584 // section and its relevant address record in additional section.
3585 //
3586 // Question
3587 // hello.example.com. IN A
3588 // Answer
3589 // hello.example.com. IN A 1.2.3.4
3590 // Authority:
3591 // hello.example.com. IN NS ns1.example.com.
3592 // Additional:
3593 // ns1.example.com. IN A 5.6.7.8
3594 //
3595 // A response may have only question, answer, and authority section. Current testing response
3596 // should be able to cover this condition.
3597
3598 // Question section.
3599 test::DNSQuestion question{
3600 .qname = {.name = kHelloExampleCom},
3601 .qtype = ns_type::ns_t_a,
3602 .qclass = ns_c_in,
3603 };
3604 header.questions.push_back(std::move(question));
3605
3606 // Answer section.
3607 test::DNSRecord recordAnswer{
3608 .name = {.name = kHelloExampleCom},
3609 .rtype = ns_type::ns_t_a,
3610 .rclass = ns_c_in,
3611 .ttl = 0, // no cache
3612 };
Hungming Chen63779052019-10-30 15:06:13 +08003613 EXPECT_TRUE(test::DNSResponder::fillRdata(kHelloExampleComAddrV4, recordAnswer));
Hungming Chenbb90ab32019-10-28 18:20:31 +08003614 header.answers.push_back(std::move(recordAnswer));
3615
3616 // Authority section.
3617 test::DNSRecord recordAuthority{
3618 .name = {.name = kHelloExampleCom},
3619 .rtype = ns_type::ns_t_ns,
3620 .rclass = ns_c_in,
3621 .ttl = 0, // no cache
3622 };
3623 EXPECT_TRUE(test::DNSResponder::fillRdata("ns1.example.com.", recordAuthority));
3624 header.authorities.push_back(std::move(recordAuthority));
3625
3626 // Additional section.
3627 test::DNSRecord recordAdditional{
3628 .name = {.name = "ns1.example.com."},
3629 .rtype = ns_type::ns_t_a,
3630 .rclass = ns_c_in,
3631 .ttl = 0, // no cache
3632 };
3633 EXPECT_TRUE(test::DNSResponder::fillRdata("5.6.7.8", recordAdditional));
3634 header.additionals.push_back(std::move(recordAdditional));
3635
3636 // Start DNS server.
3637 test::DNSResponder dns(test::DNSResponder::MappingType::DNS_HEADER);
3638 dns.addMappingDnsHeader(kHelloExampleCom, ns_type::ns_t_a, header);
3639 ASSERT_TRUE(dns.startServer());
3640 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
3641 dns.clearQueries();
3642
3643 // Expect that get the address and the resolver doesn't crash.
Hungming Chen63779052019-10-30 15:06:13 +08003644 VerifyQueryHelloExampleComV4(dns, calltype);
3645}
3646
3647TEST_P(ResolverParameterizedTest, MessageCompression) {
3648 const auto& calltype = GetParam();
3649
3650 // The response with compressed domain name by a pointer. See RFC 1035 section 4.1.4.
3651 //
3652 // Ignoring the other fields of the message, the domain name of question section and answer
3653 // section are presented as:
3654 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3655 // 12 | 5 | h |
3656 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3657 // 14 | e | l |
3658 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3659 // 16 | l | o |
3660 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3661 // 18 | 7 | e |
3662 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3663 // 20 | x | a |
3664 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3665 // 22 | m | p |
3666 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3667 // 24 | l | e |
3668 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3669 // 26 | 3 | c |
3670 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3671 // 28 | o | m |
3672 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3673 // 30 | 0 | ... |
3674 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3675 //
3676 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3677 // 35 | 1 1| 12 |
3678 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3679 const std::vector<uint8_t> kResponseAPointer = {
3680 /* Header */
3681 0x00, 0x00, /* Transaction ID: 0x0000 */
3682 0x81, 0x80, /* Flags: qr rd ra */
3683 0x00, 0x01, /* Questions: 1 */
3684 0x00, 0x01, /* Answer RRs: 1 */
3685 0x00, 0x00, /* Authority RRs: 0 */
3686 0x00, 0x00, /* Additional RRs: 0 */
3687 /* Queries */
3688 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
3689 0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name: hello.example.com */
3690 0x00, 0x01, /* Type: A */
3691 0x00, 0x01, /* Class: IN */
3692 /* Answers */
3693 0xc0, 0x0c, /* Name: hello.example.com (a pointer) */
3694 0x00, 0x01, /* Type: A */
3695 0x00, 0x01, /* Class: IN */
3696 0x00, 0x00, 0x00, 0x00, /* Time to live: 0 */
3697 0x00, 0x04, /* Data length: 4 */
3698 0x01, 0x02, 0x03, 0x04 /* Address: 1.2.3.4 */
3699 };
3700
3701 // The response with compressed domain name by a sequence of labels ending with a pointer. See
3702 // RFC 1035 section 4.1.4.
3703 //
3704 // Ignoring the other fields of the message, the domain name of question section and answer
3705 // section are presented as:
3706 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3707 // 12 | 5 | h |
3708 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3709 // 14 | e | l |
3710 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3711 // 16 | l | o |
3712 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3713 // 18 | 7 | e |
3714 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3715 // 20 | x | a |
3716 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3717 // 22 | m | p |
3718 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3719 // 24 | l | e |
3720 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3721 // 26 | 3 | c |
3722 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3723 // 28 | o | m |
3724 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3725 // 30 | 0 | ... |
3726 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3727 //
3728 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3729 // 35 | 5 | h |
3730 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3731 // 37 | e | l |
3732 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3733 // 39 | l | o |
3734 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3735 // 41 | 1 1| 18 |
3736 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3737 const std::vector<uint8_t> kResponseLabelEndingWithAPointer = {
3738 /* Header */
3739 0x00, 0x00, /* Transaction ID: 0x0000 */
3740 0x81, 0x80, /* Flags: qr rd ra */
3741 0x00, 0x01, /* Questions: 1 */
3742 0x00, 0x01, /* Answer RRs: 1 */
3743 0x00, 0x00, /* Authority RRs: 0 */
3744 0x00, 0x00, /* Additional RRs: 0 */
3745 /* Queries */
3746 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
3747 0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name: hello.example.com */
3748 0x00, 0x01, /* Type: A */
3749 0x00, 0x01, /* Class: IN */
3750 /* Answers */
3751 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0xc0,
3752 0x12, /* Name: hello.example.com (a label ending with a pointer) */
3753 0x00, 0x01, /* Type: A */
3754 0x00, 0x01, /* Class: IN */
3755 0x00, 0x00, 0x00, 0x00, /* Time to live: 0 */
3756 0x00, 0x04, /* Data length: 4 */
3757 0x01, 0x02, 0x03, 0x04 /* Address: 1.2.3.4 */
3758 };
3759
3760 for (const auto& response : {kResponseAPointer, kResponseLabelEndingWithAPointer}) {
3761 SCOPED_TRACE(StringPrintf("Hex dump: %s", toHex(makeSlice(response)).c_str()));
3762
3763 test::DNSResponder dns(test::DNSResponder::MappingType::BINARY_PACKET);
3764 dns.addMappingBinaryPacket(kHelloExampleComQueryV4, response);
3765 StartDns(dns, {});
3766 ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
3767
3768 // Expect no cache because the TTL of testing responses are 0.
3769 VerifyQueryHelloExampleComV4(dns, calltype);
Hungming Chenbb90ab32019-10-28 18:20:31 +08003770 }
Mike Yu40e67072019-10-09 21:14:09 +08003771}