1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17 
18 #define LOG_TAG "resolv_integration_test"
19 
20 #include <android-base/logging.h>
21 #include <android-base/parseint.h>
22 #include <android-base/result.h>
23 #include <android-base/unique_fd.h>
24 #include <android/multinetwork.h>  // ResNsendFlags
25 #include <arpa/inet.h>
26 #include <arpa/nameser.h>
27 #include <binder/ProcessState.h>
28 #include <cutils/sockets.h>
29 #include <gmock/gmock-matchers.h>
30 #include <gtest/gtest.h>
31 #include <netdb.h>
32 #include <netdutils/InternetAddresses.h>
33 #include <netdutils/NetNativeTestBase.h>
34 #include <netdutils/NetworkConstants.h>  // SHA256_SIZE
35 #include <netdutils/ResponseCode.h>
36 #include <netdutils/Slice.h>
37 #include <netdutils/SocketOption.h>
38 #include <netdutils/Stopwatch.h>
39 #include <netinet/in.h>
40 #include <poll.h> /* poll */
41 #include <private/android_filesystem_config.h>
42 #include <resolv.h>
43 #include <stdarg.h>
44 #include <stdlib.h>
45 #include <sys/socket.h>
46 #include <sys/un.h>
47 #include <unistd.h>
48 
49 #include <algorithm>
50 #include <chrono>
51 #include <functional>
52 #include <iterator>
53 #include <numeric>
54 #include <string_view>
55 #include <thread>
56 #include <unordered_set>
57 
58 #include <DnsProxydProtocol.h>  // NETID_USE_LOCAL_NAMESERVERS
59 #include <aidl/android/net/IDnsResolver.h>
60 #include <android/binder_manager.h>
61 #include <android/binder_process.h>
62 #include <bpf/BpfUtils.h>
63 #include <util.h>  // getApiLevel
64 #include "Experiments.h"
65 #include "NetdClient.h"
66 #include "ResolverStats.h"
67 #include "netid_client.h"  // NETID_UNSET
68 #include "params.h"        // MAXNS
69 #include "stats.h"         // RCODE_TIMEOUT
70 #include "tests/dns_metrics_listener/dns_metrics_listener.h"
71 #include "tests/dns_responder/dns_responder.h"
72 #include "tests/dns_responder/dns_responder_client_ndk.h"
73 #include "tests/dns_responder/dns_tls_certificate.h"
74 #include "tests/dns_responder/dns_tls_frontend.h"
75 #include "tests/resolv_test_utils.h"
76 #include "tests/tun_forwarder.h"
77 #include "tests/unsolicited_listener/unsolicited_event_listener.h"
78 
79 // This mainline module test still needs to be able to run on pre-S devices,
80 // and thus may run across pre-4.9 non-eBPF capable devices like the Pixel 2.
81 #define SKIP_IF_BPF_NOT_SUPPORTED                           \
82     do {                                                    \
83         if (!android::bpf::isAtLeastKernelVersion(4, 9, 0)) \
84             GTEST_SKIP() << "Skip: bpf is not supported.";  \
85     } while (0)
86 
87 // Valid VPN netId range is 100 ~ 65535
88 constexpr int TEST_VPN_NETID = 65502;
89 constexpr int MAXPACKET = (8 * 1024);
90 
91 // Sync from packages/modules/DnsResolver/resolv_private.h
92 constexpr int RES_TIMEOUT = 5000; /* min. milliseconds between retries */
93 constexpr int RES_DFLRETRY = 2;   /* Default #/tries. */
94 
95 // Semi-public Bionic hook used by the NDK (frameworks/base/native/android/net.c)
96 // Tested here for convenience.
97 extern "C" int android_getaddrinfofornet(const char* hostname, const char* servname,
98                                          const addrinfo* hints, unsigned netid, unsigned mark,
99                                          struct addrinfo** result);
100 
101 using namespace std::chrono_literals;
102 
103 using aidl::android::net::IDnsResolver;
104 using aidl::android::net::INetd;
105 using aidl::android::net::ResolverOptionsParcel;
106 using aidl::android::net::ResolverParamsParcel;
107 using aidl::android::net::UidRangeParcel;
108 using aidl::android::net::metrics::INetdEventListener;
109 using aidl::android::net::netd::aidl::NativeUidRangeConfig;
110 using aidl::android::net::resolv::aidl::DnsHealthEventParcel;
111 using aidl::android::net::resolv::aidl::IDnsResolverUnsolicitedEventListener;
112 using aidl::android::net::resolv::aidl::Nat64PrefixEventParcel;
113 using aidl::android::net::resolv::aidl::PrivateDnsValidationEventParcel;
114 using android::base::Error;
115 using android::base::GetProperty;
116 using android::base::ParseInt;
117 using android::base::Result;
118 using android::base::unique_fd;
119 using android::net::ResolverStats;
120 using android::net::TunForwarder;
121 using android::net::metrics::DnsMetricsListener;
122 using android::net::resolv::aidl::UnsolicitedEventListener;
123 using android::netdutils::enableSockopt;
124 using android::netdutils::makeSlice;
125 using android::netdutils::ResponseCode;
126 using android::netdutils::ScopedAddrinfo;
127 using android::netdutils::Stopwatch;
128 using android::netdutils::toHex;
129 
130 namespace fs = std::filesystem;
131 
132 namespace {
133 
safe_getaddrinfo_time_taken(const char * node,const char * service,const addrinfo & hints)134 std::pair<ScopedAddrinfo, int> safe_getaddrinfo_time_taken(const char* node, const char* service,
135                                                            const addrinfo& hints) {
136     Stopwatch s;
137     ScopedAddrinfo result = safe_getaddrinfo(node, service, &hints);
138     return {std::move(result), s.timeTakenUs() / 1000};
139 }
140 
141 struct NameserverStats {
142     NameserverStats() = delete;
NameserverStats__anon6dfd3fcb0111::NameserverStats143     NameserverStats(const std::string server) : server(server) {}
setSuccesses__anon6dfd3fcb0111::NameserverStats144     NameserverStats& setSuccesses(int val) {
145         successes = val;
146         return *this;
147     }
setErrors__anon6dfd3fcb0111::NameserverStats148     NameserverStats& setErrors(int val) {
149         errors = val;
150         return *this;
151     }
setTimeouts__anon6dfd3fcb0111::NameserverStats152     NameserverStats& setTimeouts(int val) {
153         timeouts = val;
154         return *this;
155     }
setInternalErrors__anon6dfd3fcb0111::NameserverStats156     NameserverStats& setInternalErrors(int val) {
157         internal_errors = val;
158         return *this;
159     }
setRttAvg__anon6dfd3fcb0111::NameserverStats160     NameserverStats& setRttAvg(int val) {
161         rtt_avg = val;
162         return *this;
163     }
164 
165     const std::string server;
166     int successes = 0;
167     int errors = 0;
168     int timeouts = 0;
169     int internal_errors = 0;
170     int rtt_avg = -1;
171 };
172 
173 const bool isAtLeastR = (getApiLevel() >= 30);
174 
175 #define SKIP_IF_KERNEL_VERSION_LOWER_THAN(major, minor, sub)                                  \
176     do {                                                                                      \
177         if (!android::bpf::isAtLeastKernelVersion(major, minor, sub))                         \
178             GTEST_SKIP() << "Required kernel: " << (major) << "." << (minor) << "." << (sub); \
179     } while (0)
180 
181 }  // namespace
182 
183 class ResolverTest : public NetNativeTestBase {
184   public:
SetUpTestSuite()185     static void SetUpTestSuite() {
186         // Get binder service.
187         // Note that |mDnsClient| is not used for getting binder service in this static function.
188         // The reason is that wants to keep |mDnsClient| as a non-static data member. |mDnsClient|
189         // which sets up device network configuration could be independent from every test.
190         // TODO: Perhaps add a static function in resolv_test_binder_utils.{cpp,h} to get binder
191         // service.
192 
193         AIBinder* binder = AServiceManager_getService("dnsresolver");
194         sResolvBinder = ndk::SpAIBinder(binder);
195         auto resolvService = aidl::android::net::IDnsResolver::fromBinder(sResolvBinder);
196         ASSERT_NE(nullptr, resolvService.get());
197 
198         // Subscribe the death recipient to the service IDnsResolver for detecting Netd death.
199         // GTEST assertion macros are not invoked for generating a test failure in the death
200         // recipient because the macros can't indicate failed test if Netd died between tests.
201         // Moreover, continuing testing may have no meaningful after Netd death. Therefore, the
202         // death recipient aborts process by GTEST_LOG_(FATAL) once Netd died.
203         sResolvDeathRecipient = AIBinder_DeathRecipient_new([](void*) {
204             constexpr char errorMessage[] = "Netd died";
205             LOG(ERROR) << errorMessage;
206             GTEST_LOG_(FATAL) << errorMessage;
207         });
208         ASSERT_EQ(STATUS_OK, AIBinder_linkToDeath(binder, sResolvDeathRecipient, nullptr));
209 
210         // Subscribe the DNS listener for verifying DNS metrics event contents.
211         sDnsMetricsListener = ndk::SharedRefBase::make<DnsMetricsListener>(
212                 TEST_NETID /*monitor specific network*/);
213         ASSERT_TRUE(resolvService->registerEventListener(sDnsMetricsListener).isOk());
214 
215         // Subscribe the unsolicited event listener for verifying unsolicited event contents.
216         sUnsolicitedEventListener = ndk::SharedRefBase::make<UnsolicitedEventListener>(
217                 TEST_NETID /*monitor specific network*/);
218         ASSERT_TRUE(
219                 resolvService->registerUnsolicitedEventListener(sUnsolicitedEventListener).isOk());
220 
221         // Start the binder thread pool for listening DNS metrics events and receiving death
222         // recipient.
223         ABinderProcess_startThreadPool();
224         AllowNetworkInBackground(TEST_UID, true);
225         AllowNetworkInBackground(TEST_UID2, true);
226     }
TearDownTestSuite()227     static void TearDownTestSuite() {
228         AIBinder_DeathRecipient_delete(sResolvDeathRecipient);
229         AllowNetworkInBackground(TEST_UID, false);
230         AllowNetworkInBackground(TEST_UID2, false);
231     }
232 
233   protected:
SetUp()234     void SetUp() {
235         mDnsClient.SetUp();
236         sDnsMetricsListener->reset();
237         sUnsolicitedEventListener->reset();
238         SetMdnsRoute();
239         mIsResolverOptionIPCSupported =
240                 DnsResponderClient::isRemoteVersionSupported(mDnsClient.resolvService(), 9);
241     }
242 
TearDown()243     void TearDown() {
244         // Ensure the dump works at the end of each test.
245         DumpResolverService();
246         RemoveMdnsRoute();
247         mDnsClient.TearDown();
248     }
249 
resetNetwork()250     void resetNetwork() {
251         EXPECT_EQ(mDnsClient.TearDownOemNetwork(TEST_NETID), 0);
252         EXPECT_EQ(mDnsClient.SetupOemNetwork(TEST_NETID), 0);
253     }
254 
StartDns(test::DNSResponder & dns,const std::vector<DnsRecord> & records)255     void StartDns(test::DNSResponder& dns, const std::vector<DnsRecord>& records) {
256         for (const auto& r : records) {
257             dns.addMapping(r.host_name, r.type, r.addr);
258         }
259 
260         ASSERT_TRUE(dns.startServer());
261         dns.clearQueries();
262     }
263 
DumpResolverService()264     void DumpResolverService() {
265         unique_fd fd(open("/dev/null", O_WRONLY));
266         EXPECT_EQ(mDnsClient.resolvService()->dump(fd, nullptr, 0), 0);
267 
268         const char* querylogCmd[] = {"querylog"};  // Keep it sync with DnsQueryLog::DUMP_KEYWORD.
269         EXPECT_EQ(mDnsClient.resolvService()->dump(fd, querylogCmd, std::size(querylogCmd)), 0);
270     }
271 
WaitForNat64Prefix(ExpectNat64PrefixStatus status,std::chrono::milliseconds timeout=std::chrono::milliseconds (1000))272     bool WaitForNat64Prefix(ExpectNat64PrefixStatus status,
273                             std::chrono::milliseconds timeout = std::chrono::milliseconds(1000)) {
274         return sDnsMetricsListener->waitForNat64Prefix(status, timeout) &&
275                sUnsolicitedEventListener->waitForNat64Prefix(
276                        status == EXPECT_FOUND
277                                ? IDnsResolverUnsolicitedEventListener::PREFIX_OPERATION_ADDED
278                                : IDnsResolverUnsolicitedEventListener::PREFIX_OPERATION_REMOVED,
279                        timeout);
280     }
281 
WaitForPrivateDnsValidation(std::string serverAddr,bool validated)282     bool WaitForPrivateDnsValidation(std::string serverAddr, bool validated) {
283         return sDnsMetricsListener->waitForPrivateDnsValidation(serverAddr, validated) &&
284                sUnsolicitedEventListener->waitForPrivateDnsValidation(
285                        serverAddr,
286                        validated ? IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_SUCCESS
287                                  : IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_FAILURE,
288                        IDnsResolverUnsolicitedEventListener::PROTOCOL_DOT);
289     }
290 
hasUncaughtPrivateDnsValidation(const std::string & serverAddr)291     bool hasUncaughtPrivateDnsValidation(const std::string& serverAddr) {
292         return sDnsMetricsListener->findValidationRecord(serverAddr) &&
293                sUnsolicitedEventListener->findValidationRecord(
294                        serverAddr, IDnsResolverUnsolicitedEventListener::PROTOCOL_DOT);
295     }
296 
ExpectDnsEvent(int32_t eventType,int32_t returnCode,const std::string & hostname,const std::vector<std::string> & ipAddresses)297     void ExpectDnsEvent(int32_t eventType, int32_t returnCode, const std::string& hostname,
298                         const std::vector<std::string>& ipAddresses) {
299         const DnsMetricsListener::DnsEvent expect = {
300                 TEST_NETID, eventType,   returnCode,
301                 hostname,   ipAddresses, static_cast<int32_t>(ipAddresses.size())};
302         do {
303             // Blocking call until timeout.
304             const auto dnsEvent = sDnsMetricsListener->popDnsEvent();
305             ASSERT_TRUE(dnsEvent.has_value()) << "Expected DnsEvent " << expect;
306             if (dnsEvent.value() == expect) break;
307             LOG(INFO) << "Skip unexpected DnsEvent: " << dnsEvent.value();
308         } while (true);
309 
310         while (returnCode == 0 || returnCode == RCODE_TIMEOUT) {
311             // Blocking call until timeout.
312             Result<int> result = sUnsolicitedEventListener->popDnsHealthResult();
313             ASSERT_TRUE(result.ok()) << "Expected dns health result is " << returnCode;
314             if ((returnCode == 0 &&
315                  result.value() == IDnsResolverUnsolicitedEventListener::DNS_HEALTH_RESULT_OK) ||
316                 (returnCode == RCODE_TIMEOUT &&
317                  result.value() ==
318                          IDnsResolverUnsolicitedEventListener::DNS_HEALTH_RESULT_TIMEOUT)) {
319                 break;
320             }
321             LOG(INFO) << "Skip unexpected dns health result:" << result.value();
322         }
323     }
324 
325     enum class StatsCmp { LE, EQ };
326 
expectStatsNotGreaterThan(const std::vector<NameserverStats> & nameserversStats)327     bool expectStatsNotGreaterThan(const std::vector<NameserverStats>& nameserversStats) {
328         return expectStatsFromGetResolverInfo(nameserversStats, StatsCmp::LE);
329     }
330 
expectStatsEqualTo(const std::vector<NameserverStats> & nameserversStats)331     bool expectStatsEqualTo(const std::vector<NameserverStats>& nameserversStats) {
332         return expectStatsFromGetResolverInfo(nameserversStats, StatsCmp::EQ);
333     }
334 
expectStatsFromGetResolverInfo(const std::vector<NameserverStats> & nameserversStats,const StatsCmp cmp)335     bool expectStatsFromGetResolverInfo(const std::vector<NameserverStats>& nameserversStats,
336                                         const StatsCmp cmp) {
337         constexpr int RTT_TOLERANCE_MS = 200;
338         const auto resolvInfo = mDnsClient.getResolverInfo();
339         if (!resolvInfo.ok()) {
340             ADD_FAILURE() << resolvInfo.error().message();
341             return false;
342         }
343         const std::vector<std::string>& res_servers = resolvInfo.value().dnsServers;
344         const std::vector<ResolverStats>& res_stats = resolvInfo.value().stats;
345 
346         if (res_servers.size() != res_stats.size()) {
347             ADD_FAILURE() << fmt::format("res_servers.size() != res_stats.size(): {} != {}",
348                                          res_servers.size(), res_stats.size());
349             return false;
350         }
351         if (res_servers.size() != nameserversStats.size()) {
352             ADD_FAILURE() << fmt::format("res_servers.size() != nameserversStats.size(): {} != {}",
353                                          res_servers.size(), nameserversStats.size());
354             return false;
355         }
356 
357         for (const auto& stats : nameserversStats) {
358             SCOPED_TRACE(stats.server);
359             const auto it = std::find(res_servers.begin(), res_servers.end(), stats.server);
360             if (it == res_servers.end()) {
361                 ADD_FAILURE() << fmt::format("nameserver {} not found in the list {{{}}}",
362                                              stats.server, fmt::join(res_servers, ", "));
363                 return false;
364             }
365             const int index = std::distance(res_servers.begin(), it);
366 
367             // The check excludes last_sample_time and usable since they will be obsolete
368             // after |res_stats| is retrieved from NetConfig.dnsStats rather than NetConfig.nsstats.
369             switch (cmp) {
370                 case StatsCmp::EQ:
371                     EXPECT_EQ(res_stats[index].successes, stats.successes);
372                     EXPECT_EQ(res_stats[index].errors, stats.errors);
373                     EXPECT_EQ(res_stats[index].timeouts, stats.timeouts);
374                     EXPECT_EQ(res_stats[index].internal_errors, stats.internal_errors);
375                     // A negative rtt_avg means that there is no effective rtt in the
376                     // stats. The value should be deterministic.
377                     // See android_net_res_stats_aggregate() for mor details.
378                     if (res_stats[index].rtt_avg < 0 || stats.rtt_avg < 0) {
379                         EXPECT_EQ(res_stats[index].rtt_avg, stats.rtt_avg);
380                     } else {
381                         EXPECT_NEAR(res_stats[index].rtt_avg, stats.rtt_avg, RTT_TOLERANCE_MS);
382                     }
383                     break;
384                 case StatsCmp::LE:
385                     EXPECT_LE(res_stats[index].successes, stats.successes);
386                     EXPECT_LE(res_stats[index].errors, stats.errors);
387                     EXPECT_LE(res_stats[index].timeouts, stats.timeouts);
388                     EXPECT_LE(res_stats[index].internal_errors, stats.internal_errors);
389                     EXPECT_LE(res_stats[index].rtt_avg, stats.rtt_avg + RTT_TOLERANCE_MS);
390                     break;
391                 default:
392                     ADD_FAILURE() << "Unknown comparator " << static_cast<int>(cmp);
393                     return false;
394             }
395         }
396 
397         return true;
398     }
399 
400     // Since there's no way to terminate private DNS validation threads at any time. Tests that
401     // focus on the results of private DNS validation can interfere with each other if they use the
402     // same IP address for test servers. getUniqueIPv4Address() is a workaround to reduce the
403     // possibility of tests being flaky. A feasible solution is to forbid the validation threads,
404     // which are considered as outdated (e.g. switch the resolver to private DNS OFF mode), updating
405     // the result to the PrivateDnsConfiguration instance.
getUniqueIPv4Address()406     static std::string getUniqueIPv4Address() {
407         static int counter = 0;
408         return fmt::format("127.0.100.{}", (++counter & 0xff));
409     }
410 
411     DnsResponderClient mDnsClient;
412 
413     bool mIsResolverOptionIPCSupported = false;
414 
415     // Use a shared static DNS listener for all tests to avoid registering lots of listeners
416     // which may be released late until process terminated. Currently, registered DNS listener
417     // is removed by binder death notification which is fired when the process hosting an
418     // IBinder has gone away. If every test in ResolverTest registers its DNS listener, Netd
419     // may temporarily hold lots of dead listeners until the unit test process terminates.
420     // TODO: Perhaps add an unregistering listener binder call or fork a listener process which
421     // could be terminated earlier.
422     static std::shared_ptr<DnsMetricsListener>
423             sDnsMetricsListener;  // Initialized in SetUpTestSuite.
424 
425     inline static std::shared_ptr<UnsolicitedEventListener>
426             sUnsolicitedEventListener;  // Initialized in SetUpTestSuite.
427 
428     // Use a shared static death recipient to monitor the service death. The static death
429     // recipient could monitor the death not only during the test but also between tests.
430     static AIBinder_DeathRecipient* sResolvDeathRecipient;  // Initialized in SetUpTestSuite.
431 
432     // The linked AIBinder_DeathRecipient will be automatically unlinked if the binder is deleted.
433     // The binder needs to be retained throughout tests.
434     static ndk::SpAIBinder sResolvBinder;
435 };
436 
437 // Initialize static member of class.
438 std::shared_ptr<DnsMetricsListener> ResolverTest::sDnsMetricsListener;
439 AIBinder_DeathRecipient* ResolverTest::sResolvDeathRecipient;
440 ndk::SpAIBinder ResolverTest::sResolvBinder;
441 
TEST_F(ResolverTest,GetHostByName)442 TEST_F(ResolverTest, GetHostByName) {
443     constexpr char nonexistent_host_name[] = "nonexistent.example.com.";
444 
445     test::DNSResponder dns;
446     StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.3"}});
447     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
448 
449     const hostent* result;
450     result = gethostbyname("nonexistent");
451     EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, nonexistent_host_name));
452     ASSERT_TRUE(result == nullptr);
453     EXPECT_EQ(HOST_NOT_FOUND, h_errno);
454 
455     dns.clearQueries();
456     result = gethostbyname("hello");
457     EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, kHelloExampleCom));
458     ASSERT_FALSE(result == nullptr);
459     ASSERT_EQ(4, result->h_length);
460     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
461     EXPECT_EQ("1.2.3.3", ToString(result));
462     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
463 }
464 
TEST_F(ResolverTest,GetHostByName_NULL)465 TEST_F(ResolverTest, GetHostByName_NULL) {
466     // Most libc implementations would just crash on gethostbyname(NULL). Instead, Bionic
467     // serializes the null argument over dnsproxyd, causing the server-side to crash!
468     // This is a regression test.
469     const char* const testcases[] = {nullptr, "", "^"};
470     for (const char* name : testcases) {
471         SCOPED_TRACE(fmt::format("gethostbyname({})", name ? name : "NULL"));
472         const hostent* result = gethostbyname(name);
473         EXPECT_TRUE(result == nullptr);
474         EXPECT_EQ(HOST_NOT_FOUND, h_errno);
475     }
476 }
477 
TEST_F(ResolverTest,GetHostByName_cnames)478 TEST_F(ResolverTest, GetHostByName_cnames) {
479     constexpr char host_name[] = "host.example.com.";
480     size_t cnamecount = 0;
481     test::DNSResponder dns;
482 
483     const std::vector<DnsRecord> records = {
484             {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
485             {"a.example.com.", ns_type::ns_t_cname, "b.example.com."},
486             {"b.example.com.", ns_type::ns_t_cname, "c.example.com."},
487             {"c.example.com.", ns_type::ns_t_cname, "d.example.com."},
488             {"d.example.com.", ns_type::ns_t_cname, "e.example.com."},
489             {"e.example.com.", ns_type::ns_t_cname, host_name},
490             {host_name, ns_type::ns_t_a, "1.2.3.3"},
491             {host_name, ns_type::ns_t_aaaa, "2001:db8::42"},
492     };
493     StartDns(dns, records);
494     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
495 
496     // using gethostbyname2() to resolve ipv4 hello.example.com. to 1.2.3.3
497     // Ensure the v4 address and cnames are correct
498     const hostent* result;
499     result = gethostbyname2("hello", AF_INET);
500     ASSERT_FALSE(result == nullptr);
501 
502     for (int i = 0; result != nullptr && result->h_aliases[i] != nullptr; i++) {
503         std::string domain_name = records[i].host_name.substr(0, records[i].host_name.size() - 1);
504         EXPECT_EQ(result->h_aliases[i], domain_name);
505         cnamecount++;
506     }
507     // The size of "Non-cname type" record in DNS records is 2
508     ASSERT_EQ(cnamecount, records.size() - 2);
509     ASSERT_EQ(4, result->h_length);
510     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
511     EXPECT_EQ("1.2.3.3", ToString(result));
512     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
513     EXPECT_EQ(1U, dns.queries().size()) << dns.dumpQueries();
514 
515     // using gethostbyname2() to resolve ipv6 hello.example.com. to 2001:db8::42
516     // Ensure the v6 address and cnames are correct
517     cnamecount = 0;
518     dns.clearQueries();
519     result = gethostbyname2("hello", AF_INET6);
520     for (unsigned i = 0; result != nullptr && result->h_aliases[i] != nullptr; i++) {
521         std::string domain_name = records[i].host_name.substr(0, records[i].host_name.size() - 1);
522         EXPECT_EQ(result->h_aliases[i], domain_name);
523         cnamecount++;
524     }
525     // The size of "Non-cname type" DNS record in records is 2
526     ASSERT_EQ(cnamecount, records.size() - 2);
527     ASSERT_FALSE(result == nullptr);
528     ASSERT_EQ(16, result->h_length);
529     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
530     EXPECT_EQ("2001:db8::42", ToString(result));
531     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
532 }
533 
TEST_F(ResolverTest,GetHostByName_cnamesInfiniteLoop)534 TEST_F(ResolverTest, GetHostByName_cnamesInfiniteLoop) {
535     test::DNSResponder dns;
536     const std::vector<DnsRecord> records = {
537             {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
538             {"a.example.com.", ns_type::ns_t_cname, kHelloExampleCom},
539     };
540     StartDns(dns, records);
541     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
542 
543     const hostent* result;
544     result = gethostbyname2("hello", AF_INET);
545     ASSERT_TRUE(result == nullptr);
546 
547     dns.clearQueries();
548     result = gethostbyname2("hello", AF_INET6);
549     ASSERT_TRUE(result == nullptr);
550 }
551 
TEST_F(ResolverTest,GetHostByName_localhost)552 TEST_F(ResolverTest, GetHostByName_localhost) {
553     constexpr char name_camelcase[] = "LocalHost";
554     constexpr char name_ip6_dot[] = "ip6-localhost.";
555     constexpr char name_ip6_fqdn[] = "ip6-localhost.example.com.";
556 
557     // Add a no-op nameserver which shouldn't receive any queries
558     test::DNSResponder dns;
559     StartDns(dns, {});
560     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
561 
562     // Expect no DNS queries; localhost is resolved via /etc/hosts
563     const hostent* result = gethostbyname(kLocalHost);
564     EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
565     ASSERT_FALSE(result == nullptr);
566     ASSERT_EQ(4, result->h_length);
567     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
568     EXPECT_EQ(kLocalHostAddr, ToString(result));
569     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
570 
571     // Ensure the hosts file resolver ignores case of hostnames
572     result = gethostbyname(name_camelcase);
573     EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
574     ASSERT_FALSE(result == nullptr);
575     ASSERT_EQ(4, result->h_length);
576     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
577     EXPECT_EQ(kLocalHostAddr, ToString(result));
578     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
579 
580     // The hosts file also contains ip6-localhost, but gethostbyname() won't
581     // return it. This would be easy to
582     // change, but there's no point in changing the legacy behavior; new code
583     // should be calling getaddrinfo() anyway.
584     // So we check the legacy behavior, which results in amusing A-record
585     // lookups for ip6-localhost, with and without search domains appended.
586     dns.clearQueries();
587     result = gethostbyname(kIp6LocalHost);
588     EXPECT_EQ(2U, dns.queries().size()) << dns.dumpQueries();
589     EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, name_ip6_dot)) << dns.dumpQueries();
590     EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, name_ip6_fqdn)) << dns.dumpQueries();
591     ASSERT_TRUE(result == nullptr);
592 
593     // Finally, use gethostbyname2() to resolve ip6-localhost to ::1 from
594     // the hosts file.
595     dns.clearQueries();
596     result = gethostbyname2(kIp6LocalHost, AF_INET6);
597     EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
598     ASSERT_FALSE(result == nullptr);
599     ASSERT_EQ(16, result->h_length);
600     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
601     EXPECT_EQ(kIp6LocalHostAddr, ToString(result));
602     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
603 }
604 
TEST_F(ResolverTest,GetHostByName_numeric)605 TEST_F(ResolverTest, GetHostByName_numeric) {
606     // Add a no-op nameserver which shouldn't receive any queries
607     test::DNSResponder dns;
608     StartDns(dns, {});
609     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
610 
611     // Numeric v4 address: expect no DNS queries
612     constexpr char numeric_v4[] = "192.168.0.1";
613     const hostent* result = gethostbyname(numeric_v4);
614     EXPECT_EQ(0U, dns.queries().size());
615     ASSERT_FALSE(result == nullptr);
616     ASSERT_EQ(4, result->h_length);  // v4
617     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
618     EXPECT_EQ(numeric_v4, ToString(result));
619     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
620 
621     // gethostbyname() recognizes a v6 address, and fails with no DNS queries
622     constexpr char numeric_v6[] = "2001:db8::42";
623     dns.clearQueries();
624     result = gethostbyname(numeric_v6);
625     EXPECT_EQ(0U, dns.queries().size());
626     EXPECT_TRUE(result == nullptr);
627 
628     // Numeric v6 address with gethostbyname2(): succeeds with no DNS queries
629     dns.clearQueries();
630     result = gethostbyname2(numeric_v6, AF_INET6);
631     EXPECT_EQ(0U, dns.queries().size());
632     ASSERT_FALSE(result == nullptr);
633     ASSERT_EQ(16, result->h_length);  // v6
634     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
635     EXPECT_EQ(numeric_v6, ToString(result));
636     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
637 
638     // Numeric v6 address with scope work with getaddrinfo(),
639     // but gethostbyname2() does not understand them; it issues two dns
640     // queries, then fails. This hardly ever happens, there's no point
641     // in fixing this. This test simply verifies the current (bogus)
642     // behavior to avoid further regressions (like crashes, or leaks).
643     constexpr char numeric_v6_scope[] = "fe80::1%lo";
644     dns.clearQueries();
645     result = gethostbyname2(numeric_v6_scope, AF_INET6);
646     EXPECT_EQ(2U, dns.queries().size());  // OUCH!
647     ASSERT_TRUE(result == nullptr);
648 }
649 
TEST_F(ResolverTest,BinderSerialization)650 TEST_F(ResolverTest, BinderSerialization) {
651     std::array<int, IDnsResolver::RESOLVER_PARAMS_COUNT> params_offsets = {
652             IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY,
653             IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD,
654             IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES,
655             IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES,
656             IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC,
657             IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT,
658     };
659     const int size = static_cast<int>(params_offsets.size());
660     EXPECT_EQ(size, IDnsResolver::RESOLVER_PARAMS_COUNT);
661     std::sort(params_offsets.begin(), params_offsets.end());
662     for (int i = 0; i < size; ++i) {
663         EXPECT_EQ(params_offsets[i], i);
664     }
665 }
666 
TEST_F(ResolverTest,GetHostByName_Binder)667 TEST_F(ResolverTest, GetHostByName_Binder) {
668     std::vector<std::string> domains = {"example.com"};
669     std::vector<std::unique_ptr<test::DNSResponder>> dns;
670     std::vector<std::string> servers;
671     std::vector<DnsResponderClient::Mapping> mappings;
672     ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(1, domains, &mappings));
673     ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(4, mappings, &dns, &servers));
674     ASSERT_EQ(1U, mappings.size());
675     const DnsResponderClient::Mapping& mapping = mappings[0];
676 
677     const auto resolverParams = ResolverParams::Builder()
678                                         .setDomains(domains)
679                                         .setDnsServers(servers)
680                                         .setDotServers({})
681                                         .build();
682     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(resolverParams));
683 
684     const hostent* result = gethostbyname(mapping.host.c_str());
685     const size_t total_queries =
686             std::accumulate(dns.begin(), dns.end(), 0, [&mapping](size_t total, auto& d) {
687                 return total + GetNumQueriesForType(*d, ns_type::ns_t_a, mapping.entry.c_str());
688             });
689 
690     EXPECT_LE(1U, total_queries);
691     ASSERT_FALSE(result == nullptr);
692     ASSERT_EQ(4, result->h_length);
693     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
694     EXPECT_EQ(mapping.ip4, ToString(result));
695     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
696 
697     const auto resolvInfo = mDnsClient.getResolverInfo();
698     ASSERT_RESULT_OK(resolvInfo);
699     EXPECT_EQ(servers.size(), resolvInfo.value().dnsServers.size());
700     EXPECT_EQ(domains.size(), resolvInfo.value().domains.size());
701     EXPECT_TRUE(resolvInfo.value().dotServers.empty());
702     EXPECT_EQ(resolverParams.sampleValiditySeconds, resolvInfo.value().params.sample_validity);
703     EXPECT_EQ(resolverParams.successThreshold, resolvInfo.value().params.success_threshold);
704     EXPECT_EQ(resolverParams.minSamples, resolvInfo.value().params.min_samples);
705     EXPECT_EQ(resolverParams.maxSamples, resolvInfo.value().params.max_samples);
706     EXPECT_EQ(resolverParams.baseTimeoutMsec, resolvInfo.value().params.base_timeout_msec);
707     EXPECT_EQ(resolverParams.retryCount, resolvInfo.value().params.retry_count);
708     EXPECT_EQ(servers.size(), resolvInfo.value().stats.size());
709 
710     EXPECT_THAT(resolvInfo.value().dnsServers, testing::UnorderedElementsAreArray(servers));
711     EXPECT_THAT(resolvInfo.value().domains, testing::UnorderedElementsAreArray(domains));
712 }
713 
TEST_F(ResolverTest,GetAddrInfo)714 TEST_F(ResolverTest, GetAddrInfo) {
715     constexpr char listen_addr[] = "127.0.0.4";
716     constexpr char listen_addr2[] = "127.0.0.5";
717     constexpr char host_name[] = "howdy.example.com.";
718 
719     const std::vector<DnsRecord> records = {
720             {host_name, ns_type::ns_t_a, "1.2.3.4"},
721             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
722     };
723     test::DNSResponder dns(listen_addr);
724     test::DNSResponder dns2(listen_addr2);
725     StartDns(dns, records);
726     StartDns(dns2, records);
727 
728     ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr}));
729     dns.clearQueries();
730     dns2.clearQueries();
731 
732     ScopedAddrinfo result = safe_getaddrinfo("howdy", nullptr, nullptr);
733     EXPECT_TRUE(result != nullptr);
734     size_t found = GetNumQueries(dns, host_name);
735     EXPECT_LE(1U, found);
736     // Could be A or AAAA
737     std::string result_str = ToString(result);
738     EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
739             << ", result_str='" << result_str << "'";
740 
741     // Verify that the name is cached.
742     size_t old_found = found;
743     result = safe_getaddrinfo("howdy", nullptr, nullptr);
744     EXPECT_TRUE(result != nullptr);
745     found = GetNumQueries(dns, host_name);
746     EXPECT_LE(1U, found);
747     EXPECT_EQ(old_found, found);
748     result_str = ToString(result);
749     EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4") << result_str;
750 
751     // Change the DNS resolver, ensure that queries are still cached.
752     ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr2}));
753     dns.clearQueries();
754     dns2.clearQueries();
755 
756     result = safe_getaddrinfo("howdy", nullptr, nullptr);
757     EXPECT_TRUE(result != nullptr);
758     found = GetNumQueries(dns, host_name);
759     size_t found2 = GetNumQueries(dns2, host_name);
760     EXPECT_EQ(0U, found);
761     EXPECT_LE(0U, found2);
762 
763     // Could be A or AAAA
764     result_str = ToString(result);
765     EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
766             << ", result_str='" << result_str << "'";
767 }
768 
TEST_F(ResolverTest,GetAddrInfoV4)769 TEST_F(ResolverTest, GetAddrInfoV4) {
770     test::DNSResponder dns;
771     StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.5"}});
772     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
773 
774     const addrinfo hints = {.ai_family = AF_INET};
775     ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
776     EXPECT_TRUE(result != nullptr);
777     EXPECT_EQ(1U, GetNumQueries(dns, kHelloExampleCom));
778     EXPECT_EQ("1.2.3.5", ToString(result));
779 }
780 
TEST_F(ResolverTest,GetAddrInfo_localhost)781 TEST_F(ResolverTest, GetAddrInfo_localhost) {
782     // Add a no-op nameserver which shouldn't receive any queries
783     test::DNSResponder dns;
784     StartDns(dns, {});
785     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
786 
787     ScopedAddrinfo result = safe_getaddrinfo(kLocalHost, nullptr, nullptr);
788     EXPECT_TRUE(result != nullptr);
789     // Expect no DNS queries; localhost is resolved via /etc/hosts
790     EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
791     EXPECT_EQ(kLocalHostAddr, ToString(result));
792 
793     result = safe_getaddrinfo(kIp6LocalHost, nullptr, nullptr);
794     EXPECT_TRUE(result != nullptr);
795     // Expect no DNS queries; ip6-localhost is resolved via /etc/hosts
796     EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
797     EXPECT_EQ(kIp6LocalHostAddr, ToString(result));
798 }
799 
TEST_F(ResolverTest,GetAddrInfo_NumericHostname)800 TEST_F(ResolverTest, GetAddrInfo_NumericHostname) {
801     // Add a no-op nameserver which shouldn't receive any queries
802     test::DNSResponder dns;
803     StartDns(dns, {});
804     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
805 
806     ScopedAddrinfo result = safe_getaddrinfo("1.2.3.4", nullptr, nullptr);
807     EXPECT_TRUE(result != nullptr);
808     // Expect no DNS queries. Numeric hostname doesn't need to resolve.
809     EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
810     EXPECT_EQ("1.2.3.4", ToString(result));
811 
812     result = safe_getaddrinfo("2001:db8::1", nullptr, nullptr);
813     EXPECT_TRUE(result != nullptr);
814     // Expect no DNS queries. Numeric hostname doesn't need to resolve.
815     EXPECT_TRUE(dns.queries().empty()) << dns.dumpQueries();
816     EXPECT_EQ("2001:db8::1", ToString(result));
817 }
818 
TEST_F(ResolverTest,GetAddrInfo_InvalidSocketType)819 TEST_F(ResolverTest, GetAddrInfo_InvalidSocketType) {
820     test::DNSResponder dns;
821     StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, "1.2.3.5"}});
822     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
823 
824     // TODO: Test other invalid socket types.
825     const addrinfo hints = {
826             .ai_family = AF_UNSPEC,
827             .ai_socktype = SOCK_PACKET,
828     };
829     addrinfo* result = nullptr;
830     // This is a valid hint, but the query won't be sent because the socket type is
831     // not supported.
832     EXPECT_EQ(EAI_NODATA, getaddrinfo("hello", nullptr, &hints, &result));
833     ScopedAddrinfo result_cleanup(result);
834     EXPECT_EQ(nullptr, result);
835 }
836 
837 // Verify if the resolver correctly handle multiple queries simultaneously
838 // step 1: set dns server#1 into deferred responding mode.
839 // step 2: thread#1 query "hello.example.com." --> resolver send query to server#1.
840 // step 3: thread#2 query "hello.example.com." --> resolver hold the request and wait for
841 //           response of previous pending query sent by thread#1.
842 // step 4: thread#3 query "konbanha.example.com." --> resolver send query to server#3. Server
843 //           respond to resolver immediately.
844 // step 5: check if server#1 get 1 query by thread#1, server#2 get 0 query, server#3 get 1 query.
845 // step 6: resume dns server#1 to respond dns query in step#2.
846 // step 7: thread#1 and #2 should get returned from DNS query after step#6. Also, check the
847 //           number of queries in server#2 is 0 to ensure thread#2 does not wake up unexpectedly
848 //           before signaled by thread#1.
TEST_F(ResolverTest,GetAddrInfoV4_deferred_resp)849 TEST_F(ResolverTest, GetAddrInfoV4_deferred_resp) {
850     const char* listen_addr1 = "127.0.0.9";
851     const char* listen_addr2 = "127.0.0.10";
852     const char* listen_addr3 = "127.0.0.11";
853     const char* listen_srv = "53";
854     const char* host_name_deferred = "hello.example.com.";
855     const char* host_name_normal = "konbanha.example.com.";
856     test::DNSResponder dns1(listen_addr1, listen_srv, ns_rcode::ns_r_servfail);
857     test::DNSResponder dns2(listen_addr2, listen_srv, ns_rcode::ns_r_servfail);
858     test::DNSResponder dns3(listen_addr3, listen_srv, ns_rcode::ns_r_servfail);
859     dns1.addMapping(host_name_deferred, ns_type::ns_t_a, "1.2.3.4");
860     dns2.addMapping(host_name_deferred, ns_type::ns_t_a, "1.2.3.4");
861     dns3.addMapping(host_name_normal, ns_type::ns_t_a, "1.2.3.5");
862     ASSERT_TRUE(dns1.startServer());
863     ASSERT_TRUE(dns2.startServer());
864     ASSERT_TRUE(dns3.startServer());
865     const std::vector<std::string> servers_for_t1 = {listen_addr1};
866     const std::vector<std::string> servers_for_t2 = {listen_addr2};
867     const std::vector<std::string> servers_for_t3 = {listen_addr3};
868     addrinfo hints = {.ai_family = AF_INET};
869     const std::array<int, IDnsResolver::RESOLVER_PARAMS_COUNT> params = {300, 25, 8, 8, 5000, 0};
870     bool t3_task_done = false;
871     bool t2_sv_setup_done = false;
872 
873     dns1.setDeferredResp(true);
874     std::thread t1([&, this]() {
875         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(ResolverParams::Builder()
876                                                               .setDnsServers(servers_for_t1)
877                                                               .setDotServers({})
878                                                               .setParams(params)
879                                                               .build()));
880         ScopedAddrinfo result = safe_getaddrinfo(host_name_deferred, nullptr, &hints);
881         // t3's dns query should got returned first
882         EXPECT_TRUE(t3_task_done);
883         EXPECT_EQ(1U, GetNumQueries(dns1, host_name_deferred));
884         EXPECT_TRUE(result != nullptr);
885         EXPECT_EQ("1.2.3.4", ToString(result));
886     });
887 
888     // ensuring t1 and t2 handler functions are processed in order
889     EXPECT_TRUE(PollForCondition([&]() { return GetNumQueries(dns1, host_name_deferred); }));
890     std::thread t2([&, this]() {
891         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(ResolverParams::Builder()
892                                                               .setDnsServers(servers_for_t2)
893                                                               .setDotServers({})
894                                                               .setParams(params)
895                                                               .build()));
896         t2_sv_setup_done = true;
897         ScopedAddrinfo result = safe_getaddrinfo(host_name_deferred, nullptr, &hints);
898         EXPECT_TRUE(t3_task_done);
899         EXPECT_EQ(0U, GetNumQueries(dns2, host_name_deferred));
900         EXPECT_TRUE(result != nullptr);
901         EXPECT_EQ("1.2.3.4", ToString(result));
902         const auto resolvInfo = mDnsClient.getResolverInfo();
903         ASSERT_RESULT_OK(resolvInfo);
904         EXPECT_EQ(0, resolvInfo.value().waitForPendingReqTimeoutCount);
905     });
906 
907     // ensuring t2 and t3 handler functions are processed in order
908     EXPECT_TRUE(PollForCondition([&]() { return t2_sv_setup_done; }));
909     std::thread t3([&, this]() {
910         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(ResolverParams::Builder()
911                                                               .setDnsServers(servers_for_t3)
912                                                               .setDotServers({})
913                                                               .setParams(params)
914                                                               .build()));
915         ScopedAddrinfo result = safe_getaddrinfo(host_name_normal, nullptr, &hints);
916         EXPECT_EQ(1U, GetNumQueries(dns1, host_name_deferred));
917         EXPECT_EQ(0U, GetNumQueries(dns2, host_name_deferred));
918         EXPECT_EQ(1U, GetNumQueries(dns3, host_name_normal));
919         EXPECT_TRUE(result != nullptr);
920         EXPECT_EQ("1.2.3.5", ToString(result));
921 
922         t3_task_done = true;
923         dns1.setDeferredResp(false);
924     });
925     t3.join();
926     t1.join();
927     t2.join();
928 }
929 
TEST_F(ResolverTest,GetAddrInfoV4_MultiAnswers)930 TEST_F(ResolverTest, GetAddrInfoV4_MultiAnswers) {
931     test::DNSResponder dns(test::DNSResponder::MappingType::BINARY_PACKET);
932     dns.addMappingBinaryPacket(kHelloExampleComQueryV4, kHelloExampleComResponsesV4);
933     StartDns(dns, {});
934     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
935 
936     addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM};
937     ScopedAddrinfo result = safe_getaddrinfo(kHelloExampleCom, nullptr, &hints);
938     ASSERT_FALSE(result == nullptr);
939 
940     // Expect the DNS result order is the same as the RR order in the DNS response
941     // |kHelloExampleComResponsesV4| because none of rule in the native sorting
942     // function _rfc6724_compare() is matched.
943     //
944     // The reason is here for the sorting result from _rfc6724_compare.
945     // For rule 1: avoid unusable destinations, all addresses are unusable on a fake test network.
946     // For rule 2: prefer matching scope, all addresses don't match because of no source address.
947     //             See rule#1 as well.
948     // (rule 3 is not implemented)
949     // (rule 4 is not implemented)
950     // For rule 5: prefer matching label, all addresses get the same label 4 for AF_INET.
951     // For rule 6: prefer higher precedence, all addresses get the same precedence 35 for AF_INET.
952     // (rule 7 is not implemented)
953     // For rule 8: prefer smaller scope, all destination addresses has the same scope.
954     // For rule 9: use longest matching prefix, IPv6 only.
955     // For rule 10: leave the order unchanged, these IPv4 DNS addresses meet this rule.
956     //
957     // See packages/modules/DnsResolver/getaddrinfo.cpp
958     EXPECT_THAT(ToStrings(result),
959                 testing::ElementsAre(kHelloExampleComAddrV4, kHelloExampleComAddrV4_2,
960                                      kHelloExampleComAddrV4_3));
961 
962     // .ai_socktype will be 0.
963     hints = {.ai_family = AF_UNSPEC};
964     result = safe_getaddrinfo(kHelloExampleCom, nullptr, &hints);
965     ASSERT_FALSE(result == nullptr);
966 
967     // The results are sorted in every querying by explore_options and then concatenates all sorted
968     // results. resolv_getaddrinfo() calls explore_fqdn() many times by the different
969     // explore_options. It means that resolv_rfc6724_sort() only sorts the ordering in the results
970     // of each explore_options and concatenates all sorted results into one link list. The address
971     // order of the output addrinfo is:
972     //   1.2.3.4 (socktype=2, protocol=17) ->
973     //   8.8.8.8 (socktype=2, protocol=17) ->
974     //   81.117.21.202 (socktype=2, protocol=17) ->
975     //   1.2.3.4 (socktype=1, protocol=6) ->
976     //   8.8.8.8 (socktype=1, protocol=6) ->
977     //   81.117.21.202 (socktype=1, protocol=6)
978     //
979     // See resolv_getaddrinfo, explore_fqdn and dns_getaddrinfo.
980     EXPECT_THAT(ToStrings(result),
981                 testing::ElementsAre(kHelloExampleComAddrV4, kHelloExampleComAddrV4_2,
982                                      kHelloExampleComAddrV4_3, kHelloExampleComAddrV4,
983                                      kHelloExampleComAddrV4_2, kHelloExampleComAddrV4_3));
984 }
985 
TEST_F(ResolverTest,GetAddrInfoV6_MultiAnswers)986 TEST_F(ResolverTest, GetAddrInfoV6_MultiAnswers) {
987     test::DNSResponder dns(test::DNSResponder::MappingType::BINARY_PACKET);
988     dns.addMappingBinaryPacket(kHelloExampleComQueryV6, kHelloExampleComResponsesV6);
989     StartDns(dns, {});
990     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
991 
992     addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM};
993     ScopedAddrinfo result = safe_getaddrinfo(kHelloExampleCom, nullptr, &hints);
994     ASSERT_FALSE(result == nullptr);
995 
996     // Expect the DNS result order is GUA, teredo tunneling address and IPv4-compatible address
997     // because of the precedence comparison of RFC 6724.
998     //
999     // The reason is here for the sorting result from _rfc6724_compare.
1000     // For rule 1: avoid unusable destinations, all addresses are unusable on a fake test network.
1001     // For rule 2: prefer matching scope, all addresses don't match because of no source address.
1002     //             See rule#1 as well.
1003     // (rule 3 is not implemented)
1004     // (rule 4 is not implemented)
1005     // For rule 5: prefer matching label, the source address is not valid and can't match the dns
1006     //             reply addresses. See rule#1 as well.
1007     // For rule 6: prefer higher precedence, sorted by the order: gua(40), teredo(5) and
1008     //             ipv4-compatible(1).
1009     // Ignore from rule 7 to rule 10 because the results has been sorted by rule 6.
1010     //
1011     // See _get_precedence, _rfc6724_compare in packages/modules/DnsResolver/getaddrinfo.cpp
1012     EXPECT_THAT(ToStrings(result),
1013                 testing::ElementsAre(kHelloExampleComAddrV6_GUA, kHelloExampleComAddrV6_TEREDO,
1014                                      kHelloExampleComAddrV6_IPV4COMPAT));
1015 
1016     hints = {.ai_family = AF_UNSPEC};
1017     result = safe_getaddrinfo(kHelloExampleCom, nullptr, &hints);
1018     ASSERT_FALSE(result == nullptr);
1019 
1020     // The results are sorted in every querying by explore_options and then concatenates all sorted
1021     // results. resolv_getaddrinfo() calls explore_fqdn() many times by the different
1022     // explore_options. It means that resolv_rfc6724_sort() only sorts the ordering in the results
1023     // of each explore_options and concatenates all sorted results into one link list. The address
1024     // order of the output addrinfo is:
1025     //   2404:6800::5175:15ca (socktype=2, protocol=17) ->
1026     //   2001::47c1 (socktype=2, protocol=17) ->
1027     //   ::1.2.3.4 (socktype=2, protocol=17) ->
1028     //   2404:6800::5175:15ca (socktype=1, protocol=6) ->
1029     //   2001::47c1 (socktype=1, protocol=6) ->
1030     //   ::1.2.3.4 (socktype=1, protocol=6)
1031     //
1032     // See resolv_getaddrinfo, explore_fqdn and dns_getaddrinfo.
1033     EXPECT_THAT(
1034             ToStrings(result),
1035             testing::ElementsAre(kHelloExampleComAddrV6_GUA, kHelloExampleComAddrV6_TEREDO,
1036                                  kHelloExampleComAddrV6_IPV4COMPAT, kHelloExampleComAddrV6_GUA,
1037                                  kHelloExampleComAddrV6_TEREDO, kHelloExampleComAddrV6_IPV4COMPAT));
1038 }
1039 
TEST_F(ResolverTest,GetAddrInfoV4V6_MultiAnswers)1040 TEST_F(ResolverTest, GetAddrInfoV4V6_MultiAnswers) {
1041     test::DNSResponder dns(test::DNSResponder::MappingType::BINARY_PACKET);
1042     // Use one IPv4 address only because we can't control IPv4 address ordering in this test
1043     // which uses a fake network.
1044     dns.addMappingBinaryPacket(kHelloExampleComQueryV4, kHelloExampleComResponseV4);
1045     dns.addMappingBinaryPacket(kHelloExampleComQueryV6, kHelloExampleComResponsesV6);
1046     StartDns(dns, {});
1047     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1048 
1049     addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM};
1050     ScopedAddrinfo result = safe_getaddrinfo(kHelloExampleCom, nullptr, &hints);
1051     ASSERT_FALSE(result == nullptr);
1052 
1053     // Expect the DNS result order is ipv6 global unicast address, IPv4 address, IPv6 teredo
1054     // tunneling address and IPv4-compatible IPv6 address because of the precedence comparison
1055     // of RFC 6724.
1056     //
1057     // The reason is here for the sorting result from _rfc6724_compare.
1058     // For rule 1: avoid unusable destinations, all addresses are unusable on a fake test network.
1059     // For rule 2: prefer matching scope, all addresses don't match because of no source address.
1060     //             See rule#1 as well.
1061     // (rule 3 is not implemented)
1062     // (rule 4 is not implemented)
1063     // For rule 5: prefer matching label, the source address is not valid and can't match the dns
1064     //             reply addresses. See rule#1 as well.
1065     // For rule 6: prefer higher precedence, sorted by the order: gua(40), ipv4(35), teredo(5) and
1066     //             ipv4-compatible(1).
1067     // Ignore from rule 7 to rule 10 because the results has been sorted by rule 6.
1068     //
1069     // See _get_precedence, _rfc6724_compare in packages/modules/DnsResolver/getaddrinfo.cpp
1070     EXPECT_THAT(
1071             ToStrings(result),
1072             testing::ElementsAre(kHelloExampleComAddrV6_GUA, kHelloExampleComAddrV4,
1073                                  kHelloExampleComAddrV6_TEREDO, kHelloExampleComAddrV6_IPV4COMPAT));
1074 
1075     hints = {.ai_family = AF_UNSPEC};
1076     result = safe_getaddrinfo(kHelloExampleCom, nullptr, &hints);
1077     ASSERT_FALSE(result == nullptr);
1078 
1079     // The results are sorted in every querying by explore_options and then concatenates all sorted
1080     // results. resolv_getaddrinfo() calls explore_fqdn() many times by the different
1081     // explore_options. It means that resolv_rfc6724_sort() only sorts the ordering in the results
1082     // of each explore_options and concatenates all sorted results into one link list. The address
1083     // order of the output addrinfo is:
1084     //   2404:6800::5175:15ca (socktype=2, protocol=17) ->
1085     //   1.2.3.4 (socktype=2, protocol=17) ->
1086     //   2001::47c1 (socktype=2, protocol=17) ->
1087     //   ::1.2.3.4 (socktype=2, protocol=17) ->
1088     //   2404:6800::5175:15ca (socktype=1, protocol=6) ->
1089     //   1.2.3.4 (socktype=1, protocol=6) ->
1090     //   2001::47c1 (socktype=1, protocol=6) ->
1091     //   ::1.2.3.4 (socktype=1, protocol=6)
1092     //
1093     // See resolv_getaddrinfo, explore_fqdn and dns_getaddrinfo.
1094     EXPECT_THAT(
1095             ToStrings(result),
1096             testing::ElementsAre(kHelloExampleComAddrV6_GUA, kHelloExampleComAddrV4,
1097                                  kHelloExampleComAddrV6_TEREDO, kHelloExampleComAddrV6_IPV4COMPAT,
1098                                  kHelloExampleComAddrV6_GUA, kHelloExampleComAddrV4,
1099                                  kHelloExampleComAddrV6_TEREDO, kHelloExampleComAddrV6_IPV4COMPAT));
1100 }
1101 
TEST_F(ResolverTest,GetAddrInfo_cnames)1102 TEST_F(ResolverTest, GetAddrInfo_cnames) {
1103     constexpr char host_name[] = "host.example.com.";
1104     test::DNSResponder dns;
1105     const std::vector<DnsRecord> records = {
1106             {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
1107             {"a.example.com.", ns_type::ns_t_cname, "b.example.com."},
1108             {"b.example.com.", ns_type::ns_t_cname, "c.example.com."},
1109             {"c.example.com.", ns_type::ns_t_cname, "d.example.com."},
1110             {"d.example.com.", ns_type::ns_t_cname, "e.example.com."},
1111             {"e.example.com.", ns_type::ns_t_cname, host_name},
1112             {host_name, ns_type::ns_t_a, "1.2.3.3"},
1113             {host_name, ns_type::ns_t_aaaa, "2001:db8::42"},
1114     };
1115     StartDns(dns, records);
1116     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1117 
1118     addrinfo hints = {.ai_family = AF_INET};
1119     ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
1120     EXPECT_TRUE(result != nullptr);
1121     EXPECT_EQ("1.2.3.3", ToString(result));
1122 
1123     dns.clearQueries();
1124     hints = {.ai_family = AF_INET6};
1125     result = safe_getaddrinfo("hello", nullptr, &hints);
1126     EXPECT_TRUE(result != nullptr);
1127     EXPECT_EQ("2001:db8::42", ToString(result));
1128 }
1129 
TEST_F(ResolverTest,GetAddrInfo_cnamesNoIpAddress)1130 TEST_F(ResolverTest, GetAddrInfo_cnamesNoIpAddress) {
1131     test::DNSResponder dns;
1132     const std::vector<DnsRecord> records = {
1133             {kHelloExampleCom, ns_type::ns_t_cname, "a.example.com."},
1134     };
1135     StartDns(dns, records);
1136     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1137 
1138     addrinfo hints = {.ai_family = AF_INET};
1139     ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
1140     EXPECT_TRUE(result == nullptr);
1141 
1142     dns.clearQueries();
1143     hints = {.ai_family = AF_INET6};
1144     result = safe_getaddrinfo("hello", nullptr, &hints);
1145     EXPECT_TRUE(result == nullptr);
1146 }
1147 
TEST_F(ResolverTest,GetAddrInfo_cnamesIllegalRdata)1148 TEST_F(ResolverTest, GetAddrInfo_cnamesIllegalRdata) {
1149     test::DNSResponder dns;
1150     const std::vector<DnsRecord> records = {
1151             {kHelloExampleCom, ns_type::ns_t_cname, ".!#?"},
1152     };
1153     StartDns(dns, records);
1154     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1155 
1156     addrinfo hints = {.ai_family = AF_INET};
1157     ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
1158     EXPECT_TRUE(result == nullptr);
1159 
1160     dns.clearQueries();
1161     hints = {.ai_family = AF_INET6};
1162     result = safe_getaddrinfo("hello", nullptr, &hints);
1163     EXPECT_TRUE(result == nullptr);
1164 }
1165 
TEST_F(ResolverTest,GetAddrInfoForCaseInSensitiveDomains)1166 TEST_F(ResolverTest, GetAddrInfoForCaseInSensitiveDomains) {
1167     test::DNSResponder dns;
1168     const char* host_name = "howdy.example.com.";
1169     const char* host_name2 = "HOWDY.example.com.";
1170     const std::vector<DnsRecord> records = {
1171             {host_name, ns_type::ns_t_a, "1.2.3.4"},
1172             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
1173             {host_name2, ns_type::ns_t_a, "1.2.3.5"},
1174             {host_name2, ns_type::ns_t_aaaa, "::1.2.3.5"},
1175     };
1176     StartDns(dns, records);
1177     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1178 
1179     ScopedAddrinfo hostname_result = safe_getaddrinfo("howdy", nullptr, nullptr);
1180     EXPECT_TRUE(hostname_result != nullptr);
1181     const size_t hostname1_count_after_first_query = GetNumQueries(dns, host_name);
1182     EXPECT_LE(1U, hostname1_count_after_first_query);
1183     // Could be A or AAAA
1184     std::string hostname_result_str = ToString(hostname_result);
1185     EXPECT_TRUE(hostname_result_str == "1.2.3.4" || hostname_result_str == "::1.2.3.4");
1186 
1187     // Verify that the name is cached.
1188     ScopedAddrinfo hostname2_result = safe_getaddrinfo("HOWDY", nullptr, nullptr);
1189     EXPECT_TRUE(hostname2_result != nullptr);
1190     const size_t hostname1_count_after_second_query = GetNumQueries(dns, host_name);
1191     EXPECT_LE(1U, hostname1_count_after_second_query);
1192 
1193     // verify that there is no change in num of queries for howdy.example.com
1194     EXPECT_EQ(hostname1_count_after_first_query, hostname1_count_after_second_query);
1195 
1196     // Number of queries for HOWDY.example.com would be >= 1 if domain names
1197     // are considered case-sensitive, else number of queries should be 0.
1198     const size_t hostname2_count = GetNumQueries(dns, host_name2);
1199     EXPECT_EQ(0U,hostname2_count);
1200     std::string hostname2_result_str = ToString(hostname2_result);
1201     EXPECT_TRUE(hostname2_result_str == "1.2.3.4" || hostname2_result_str == "::1.2.3.4");
1202 
1203     // verify that the result is still the same address even though
1204     // mixed-case string is not in the DNS
1205     ScopedAddrinfo result = safe_getaddrinfo("HowDY", nullptr, nullptr);
1206     EXPECT_TRUE(result != nullptr);
1207     std::string result_str = ToString(result);
1208     EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4");
1209 }
1210 
TEST_F(ResolverTest,MultidomainResolution)1211 TEST_F(ResolverTest, MultidomainResolution) {
1212     constexpr char host_name[] = "nihao.example2.com.";
1213     std::vector<std::string> searchDomains = {"example1.com", "example2.com", "example3.com"};
1214 
1215     test::DNSResponder dns("127.0.0.6");
1216     StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.3"}});
1217     ASSERT_TRUE(mDnsClient.SetResolversForNetwork({"127.0.0.6"}, searchDomains));
1218 
1219     const hostent* result = gethostbyname("nihao");
1220 
1221     EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
1222     ASSERT_FALSE(result == nullptr);
1223     ASSERT_EQ(4, result->h_length);
1224     ASSERT_FALSE(result->h_addr_list[0] == nullptr);
1225     EXPECT_EQ("1.2.3.3", ToString(result));
1226     EXPECT_TRUE(result->h_addr_list[1] == nullptr);
1227 }
1228 
TEST_F(ResolverTest,GetAddrInfoV6_numeric)1229 TEST_F(ResolverTest, GetAddrInfoV6_numeric) {
1230     constexpr char host_name[] = "ohayou.example.com.";
1231     constexpr char numeric_addr[] = "fe80::1%lo";
1232 
1233     test::DNSResponder dns;
1234     dns.setResponseProbability(0.0);
1235     StartDns(dns, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
1236     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
1237 
1238     addrinfo hints = {.ai_family = AF_INET6};
1239     ScopedAddrinfo result = safe_getaddrinfo(numeric_addr, nullptr, &hints);
1240     EXPECT_TRUE(result != nullptr);
1241     EXPECT_EQ(numeric_addr, ToString(result));
1242     EXPECT_TRUE(dns.queries().empty());  // Ensure no DNS queries were sent out
1243 
1244     // Now try a non-numeric hostname query with the AI_NUMERICHOST flag set.
1245     // We should fail without sending out a DNS query.
1246     hints.ai_flags |= AI_NUMERICHOST;
1247     result = safe_getaddrinfo(host_name, nullptr, &hints);
1248     EXPECT_TRUE(result == nullptr);
1249     EXPECT_TRUE(dns.queries().empty());  // Ensure no DNS queries were sent out
1250 }
1251 
TEST_F(ResolverTest,GetAddrInfoV6_failing)1252 TEST_F(ResolverTest, GetAddrInfoV6_failing) {
1253     constexpr char listen_addr0[] = "127.0.0.7";
1254     constexpr char listen_addr1[] = "127.0.0.8";
1255     const char* host_name = "ohayou.example.com.";
1256 
1257     test::DNSResponder dns0(listen_addr0);
1258     test::DNSResponder dns1(listen_addr1);
1259     dns0.setResponseProbability(0.0);
1260     StartDns(dns0, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
1261     StartDns(dns1, {{host_name, ns_type::ns_t_aaaa, "2001:db8::6"}});
1262 
1263     std::vector<std::string> servers = {listen_addr0, listen_addr1};
1264     // <sample validity in s> <success threshold in percent> <min samples> <max samples>
1265     int sample_count = 8;
1266     const std::array<int, IDnsResolver::RESOLVER_PARAMS_COUNT> params = {
1267             300, 25, sample_count, sample_count, 0, 0};
1268     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(ResolverParams::Builder()
1269                                                           .setDnsServers(servers)
1270                                                           .setDotServers({})
1271                                                           .setParams(params)
1272                                                           .build()));
1273 
1274     // Repeatedly perform resolutions for non-existing domains until MAXNSSAMPLES resolutions have
1275     // reached the dns0, which is set to fail. No more requests should then arrive at that server
1276     // for the next sample_lifetime seconds.
1277     // TODO: This approach is implementation-dependent, change once metrics reporting is available.
1278     const addrinfo hints = {.ai_family = AF_INET6};
1279     for (int i = 0; i < sample_count; ++i) {
1280         std::string domain = fmt::format("nonexistent{}", i);
1281         ScopedAddrinfo result = safe_getaddrinfo(domain.c_str(), nullptr, &hints);
1282     }
1283     // Due to 100% errors for all possible samples, the server should be ignored from now on and
1284     // only the second one used for all following queries, until NSSAMPLE_VALIDITY is reached.
1285     dns0.clearQueries();
1286     dns1.clearQueries();
1287     ScopedAddrinfo result = safe_getaddrinfo("ohayou", nullptr, &hints);
1288     EXPECT_TRUE(result != nullptr);
1289     EXPECT_EQ(0U, GetNumQueries(dns0, host_name));
1290     EXPECT_EQ(1U, GetNumQueries(dns1, host_name));
1291 }
1292 
TEST_F(ResolverTest,GetAddrInfoV6_nonresponsive)1293 TEST_F(ResolverTest, GetAddrInfoV6_nonresponsive) {
1294     constexpr char listen_addr0[] = "127.0.0.7";
1295     constexpr char listen_addr1[] = "127.0.0.8";
1296     constexpr char listen_srv[] = "53";
1297     constexpr char host_name1[] = "ohayou.example.com.";
1298     constexpr char host_name2[] = "ciao.example.com.";
1299     const std::vector<std::string> defaultSearchDomain = {"example.com"};
1300     // The minimal timeout is 1000ms, so we can't decrease timeout
1301     // So reduce retry count.
1302     const std::array<int, IDnsResolver::RESOLVER_PARAMS_COUNT> reduceRetryParams = {
1303             300,      // sample validity in seconds
1304             25,       // success threshod in percent
1305             8,    8,  // {MIN,MAX}_SAMPLES
1306             1000,     // BASE_TIMEOUT_MSEC
1307             1,        // retry count
1308     };
1309     const std::vector<DnsRecord> records0 = {
1310             {host_name1, ns_type::ns_t_aaaa, "2001:db8::5"},
1311             {host_name2, ns_type::ns_t_aaaa, "2001:db8::5"},
1312     };
1313     const std::vector<DnsRecord> records1 = {
1314             {host_name1, ns_type::ns_t_aaaa, "2001:db8::6"},
1315             {host_name2, ns_type::ns_t_aaaa, "2001:db8::6"},
1316     };
1317 
1318     // dns0 does not respond with 100% probability, while
1319     // dns1 responds normally, at least initially.
1320     test::DNSResponder dns0(listen_addr0, listen_srv, static_cast<ns_rcode>(-1));
1321     test::DNSResponder dns1(listen_addr1, listen_srv, static_cast<ns_rcode>(-1));
1322     dns0.setResponseProbability(0.0);
1323     StartDns(dns0, records0);
1324     StartDns(dns1, records1);
1325     ASSERT_TRUE(
1326             mDnsClient.SetResolversFromParcel(ResolverParams::Builder()
1327                                                       .setDnsServers({listen_addr0, listen_addr1})
1328                                                       .setDotServers({})
1329                                                       .setParams(reduceRetryParams)
1330                                                       .build()));
1331 
1332     // Specify ai_socktype to make getaddrinfo will only query 1 time
1333     const addrinfo hints = {.ai_family = AF_INET6, .ai_socktype = SOCK_STREAM};
1334 
1335     // dns0 will ignore the request, and we'll fallback to dns1 after the first
1336     // retry.
1337     ScopedAddrinfo result = safe_getaddrinfo(host_name1, nullptr, &hints);
1338     EXPECT_TRUE(result != nullptr);
1339     EXPECT_EQ(1U, GetNumQueries(dns0, host_name1));
1340     EXPECT_EQ(1U, GetNumQueries(dns1, host_name1));
1341     ExpectDnsEvent(INetdEventListener::EVENT_GETADDRINFO, 0, host_name1, {"2001:db8::6"});
1342 
1343     // Now make dns1 also ignore 100% requests... The resolve should alternate
1344     // queries between the nameservers and fail
1345     dns1.setResponseProbability(0.0);
1346     addrinfo* result2 = nullptr;
1347     EXPECT_EQ(EAI_NODATA, getaddrinfo(host_name2, nullptr, &hints, &result2));
1348     EXPECT_EQ(nullptr, result2);
1349     EXPECT_EQ(1U, GetNumQueries(dns0, host_name2));
1350     EXPECT_EQ(1U, GetNumQueries(dns1, host_name2));
1351     ExpectDnsEvent(INetdEventListener::EVENT_GETADDRINFO, RCODE_TIMEOUT, host_name2, {});
1352 }
1353 
TEST_F(ResolverTest,GetAddrInfoV6_concurrent)1354 TEST_F(ResolverTest, GetAddrInfoV6_concurrent) {
1355     constexpr char listen_addr0[] = "127.0.0.9";
1356     constexpr char listen_addr1[] = "127.0.0.10";
1357     constexpr char listen_addr2[] = "127.0.0.11";
1358     constexpr char host_name[] = "konbanha.example.com.";
1359 
1360     test::DNSResponder dns0(listen_addr0);
1361     test::DNSResponder dns1(listen_addr1);
1362     test::DNSResponder dns2(listen_addr2);
1363     StartDns(dns0, {{host_name, ns_type::ns_t_aaaa, "2001:db8::5"}});
1364     StartDns(dns1, {{host_name, ns_type::ns_t_aaaa, "2001:db8::6"}});
1365     StartDns(dns2, {{host_name, ns_type::ns_t_aaaa, "2001:db8::7"}});
1366 
1367     const std::vector<std::string> servers = {listen_addr0, listen_addr1, listen_addr2};
1368     std::vector<std::thread> threads(10);
1369     for (std::thread& thread : threads) {
1370         thread = std::thread([this, &servers]() {
1371             unsigned delay = arc4random_uniform(1 * 1000 * 1000);  // <= 1s
1372             usleep(delay);
1373             std::vector<std::string> serverSubset;
1374             for (const auto& server : servers) {
1375                 if (arc4random_uniform(2)) {
1376                     serverSubset.push_back(server);
1377                 }
1378             }
1379             if (serverSubset.empty()) serverSubset = servers;
1380             ASSERT_TRUE(mDnsClient.SetResolversForNetwork(serverSubset));
1381             const addrinfo hints = {.ai_family = AF_INET6};
1382             addrinfo* result = nullptr;
1383             int rv = getaddrinfo("konbanha", nullptr, &hints, &result);
1384             EXPECT_EQ(0, rv) << "error [" << rv << "] " << gai_strerror(rv);
1385             if (result) {
1386                 freeaddrinfo(result);
1387                 result = nullptr;
1388             }
1389         });
1390     }
1391     for (std::thread& thread : threads) {
1392         thread.join();
1393     }
1394 
1395     const auto resolvInfo = mDnsClient.getResolverInfo();
1396     ASSERT_RESULT_OK(resolvInfo);
1397     EXPECT_EQ(0, resolvInfo.value().waitForPendingReqTimeoutCount);
1398 }
1399 
TEST_F(ResolverTest,SkipBadServersDueToInternalError)1400 TEST_F(ResolverTest, SkipBadServersDueToInternalError) {
1401     constexpr char listen_addr1[] = "fe80::1";
1402     constexpr char listen_addr2[] = "255.255.255.255";
1403     constexpr char listen_addr3[] = "127.0.0.3";
1404     int counter = 0;  // To generate unique hostnames.
1405     test::DNSResponder dns(listen_addr3);
1406     ASSERT_TRUE(dns.startServer());
1407 
1408     ResolverParamsParcel setupParams = DnsResponderClient::GetDefaultResolverParamsParcel();
1409     setupParams.servers = {listen_addr1, listen_addr2, listen_addr3};
1410     setupParams.minSamples = 2;  // Recognize bad servers in two attempts when sorting not enabled.
1411 
1412     ResolverParamsParcel cleanupParams = DnsResponderClient::GetDefaultResolverParamsParcel();
1413     cleanupParams.servers.clear();
1414     cleanupParams.tlsServers.clear();
1415 
1416     for (const auto& sortNameserversFlag : {"" /* unset */, "0" /* off */, "1" /* on */}) {
1417         SCOPED_TRACE(fmt::format("sortNameversFlag_{}", sortNameserversFlag));
1418         ScopedSystemProperties scopedSystemProperties(kSortNameserversFlag, sortNameserversFlag);
1419 
1420         // Re-setup test network to make experiment flag take effect.
1421         resetNetwork();
1422 
1423         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(setupParams));
1424 
1425         // Start sending synchronized querying.
1426         for (int i = 0; i < 100; i++) {
1427             std::string hostName = fmt::format("hello{}.com.", counter++);
1428             dns.addMapping(hostName, ns_type::ns_t_a, "1.2.3.4");
1429             const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
1430             EXPECT_TRUE(safe_getaddrinfo(hostName.c_str(), nullptr, &hints) != nullptr);
1431         }
1432 
1433         const std::vector<NameserverStats> targetStats = {
1434                 NameserverStats(listen_addr1).setInternalErrors(5),
1435                 NameserverStats(listen_addr2).setInternalErrors(5),
1436                 NameserverStats(listen_addr3).setSuccesses(setupParams.maxSamples).setRttAvg(1),
1437         };
1438         EXPECT_TRUE(expectStatsNotGreaterThan(targetStats));
1439 
1440         // Also verify the number of queries received in the server because res_stats.successes has
1441         // a maximum.
1442         EXPECT_EQ(dns.queries().size(), 100U);
1443 
1444         // Reset the state.
1445         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(cleanupParams));
1446         dns.clearQueries();
1447     }
1448 }
1449 
TEST_F(ResolverTest,SkipBadServersDueToTimeout)1450 TEST_F(ResolverTest, SkipBadServersDueToTimeout) {
1451     constexpr char listen_addr1[] = "127.0.0.3";
1452     constexpr char listen_addr2[] = "127.0.0.4";
1453     int counter = 0;  // To generate unique hostnames.
1454 
1455     ResolverParamsParcel setupParams = DnsResponderClient::GetDefaultResolverParamsParcel();
1456     setupParams.servers = {listen_addr1, listen_addr2};
1457     setupParams.minSamples = 2;  // Recognize bad servers in two attempts when sorting not enabled.
1458 
1459     ResolverParamsParcel cleanupParams = DnsResponderClient::GetDefaultResolverParamsParcel();
1460     cleanupParams.servers.clear();
1461     cleanupParams.tlsServers.clear();
1462 
1463     // Set dns1 non-responsive and dns2 workable.
1464     test::DNSResponder dns1(listen_addr1, test::kDefaultListenService, static_cast<ns_rcode>(-1));
1465     test::DNSResponder dns2(listen_addr2);
1466     dns1.setResponseProbability(0.0);
1467     ASSERT_TRUE(dns1.startServer());
1468     ASSERT_TRUE(dns2.startServer());
1469 
1470     for (const auto& sortNameserversFlag : {"" /* unset */, "0" /* off */, "1" /* on */}) {
1471         SCOPED_TRACE(fmt::format("sortNameversFlag_{}", sortNameserversFlag));
1472         ScopedSystemProperties scopedSystemProperties(kSortNameserversFlag, sortNameserversFlag);
1473 
1474         // Re-setup test network to make experiment flag take effect.
1475         resetNetwork();
1476 
1477         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(setupParams));
1478 
1479         // Start sending synchronized querying.
1480         for (int i = 0; i < 100; i++) {
1481             std::string hostName = fmt::format("hello{}.com.", counter++);
1482             dns1.addMapping(hostName, ns_type::ns_t_a, "1.2.3.4");
1483             dns2.addMapping(hostName, ns_type::ns_t_a, "1.2.3.5");
1484             const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
1485             EXPECT_TRUE(safe_getaddrinfo(hostName.c_str(), nullptr, &hints) != nullptr);
1486         }
1487 
1488         const std::vector<NameserverStats> targetStats = {
1489                 NameserverStats(listen_addr1).setTimeouts(5),
1490                 NameserverStats(listen_addr2).setSuccesses(setupParams.maxSamples).setRttAvg(1),
1491         };
1492         EXPECT_TRUE(expectStatsNotGreaterThan(targetStats));
1493 
1494         // Also verify the number of queries received in the server because res_stats.successes has
1495         // an upper bound.
1496         EXPECT_GT(dns1.queries().size(), 0U);
1497         EXPECT_LT(dns1.queries().size(), 5U);
1498         EXPECT_EQ(dns2.queries().size(), 100U);
1499 
1500         // Reset the state.
1501         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(cleanupParams));
1502         dns1.clearQueries();
1503         dns2.clearQueries();
1504     }
1505 }
1506 
TEST_F(ResolverTest,GetAddrInfoFromCustTable_InvalidInput)1507 TEST_F(ResolverTest, GetAddrInfoFromCustTable_InvalidInput) {
1508     constexpr char hostnameNoip[] = "noip.example.com.";
1509     constexpr char hostnameInvalidip[] = "invalidip.example.com.";
1510     const std::vector<aidl::android::net::ResolverHostsParcel> invalidCustHosts = {
1511             {"", hostnameNoip},
1512             {"wrong IP", hostnameInvalidip},
1513     };
1514     test::DNSResponder dns;
1515     StartDns(dns, {});
1516     auto resolverParams = DnsResponderClient::GetDefaultResolverParamsParcel();
1517 
1518     ResolverOptionsParcel resolverOptions;
1519     resolverOptions.hosts = invalidCustHosts;
1520     if (!mIsResolverOptionIPCSupported) {
1521         resolverParams.resolverOptions = resolverOptions;
1522     }
1523     ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(resolverParams).isOk());
1524     if (mIsResolverOptionIPCSupported) {
1525         ASSERT_TRUE(mDnsClient.resolvService()
1526                             ->setResolverOptions(resolverParams.netId, resolverOptions)
1527                             .isOk());
1528     }
1529     for (const auto& hostname : {hostnameNoip, hostnameInvalidip}) {
1530         // The query won't get data from customized table because of invalid customized table
1531         // and DNSResponder also has no records. hostnameNoip has never registered and
1532         // hostnameInvalidip has registered but wrong IP.
1533         const addrinfo hints = {.ai_family = AF_UNSPEC};
1534         ScopedAddrinfo result = safe_getaddrinfo(hostname, nullptr, &hints);
1535         ASSERT_TRUE(result == nullptr);
1536         EXPECT_EQ(4U, GetNumQueries(dns, hostname));
1537     }
1538 }
1539 
TEST_F(ResolverTest,GetAddrInfoFromCustTable)1540 TEST_F(ResolverTest, GetAddrInfoFromCustTable) {
1541     constexpr char hostnameV4[] = "v4only.example.com.";
1542     constexpr char hostnameV6[] = "v6only.example.com.";
1543     constexpr char hostnameV4V6[] = "v4v6.example.com.";
1544     constexpr char custAddrV4[] = "1.2.3.4";
1545     constexpr char custAddrV6[] = "::1.2.3.4";
1546     constexpr char dnsSvAddrV4[] = "1.2.3.5";
1547     constexpr char dnsSvAddrV6[] = "::1.2.3.5";
1548     const std::vector<aidl::android::net::ResolverHostsParcel> custHostV4 = {
1549             {custAddrV4, hostnameV4},
1550     };
1551     const std::vector<aidl::android::net::ResolverHostsParcel> custHostV6 = {
1552             {custAddrV6, hostnameV6},
1553     };
1554     const std::vector<aidl::android::net::ResolverHostsParcel> custHostV4V6 = {
1555             {custAddrV4, hostnameV4V6},
1556             {custAddrV6, hostnameV4V6},
1557     };
1558     const std::vector<DnsRecord> dnsSvHostV4 = {
1559             {hostnameV4, ns_type::ns_t_a, dnsSvAddrV4},
1560     };
1561     const std::vector<DnsRecord> dnsSvHostV6 = {
1562             {hostnameV6, ns_type::ns_t_aaaa, dnsSvAddrV6},
1563     };
1564     const std::vector<DnsRecord> dnsSvHostV4V6 = {
1565             {hostnameV4V6, ns_type::ns_t_a, dnsSvAddrV4},
1566             {hostnameV4V6, ns_type::ns_t_aaaa, dnsSvAddrV6},
1567     };
1568     struct TestConfig {
1569         const std::string name;
1570         const std::vector<aidl::android::net::ResolverHostsParcel> customizedHosts;
1571         const std::vector<DnsRecord> dnsserverHosts;
1572         const std::vector<std::string> queryResult;
1573         std::string asParameters() const {
1574             return fmt::format("name: {}, customizedHosts: {}, dnsserverHosts: {}", name,
1575                                customizedHosts.empty() ? "No" : "Yes",
1576                                dnsserverHosts.empty() ? "No" : "Yes");
1577         }
1578     } testConfigs[]{
1579             // clang-format off
1580             {hostnameV4,    {},            {},             {}},
1581             {hostnameV4,    {},            dnsSvHostV4,    {dnsSvAddrV4}},
1582             {hostnameV4,    custHostV4,    {},             {custAddrV4}},
1583             {hostnameV4,    custHostV4,    dnsSvHostV4,    {custAddrV4}},
1584             {hostnameV6,    {},            {},             {}},
1585             {hostnameV6,    {},            dnsSvHostV6,    {dnsSvAddrV6}},
1586             {hostnameV6,    custHostV6,    {},             {custAddrV6}},
1587             {hostnameV6,    custHostV6,    dnsSvHostV6,    {custAddrV6}},
1588             {hostnameV4V6,  {},            {},             {}},
1589             {hostnameV4V6,  {},            dnsSvHostV4V6,  {dnsSvAddrV4, dnsSvAddrV6}},
1590             {hostnameV4V6,  custHostV4V6,  {},             {custAddrV4, custAddrV6}},
1591             {hostnameV4V6,  custHostV4V6,  dnsSvHostV4V6,  {custAddrV4, custAddrV6}},
1592             // clang-format on
1593     };
1594 
1595     for (const auto& config : testConfigs) {
1596         SCOPED_TRACE(config.asParameters());
1597 
1598         test::DNSResponder dns;
1599         StartDns(dns, config.dnsserverHosts);
1600 
1601         auto resolverParams = DnsResponderClient::GetDefaultResolverParamsParcel();
1602         ResolverOptionsParcel resolverOptions;
1603         resolverOptions.hosts = config.customizedHosts;
1604         if (!mIsResolverOptionIPCSupported) {
1605             resolverParams.resolverOptions = resolverOptions;
1606         }
1607         ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(resolverParams).isOk());
1608 
1609         if (mIsResolverOptionIPCSupported) {
1610             ASSERT_TRUE(mDnsClient.resolvService()
1611                                 ->setResolverOptions(resolverParams.netId, resolverOptions)
1612                                 .isOk());
1613         }
1614         const addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_STREAM};
1615         ScopedAddrinfo result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
1616         if (config.customizedHosts.empty() && config.dnsserverHosts.empty()) {
1617             ASSERT_TRUE(result == nullptr);
1618             EXPECT_EQ(2U, GetNumQueries(dns, config.name.c_str()));
1619         } else {
1620             ASSERT_TRUE(result != nullptr);
1621             EXPECT_THAT(ToStrings(result), testing::UnorderedElementsAreArray(config.queryResult));
1622             EXPECT_EQ(config.customizedHosts.empty() ? 2U : 0U,
1623                       GetNumQueries(dns, config.name.c_str()));
1624         }
1625 
1626         EXPECT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
1627     }
1628 }
1629 
TEST_F(ResolverTest,GetAddrInfoFromCustTable_Modify)1630 TEST_F(ResolverTest, GetAddrInfoFromCustTable_Modify) {
1631     constexpr char hostnameV4V6[] = "v4v6.example.com.";
1632     constexpr char custAddrV4[] = "1.2.3.4";
1633     constexpr char custAddrV6[] = "::1.2.3.4";
1634     constexpr char dnsSvAddrV4[] = "1.2.3.5";
1635     constexpr char dnsSvAddrV6[] = "::1.2.3.5";
1636     const std::vector<DnsRecord> dnsSvHostV4V6 = {
1637             {hostnameV4V6, ns_type::ns_t_a, dnsSvAddrV4},
1638             {hostnameV4V6, ns_type::ns_t_aaaa, dnsSvAddrV6},
1639     };
1640     const std::vector<aidl::android::net::ResolverHostsParcel> custHostV4V6 = {
1641             {custAddrV4, hostnameV4V6},
1642             {custAddrV6, hostnameV4V6},
1643     };
1644     test::DNSResponder dns;
1645     StartDns(dns, dnsSvHostV4V6);
1646     auto resolverParams = DnsResponderClient::GetDefaultResolverParamsParcel();
1647 
1648     ResolverOptionsParcel resolverOptions;
1649     resolverOptions.hosts = custHostV4V6;
1650     if (!mIsResolverOptionIPCSupported) {
1651         resolverParams.resolverOptions = resolverOptions;
1652     }
1653     ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(resolverParams).isOk());
1654 
1655     if (mIsResolverOptionIPCSupported) {
1656         ASSERT_TRUE(mDnsClient.resolvService()
1657                             ->setResolverOptions(resolverParams.netId, resolverOptions)
1658                             .isOk());
1659     }
1660 
1661     const addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_STREAM};
1662     ScopedAddrinfo result = safe_getaddrinfo(hostnameV4V6, nullptr, &hints);
1663     ASSERT_TRUE(result != nullptr);
1664     EXPECT_THAT(ToStrings(result), testing::UnorderedElementsAreArray({custAddrV4, custAddrV6}));
1665     EXPECT_EQ(0U, GetNumQueries(dns, hostnameV4V6));
1666 
1667     resolverOptions.hosts = {};
1668     if (!mIsResolverOptionIPCSupported) {
1669         resolverParams.resolverOptions = resolverOptions;
1670         ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(resolverParams).isOk());
1671     } else {
1672         ASSERT_TRUE(mDnsClient.resolvService()
1673                             ->setResolverOptions(resolverParams.netId, resolverOptions)
1674                             .isOk());
1675     }
1676     result = safe_getaddrinfo(hostnameV4V6, nullptr, &hints);
1677     ASSERT_TRUE(result != nullptr);
1678     EXPECT_THAT(ToStrings(result), testing::UnorderedElementsAreArray({dnsSvAddrV4, dnsSvAddrV6}));
1679     EXPECT_EQ(2U, GetNumQueries(dns, hostnameV4V6));
1680 }
1681 
TEST_F(ResolverTest,GetAddrInfoV4V6FromCustTable_MultiAnswers)1682 TEST_F(ResolverTest, GetAddrInfoV4V6FromCustTable_MultiAnswers) {
1683     test::DNSResponder dns;
1684     StartDns(dns, {});
1685 
1686     auto resolverParams = DnsResponderClient::GetDefaultResolverParamsParcel();
1687     ResolverOptionsParcel resolverOptions;
1688     resolverOptions.hosts = {
1689             {kHelloExampleComAddrV4, kHelloExampleCom},
1690             {kHelloExampleComAddrV6_GUA, kHelloExampleCom},
1691             {kHelloExampleComAddrV6_IPV4COMPAT, kHelloExampleCom},
1692             {kHelloExampleComAddrV6_TEREDO, kHelloExampleCom},
1693     };
1694     if (!mIsResolverOptionIPCSupported) {
1695         resolverParams.resolverOptions = resolverOptions;
1696     }
1697     ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(resolverParams).isOk());
1698 
1699     if (mIsResolverOptionIPCSupported) {
1700         ASSERT_TRUE(mDnsClient.resolvService()
1701                             ->setResolverOptions(resolverParams.netId, resolverOptions)
1702                             .isOk());
1703     }
1704 
1705     addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_STREAM};
1706     ScopedAddrinfo result = safe_getaddrinfo(kHelloExampleCom, nullptr, &hints);
1707     ASSERT_TRUE(result != nullptr);
1708     // Expect the order is the same as the order of record insertion because the custom table uses
1709     // std::multimap to store and the queried results are not sorted by RFC 6724.
1710     // See getCustomHosts in packages/modules/DnsResolver/getaddrinfo.cpp
1711     EXPECT_THAT(ToStrings(result),
1712                 testing::ElementsAreArray({kHelloExampleComAddrV4, kHelloExampleComAddrV6_GUA,
1713                                            kHelloExampleComAddrV6_IPV4COMPAT,
1714                                            kHelloExampleComAddrV6_TEREDO}));
1715     EXPECT_EQ(0U, GetNumQueries(dns, kHelloExampleCom));
1716 
1717     hints = {.ai_family = AF_UNSPEC};
1718     result = safe_getaddrinfo(kHelloExampleCom, nullptr, &hints);
1719     ASSERT_TRUE(result != nullptr);
1720     // The overall result is the concatenation of each result from explore_fqdn().
1721     // resolv_getaddrinfo() calls explore_fqdn() many times by the different explore_options.
1722     // It means that the results of each explore_options keep the order and concatenates
1723     // all results into one link list. The address order of the output addrinfo is:
1724     //   1.2.3.4 (socktype=2, protocol=17) ->
1725     //   2404:6800::5175:15ca (socktype=2, protocol=17) ->
1726     //   ::1.2.3.4 (socktype=2, protocol=17) ->
1727     //   2001::47c1 (socktype=2, protocol=17) ->
1728     //   1.2.3.4 (socktype=1, protocol=6) ->
1729     //   2404:6800::5175:15ca (socktype=1, protocol=6) ->
1730     //   ::1.2.3.4 (socktype=1, protocol=6) ->
1731     //   2001::47c1 (socktype=1, protocol=6)
1732     //
1733     // See resolv_getaddrinfo, explore_fqdn and dns_getaddrinfo.
1734     EXPECT_THAT(ToStrings(result),
1735                 testing::ElementsAreArray(
1736                         {kHelloExampleComAddrV4, kHelloExampleComAddrV6_GUA,
1737                          kHelloExampleComAddrV6_IPV4COMPAT, kHelloExampleComAddrV6_TEREDO,
1738                          kHelloExampleComAddrV4, kHelloExampleComAddrV6_GUA,
1739                          kHelloExampleComAddrV6_IPV4COMPAT, kHelloExampleComAddrV6_TEREDO}));
1740     EXPECT_EQ(0U, GetNumQueries(dns, kHelloExampleCom));
1741 }
1742 
TEST_F(ResolverTest,EmptySetup)1743 TEST_F(ResolverTest, EmptySetup) {
1744     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(ResolverParamsParcel{.netId = TEST_NETID}));
1745     const auto resolvInfo = mDnsClient.getResolverInfo();
1746     ASSERT_RESULT_OK(resolvInfo);
1747     EXPECT_TRUE(resolvInfo.value().dnsServers.empty());
1748     EXPECT_TRUE(resolvInfo.value().domains.empty());
1749     EXPECT_TRUE(resolvInfo.value().dotServers.empty());
1750     EXPECT_EQ(0U, resolvInfo.value().params.sample_validity);
1751     EXPECT_EQ(0U, resolvInfo.value().params.success_threshold);
1752     EXPECT_EQ(0U, resolvInfo.value().params.min_samples);
1753     EXPECT_EQ(0U, resolvInfo.value().params.max_samples);
1754     // We don't check baseTimeoutMsec and retryCount because their value differ depending on
1755     // the experiment flags.
1756 }
1757 
TEST_F(ResolverTest,SearchPathChange)1758 TEST_F(ResolverTest, SearchPathChange) {
1759     constexpr char listen_addr[] = "127.0.0.13";
1760     constexpr char host_name1[] = "test13.domain1.org.";
1761     constexpr char host_name2[] = "test13.domain2.org.";
1762     std::vector<std::string> servers = {listen_addr};
1763     std::vector<std::string> domains = {"domain1.org"};
1764 
1765     const std::vector<DnsRecord> records = {
1766             {host_name1, ns_type::ns_t_aaaa, "2001:db8::13"},
1767             {host_name2, ns_type::ns_t_aaaa, "2001:db8::1:13"},
1768     };
1769     test::DNSResponder dns(listen_addr);
1770     StartDns(dns, records);
1771     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
1772 
1773     const addrinfo hints = {.ai_family = AF_INET6};
1774     ScopedAddrinfo result = safe_getaddrinfo("test13", nullptr, &hints);
1775     EXPECT_TRUE(result != nullptr);
1776     EXPECT_EQ(1U, dns.queries().size());
1777     EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
1778     EXPECT_EQ("2001:db8::13", ToString(result));
1779 
1780     // Test that changing the domain search path on its own works.
1781     domains = {"domain2.org"};
1782     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, domains));
1783     dns.clearQueries();
1784 
1785     result = safe_getaddrinfo("test13", nullptr, &hints);
1786     EXPECT_TRUE(result != nullptr);
1787     EXPECT_EQ(1U, dns.queries().size());
1788     EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
1789     EXPECT_EQ("2001:db8::1:13", ToString(result));
1790 }
1791 
TEST_F(ResolverTest,SearchPathPrune)1792 TEST_F(ResolverTest, SearchPathPrune) {
1793     constexpr size_t DUPLICATED_DOMAIN_NUM = 3;
1794     constexpr char listen_addr[] = "127.0.0.13";
1795     constexpr char domian_name1[] = "domain13.org.";
1796     constexpr char domian_name2[] = "domain14.org.";
1797     constexpr char host_name1[] = "test13.domain13.org.";
1798     constexpr char host_name2[] = "test14.domain14.org.";
1799     std::vector<std::string> servers = {listen_addr};
1800 
1801     std::vector<std::string> testDomains1;
1802     std::vector<std::string> testDomains2;
1803     // Domain length should be <= 255
1804     // Max number of domains in search path is 6
1805     for (size_t i = 0; i < MAXDNSRCH + 1; i++) {
1806         // Fill up with invalid domain
1807         testDomains1.push_back(std::string(300, i + '0'));
1808         // Fill up with valid but duplicated domain
1809         testDomains2.push_back(fmt::format("domain{}.org", i % DUPLICATED_DOMAIN_NUM));
1810     }
1811 
1812     // Add valid domain used for query.
1813     testDomains1.push_back(domian_name1);
1814 
1815     // Add valid domain twice used for query.
1816     testDomains2.push_back(domian_name2);
1817     testDomains2.push_back(domian_name2);
1818 
1819     const std::vector<DnsRecord> records = {
1820             {host_name1, ns_type::ns_t_aaaa, "2001:db8::13"},
1821             {host_name2, ns_type::ns_t_aaaa, "2001:db8::1:13"},
1822     };
1823     test::DNSResponder dns(listen_addr);
1824     StartDns(dns, records);
1825     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, testDomains1));
1826 
1827     const addrinfo hints = {.ai_family = AF_INET6};
1828     ScopedAddrinfo result = safe_getaddrinfo("test13", nullptr, &hints);
1829 
1830     EXPECT_TRUE(result != nullptr);
1831 
1832     EXPECT_EQ(1U, dns.queries().size());
1833     EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
1834     EXPECT_EQ("2001:db8::13", ToString(result));
1835 
1836     auto resolvInfo = mDnsClient.getResolverInfo();
1837     ASSERT_RESULT_OK(resolvInfo);
1838     const auto& res_domains1 = resolvInfo.value().domains;
1839     // Expect 1 valid domain, invalid domains are removed.
1840     ASSERT_EQ(1U, res_domains1.size());
1841     EXPECT_EQ(domian_name1, res_domains1[0]);
1842 
1843     dns.clearQueries();
1844 
1845     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers, testDomains2));
1846 
1847     result = safe_getaddrinfo("test14", nullptr, &hints);
1848     EXPECT_TRUE(result != nullptr);
1849 
1850     // (3 domains * 2 retries) + 1 success query = 7
1851     EXPECT_EQ(7U, dns.queries().size());
1852     EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
1853     EXPECT_EQ("2001:db8::1:13", ToString(result));
1854 
1855     resolvInfo = mDnsClient.getResolverInfo();
1856     ASSERT_RESULT_OK(resolvInfo);
1857     const auto& res_domains2 = resolvInfo.value().domains;
1858     // Expect 4 valid domain, duplicate domains are removed.
1859     EXPECT_EQ(DUPLICATED_DOMAIN_NUM + 1U, res_domains2.size());
1860     EXPECT_THAT(
1861             std::vector<std::string>({"domain0.org", "domain1.org", "domain2.org", domian_name2}),
1862             testing::ElementsAreArray(res_domains2));
1863 }
1864 
1865 // If we move this function to dns_responder_client, it will complicate the dependency need of
1866 // dns_tls_frontend.h.
setupTlsServers(const std::vector<std::string> & servers,std::vector<std::unique_ptr<test::DnsTlsFrontend>> * tls)1867 static void setupTlsServers(const std::vector<std::string>& servers,
1868                             std::vector<std::unique_ptr<test::DnsTlsFrontend>>* tls) {
1869     constexpr char listen_udp[] = "53";
1870     constexpr char listen_tls[] = "853";
1871 
1872     for (const auto& server : servers) {
1873         auto t = std::make_unique<test::DnsTlsFrontend>(server, listen_tls, server, listen_udp);
1874         t = std::make_unique<test::DnsTlsFrontend>(server, listen_tls, server, listen_udp);
1875         t->startServer();
1876         tls->push_back(std::move(t));
1877     }
1878 }
1879 
TEST_F(ResolverTest,MaxServerPrune_Binder)1880 TEST_F(ResolverTest, MaxServerPrune_Binder) {
1881     std::vector<std::string> domains;
1882     std::vector<std::unique_ptr<test::DNSResponder>> dns;
1883     std::vector<std::unique_ptr<test::DnsTlsFrontend>> tls;
1884     std::vector<std::string> servers;
1885     std::vector<DnsResponderClient::Mapping> mappings;
1886 
1887     for (unsigned i = 0; i < MAXDNSRCH + 1; i++) {
1888         domains.push_back(fmt::format("example{}.com", i));
1889     }
1890     ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupMappings(1, domains, &mappings));
1891     ASSERT_NO_FATAL_FAILURE(mDnsClient.SetupDNSServers(MAXNS + 1, mappings, &dns, &servers));
1892     ASSERT_NO_FATAL_FAILURE(setupTlsServers(servers, &tls));
1893 
1894     const auto parcel = ResolverParams::Builder()
1895                                 .setDomains(domains)
1896                                 .setDnsServers(servers)
1897                                 .setDotServers(servers)
1898                                 .setPrivateDnsProvider(kDefaultPrivateDnsHostName)
1899                                 .build();
1900     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
1901 
1902     // If the private DNS validation hasn't completed yet before backend DNS servers stop,
1903     // TLS servers will get stuck in handleOneRequest(), which causes this test stuck in
1904     // ~DnsTlsFrontend() because the TLS server loop threads can't be terminated.
1905     // So, wait for private DNS validation done before stopping backend DNS servers.
1906     for (int i = 0; i < MAXNS; i++) {
1907         LOG(INFO) << "Waiting for private DNS validation on " << tls[i]->listen_address() << ".";
1908         EXPECT_TRUE(WaitForPrivateDnsValidation(tls[i]->listen_address(), true));
1909         LOG(INFO) << "private DNS validation on " << tls[i]->listen_address() << " done.";
1910     }
1911 
1912     const auto resolvInfo = mDnsClient.getResolverInfo();
1913     ASSERT_RESULT_OK(resolvInfo);
1914     EXPECT_EQ(static_cast<size_t>(MAXNS), resolvInfo.value().dnsServers.size());
1915     EXPECT_EQ(static_cast<size_t>(MAXNS), resolvInfo.value().dotServers.size());
1916     EXPECT_EQ(static_cast<size_t>(MAXDNSRCH), resolvInfo.value().domains.size());
1917     EXPECT_TRUE(std::equal(servers.begin(), servers.begin() + MAXNS,
1918                            resolvInfo.value().dnsServers.begin()));
1919     EXPECT_TRUE(std::equal(servers.begin(), servers.begin() + MAXNS,
1920                            resolvInfo.value().dotServers.begin()));
1921     EXPECT_TRUE(std::equal(domains.begin(), domains.begin() + MAXDNSRCH,
1922                            resolvInfo.value().domains.begin()));
1923 }
1924 
TEST_F(ResolverTest,ResolverStats)1925 TEST_F(ResolverTest, ResolverStats) {
1926     constexpr char listen_addr1[] = "127.0.0.4";
1927     constexpr char listen_addr2[] = "127.0.0.5";
1928     constexpr char listen_addr3[] = "127.0.0.6";
1929 
1930     // Set server 1 timeout.
1931     test::DNSResponder dns1(listen_addr1, "53", static_cast<ns_rcode>(-1));
1932     dns1.setResponseProbability(0.0);
1933     ASSERT_TRUE(dns1.startServer());
1934 
1935     // Set server 2 responding server failure.
1936     test::DNSResponder dns2(listen_addr2);
1937     dns2.setResponseProbability(0.0);
1938     ASSERT_TRUE(dns2.startServer());
1939 
1940     // Set server 3 workable.
1941     test::DNSResponder dns3(listen_addr3);
1942     dns3.addMapping(kHelloExampleCom, ns_type::ns_t_a, "1.2.3.4");
1943     ASSERT_TRUE(dns3.startServer());
1944 
1945     std::vector<std::string> servers = {listen_addr1, listen_addr2, listen_addr3};
1946     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
1947 
1948     dns3.clearQueries();
1949     const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
1950     ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
1951     size_t found = GetNumQueries(dns3, kHelloExampleCom);
1952     EXPECT_LE(1U, found);
1953     std::string result_str = ToString(result);
1954     EXPECT_TRUE(result_str == "1.2.3.4") << ", result_str='" << result_str << "'";
1955 
1956     const std::vector<NameserverStats> expectedCleartextDnsStats = {
1957             NameserverStats(listen_addr1).setTimeouts(1),
1958             NameserverStats(listen_addr2).setErrors(1),
1959             NameserverStats(listen_addr3).setSuccesses(1).setRttAvg(1),
1960     };
1961     EXPECT_TRUE(expectStatsEqualTo(expectedCleartextDnsStats));
1962 }
1963 
TEST_F(ResolverTest,AlwaysUseLatestSetupParamsInLookups)1964 TEST_F(ResolverTest, AlwaysUseLatestSetupParamsInLookups) {
1965     constexpr char listen_addr1[] = "127.0.0.3";
1966     constexpr char listen_addr2[] = "255.255.255.255";
1967     constexpr char listen_addr3[] = "127.0.0.4";
1968     constexpr char hostname[] = "hello";
1969     constexpr char fqdn_with_search_domain[] = "hello.domain2.com.";
1970 
1971     test::DNSResponder dns1(listen_addr1, test::kDefaultListenService, static_cast<ns_rcode>(-1));
1972     dns1.setResponseProbability(0.0);
1973     ASSERT_TRUE(dns1.startServer());
1974 
1975     test::DNSResponder dns3(listen_addr3);
1976     StartDns(dns3, {{fqdn_with_search_domain, ns_type::ns_t_a, "1.2.3.4"}});
1977 
1978     ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
1979     parcel.tlsServers.clear();
1980     parcel.servers = {listen_addr1, listen_addr2};
1981     parcel.domains = {"domain1.com", "domain2.com"};
1982     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
1983 
1984     // Expect the things happening in t1:
1985     //   1. The lookup starts using the first domain for query. It sends queries to the populated
1986     //      nameserver list {listen_addr1, listen_addr2} for the hostname "hello.domain1.com".
1987     //   2. A different list of nameservers is updated to the resolver. Revision ID is incremented.
1988     //   3. The query for the hostname times out. The lookup fails to add the timeout record to the
1989     //      the stats because of the unmatched revision ID.
1990     //   4. The lookup starts using the second domain for query. It sends queries to the populated
1991     //      nameserver list {listen_addr3, listen_addr1, listen_addr2} for another hostname
1992     //      "hello.domain2.com".
1993     //   5. The lookup gets the answer and updates a success record to the stats.
1994     std::thread t1([&hostname]() {
1995         const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
1996         ScopedAddrinfo result = safe_getaddrinfo(hostname, nullptr, &hints);
1997         EXPECT_NE(result.get(), nullptr);
1998         EXPECT_EQ(ToString(result), "1.2.3.4");
1999     });
2000 
2001     // Wait for t1 to start the step 1.
2002     while (dns1.queries().size() == 0) {
2003         usleep(1000);
2004     }
2005 
2006     // Update the resolver with three nameservers. This will increment the revision ID.
2007     parcel.servers = {listen_addr3, listen_addr1, listen_addr2};
2008     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
2009 
2010     t1.join();
2011     EXPECT_EQ(0U, GetNumQueriesForType(dns3, ns_type::ns_t_aaaa, fqdn_with_search_domain));
2012     EXPECT_EQ(1U, GetNumQueriesForType(dns3, ns_type::ns_t_a, fqdn_with_search_domain));
2013 
2014     const std::vector<NameserverStats> expectedCleartextDnsStats = {
2015             NameserverStats(listen_addr1),
2016             NameserverStats(listen_addr2),
2017             NameserverStats(listen_addr3).setSuccesses(1).setRttAvg(1),
2018     };
2019     EXPECT_TRUE(expectStatsEqualTo(expectedCleartextDnsStats));
2020 }
2021 
2022 // Test what happens if the specified TLS server is nonexistent.
TEST_F(ResolverTest,GetHostByName_TlsMissing)2023 TEST_F(ResolverTest, GetHostByName_TlsMissing) {
2024     constexpr char host_name[] = "tlsmissing.example.com.";
2025     test::DNSResponder dns;
2026     StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.3"}});
2027 
2028     // There's nothing listening on this address, so validation will either fail or
2029     /// hang.  Either way, queries will continue to flow to the DNSResponder.
2030     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(ResolverParams::Builder().build()));
2031 
2032     const hostent* result;
2033     result = gethostbyname("tlsmissing");
2034     ASSERT_FALSE(result == nullptr);
2035     EXPECT_EQ("1.2.3.3", ToString(result));
2036 }
2037 
2038 // Test what happens if the specified TLS server replies with garbage.
TEST_F(ResolverTest,GetHostByName_TlsBroken)2039 TEST_F(ResolverTest, GetHostByName_TlsBroken) {
2040     constexpr char host_name1[] = "tlsbroken1.example.com.";
2041     constexpr char host_name2[] = "tlsbroken2.example.com.";
2042     const std::vector<DnsRecord> records = {
2043             {host_name1, ns_type::ns_t_a, "1.2.3.1"},
2044             {host_name2, ns_type::ns_t_a, "1.2.3.2"},
2045     };
2046 
2047     test::DNSResponder dns;
2048     StartDns(dns, records);
2049 
2050     // Bind the specified private DNS socket but don't respond to any client sockets yet.
2051     int s = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP);
2052     ASSERT_TRUE(s >= 0);
2053     struct sockaddr_in tlsServer = {
2054             .sin_family = AF_INET,
2055             .sin_port = htons(853),
2056     };
2057     ASSERT_TRUE(inet_pton(AF_INET, kDefaultServer, &tlsServer.sin_addr));
2058     ASSERT_TRUE(enableSockopt(s, SOL_SOCKET, SO_REUSEPORT).ok());
2059     ASSERT_TRUE(enableSockopt(s, SOL_SOCKET, SO_REUSEADDR).ok());
2060     ASSERT_FALSE(bind(s, reinterpret_cast<struct sockaddr*>(&tlsServer), sizeof(tlsServer)));
2061     ASSERT_FALSE(listen(s, 1));
2062 
2063     // Trigger TLS validation.
2064     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(ResolverParams::Builder().build()));
2065 
2066     struct sockaddr_storage cliaddr;
2067     socklen_t sin_size = sizeof(cliaddr);
2068     int new_fd = accept4(s, reinterpret_cast<struct sockaddr*>(&cliaddr), &sin_size, SOCK_CLOEXEC);
2069     ASSERT_TRUE(new_fd > 0);
2070 
2071     // We've received the new file descriptor but not written to it or closed, so the
2072     // validation is still pending.  Queries should still flow correctly because the
2073     // server is not used until validation succeeds.
2074     const hostent* result;
2075     result = gethostbyname("tlsbroken1");
2076     ASSERT_FALSE(result == nullptr);
2077     EXPECT_EQ("1.2.3.1", ToString(result));
2078 
2079     // Now we cause the validation to fail.
2080     std::string garbage = "definitely not a valid TLS ServerHello";
2081     write(new_fd, garbage.data(), garbage.size());
2082     close(new_fd);
2083 
2084     // Validation failure shouldn't interfere with lookups, because lookups won't be sent
2085     // to the TLS server unless validation succeeds.
2086     result = gethostbyname("tlsbroken2");
2087     ASSERT_FALSE(result == nullptr);
2088     EXPECT_EQ("1.2.3.2", ToString(result));
2089 
2090     // Clear TLS bit.
2091     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
2092     close(s);
2093 }
2094 
TEST_F(ResolverTest,GetHostByName_Tls)2095 TEST_F(ResolverTest, GetHostByName_Tls) {
2096     constexpr char listen_udp[] = "53";
2097     constexpr char listen_tls[] = "853";
2098     constexpr char host_name1[] = "tls1.example.com.";
2099     constexpr char host_name2[] = "tls2.example.com.";
2100     constexpr char host_name3[] = "tls3.example.com.";
2101     const std::vector<DnsRecord> records = {
2102             {host_name1, ns_type::ns_t_a, "1.2.3.1"},
2103             {host_name2, ns_type::ns_t_a, "1.2.3.2"},
2104             {host_name3, ns_type::ns_t_a, "1.2.3.3"},
2105     };
2106 
2107     test::DNSResponder dns;
2108     StartDns(dns, records);
2109 
2110     test::DnsTlsFrontend tls(kDefaultServer, listen_tls, kDefaultServer, listen_udp);
2111     ASSERT_TRUE(tls.startServer());
2112     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(ResolverParams::Builder().build()));
2113     EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
2114 
2115     const hostent* result = gethostbyname("tls1");
2116     ASSERT_FALSE(result == nullptr);
2117     EXPECT_EQ("1.2.3.1", ToString(result));
2118 
2119     // Wait for query to get counted.
2120     EXPECT_TRUE(tls.waitForQueries(2));
2121 
2122     // Stop the TLS server.  Since we're in opportunistic mode, queries will
2123     // fall back to the locally-assigned (clear text) nameservers.
2124     tls.stopServer();
2125 
2126     dns.clearQueries();
2127     result = gethostbyname("tls2");
2128     EXPECT_FALSE(result == nullptr);
2129     EXPECT_EQ("1.2.3.2", ToString(result));
2130     const auto queries = dns.queries();
2131     EXPECT_EQ(1U, queries.size());
2132     EXPECT_EQ("tls2.example.com.", queries[0].name);
2133     EXPECT_EQ(ns_t_a, queries[0].type);
2134 
2135     // Reset the resolvers without enabling TLS.  Queries should still be routed
2136     // to the UDP endpoint.
2137     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
2138 
2139     result = gethostbyname("tls3");
2140     ASSERT_FALSE(result == nullptr);
2141     EXPECT_EQ("1.2.3.3", ToString(result));
2142 }
2143 
TEST_F(ResolverTest,GetHostByName_TlsFailover)2144 TEST_F(ResolverTest, GetHostByName_TlsFailover) {
2145     constexpr char listen_addr1[] = "127.0.0.3";
2146     constexpr char listen_addr2[] = "127.0.0.4";
2147     constexpr char listen_udp[] = "53";
2148     constexpr char listen_tls[] = "853";
2149     constexpr char host_name1[] = "tlsfailover1.example.com.";
2150     constexpr char host_name2[] = "tlsfailover2.example.com.";
2151     const std::vector<DnsRecord> records1 = {
2152             {host_name1, ns_type::ns_t_a, "1.2.3.1"},
2153             {host_name2, ns_type::ns_t_a, "1.2.3.2"},
2154     };
2155     const std::vector<DnsRecord> records2 = {
2156             {host_name1, ns_type::ns_t_a, "1.2.3.3"},
2157             {host_name2, ns_type::ns_t_a, "1.2.3.4"},
2158     };
2159 
2160     test::DNSResponder dns1(listen_addr1);
2161     test::DNSResponder dns2(listen_addr2);
2162     StartDns(dns1, records1);
2163     StartDns(dns2, records2);
2164 
2165     std::vector<std::string> servers = {listen_addr1, listen_addr2};
2166 
2167     test::DnsTlsFrontend tls1(listen_addr1, listen_tls, listen_addr1, listen_udp);
2168     test::DnsTlsFrontend tls2(listen_addr2, listen_tls, listen_addr2, listen_udp);
2169     ASSERT_TRUE(tls1.startServer());
2170     ASSERT_TRUE(tls2.startServer());
2171     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(
2172             ResolverParams::Builder()
2173                     .setDnsServers(servers)
2174                     .setDotServers(servers)
2175                     .setPrivateDnsProvider(kDefaultPrivateDnsHostName)
2176                     .build()));
2177     EXPECT_TRUE(WaitForPrivateDnsValidation(tls1.listen_address(), true));
2178     EXPECT_TRUE(WaitForPrivateDnsValidation(tls2.listen_address(), true));
2179 
2180     const hostent* result = gethostbyname("tlsfailover1");
2181     ASSERT_FALSE(result == nullptr);
2182     EXPECT_EQ("1.2.3.1", ToString(result));
2183 
2184     // Wait for query to get counted.
2185     EXPECT_TRUE(tls1.waitForQueries(2));
2186     // No new queries should have reached tls2.
2187     EXPECT_TRUE(tls2.waitForQueries(1));
2188 
2189     // Stop tls1.  Subsequent queries should attempt to reach tls1, fail, and retry to tls2.
2190     tls1.stopServer();
2191 
2192     result = gethostbyname("tlsfailover2");
2193     EXPECT_EQ("1.2.3.4", ToString(result));
2194 
2195     // Wait for query to get counted.
2196     EXPECT_TRUE(tls2.waitForQueries(2));
2197 
2198     // No additional queries should have reached the insecure servers.
2199     EXPECT_EQ(2U, dns1.queries().size());
2200     EXPECT_EQ(2U, dns2.queries().size());
2201 
2202     // Clear TLS bit.
2203     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2204 }
2205 
TEST_F(ResolverTest,GetHostByName_BadTlsName)2206 TEST_F(ResolverTest, GetHostByName_BadTlsName) {
2207     constexpr char listen_udp[] = "53";
2208     constexpr char listen_tls[] = "853";
2209     constexpr char host_name[] = "badtlsname.example.com.";
2210 
2211     test::DNSResponder dns;
2212     StartDns(dns, {{host_name, ns_type::ns_t_a, "1.2.3.1"}});
2213 
2214     test::DnsTlsFrontend tls(kDefaultServer, listen_tls, kDefaultServer, listen_udp);
2215     ASSERT_TRUE(tls.startServer());
2216     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(
2217             ResolverParams::Builder()
2218                     .setPrivateDnsProvider(kDefaultIncorrectPrivateDnsHostName)
2219                     .build()));
2220 
2221     // The TLS handshake would fail because the name of TLS server doesn't
2222     // match with TLS server's certificate.
2223     EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), false));
2224 
2225     // The query should fail hard, because a name was specified.
2226     EXPECT_EQ(nullptr, gethostbyname("badtlsname"));
2227 
2228     // Clear TLS bit.
2229     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
2230 }
2231 
TEST_F(ResolverTest,GetAddrInfo_Tls)2232 TEST_F(ResolverTest, GetAddrInfo_Tls) {
2233     constexpr char listen_udp[] = "53";
2234     constexpr char listen_tls[] = "853";
2235     constexpr char host_name[] = "addrinfotls.example.com.";
2236     const std::vector<DnsRecord> records = {
2237             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2238             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2239     };
2240 
2241     test::DNSResponder dns;
2242     StartDns(dns, records);
2243 
2244     test::DnsTlsFrontend tls(kDefaultServer, listen_tls, kDefaultServer, listen_udp);
2245     ASSERT_TRUE(tls.startServer());
2246     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(
2247             ResolverParams::Builder().setPrivateDnsProvider(kDefaultPrivateDnsHostName).build()));
2248     EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
2249 
2250     dns.clearQueries();
2251     ScopedAddrinfo result = safe_getaddrinfo("addrinfotls", nullptr, nullptr);
2252     EXPECT_TRUE(result != nullptr);
2253     size_t found = GetNumQueries(dns, host_name);
2254     EXPECT_LE(1U, found);
2255     // Could be A or AAAA
2256     std::string result_str = ToString(result);
2257     EXPECT_TRUE(result_str == "1.2.3.4" || result_str == "::1.2.3.4")
2258             << ", result_str='" << result_str << "'";
2259     // Wait for both A and AAAA queries to get counted.
2260     EXPECT_TRUE(tls.waitForQueries(3));
2261 }
2262 
TEST_F(ResolverTest,TlsBypass)2263 TEST_F(ResolverTest, TlsBypass) {
2264     const char OFF[] = "off";
2265     const char OPPORTUNISTIC[] = "opportunistic";
2266     const char STRICT[] = "strict";
2267 
2268     const char GETHOSTBYNAME[] = "gethostbyname";
2269     const char GETADDRINFO[] = "getaddrinfo";
2270     const char GETADDRINFOFORNET[] = "getaddrinfofornet";
2271 
2272     const unsigned BYPASS_NETID = NETID_USE_LOCAL_NAMESERVERS | TEST_NETID;
2273 
2274     const char ADDR4[] = "192.0.2.1";
2275     const char ADDR6[] = "2001:db8::1";
2276 
2277     const char cleartext_addr[] = "127.0.0.53";
2278     const char cleartext_port[] = "53";
2279     const char tls_port[] = "853";
2280     const std::vector<std::string> servers = {cleartext_addr};
2281 
2282     test::DNSResponder dns(cleartext_addr);
2283     ASSERT_TRUE(dns.startServer());
2284 
2285     test::DnsTlsFrontend tls(cleartext_addr, tls_port, cleartext_addr, cleartext_port);
2286     ASSERT_TRUE(tls.startServer());
2287 
2288     // clang-format off
2289     struct TestConfig {
2290         const std::string mode;
2291         const bool withWorkingTLS;
2292         const std::string method;
2293 
2294         std::string asHostName() const {
2295             return fmt::format("{}.{}.{}.", mode, withWorkingTLS ? "tlsOn" : "tlsOff",
2296                                 method);
2297         }
2298     } testConfigs[]{
2299         {OFF,           true,  GETHOSTBYNAME},
2300         {OPPORTUNISTIC, true,  GETHOSTBYNAME},
2301         {STRICT,        true,  GETHOSTBYNAME},
2302         {OFF,           true,  GETADDRINFO},
2303         {OPPORTUNISTIC, true,  GETADDRINFO},
2304         {STRICT,        true,  GETADDRINFO},
2305         {OFF,           true,  GETADDRINFOFORNET},
2306         {OPPORTUNISTIC, true,  GETADDRINFOFORNET},
2307         {STRICT,        true,  GETADDRINFOFORNET},
2308         {OFF,           false, GETHOSTBYNAME},
2309         {OPPORTUNISTIC, false, GETHOSTBYNAME},
2310         {STRICT,        false, GETHOSTBYNAME},
2311         {OFF,           false, GETADDRINFO},
2312         {OPPORTUNISTIC, false, GETADDRINFO},
2313         {STRICT,        false, GETADDRINFO},
2314         {OFF,           false, GETADDRINFOFORNET},
2315         {OPPORTUNISTIC, false, GETADDRINFOFORNET},
2316         {STRICT,        false, GETADDRINFOFORNET},
2317     };
2318     // clang-format on
2319 
2320     for (const auto& config : testConfigs) {
2321         const std::string testHostName = config.asHostName();
2322         SCOPED_TRACE(testHostName);
2323 
2324         // Don't tempt test bugs due to caching.
2325         const char* host_name = testHostName.c_str();
2326         dns.addMapping(host_name, ns_type::ns_t_a, ADDR4);
2327         dns.addMapping(host_name, ns_type::ns_t_aaaa, ADDR6);
2328 
2329         if (config.withWorkingTLS) {
2330             if (!tls.running()) {
2331                 ASSERT_TRUE(tls.startServer());
2332             }
2333         } else {
2334             if (tls.running()) {
2335                 ASSERT_TRUE(tls.stopServer());
2336             }
2337         }
2338 
2339         if (config.mode == OFF) {
2340             ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2341         } else /* OPPORTUNISTIC or STRICT */ {
2342             auto builder = ResolverParams::Builder().setDnsServers(servers).setDotServers(servers);
2343             if (config.mode == STRICT) builder.setPrivateDnsProvider(kDefaultPrivateDnsHostName);
2344             ASSERT_TRUE(mDnsClient.SetResolversFromParcel(builder.build()));
2345 
2346             // Wait for the validation event. If the server is running, the validation should
2347             // succeed; otherwise, the validation should fail.
2348             EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), config.withWorkingTLS));
2349             if (config.withWorkingTLS) {
2350                 EXPECT_TRUE(tls.waitForQueries(1));
2351                 tls.clearQueries();
2352             }
2353         }
2354 
2355         const hostent* h_result = nullptr;
2356         ScopedAddrinfo ai_result;
2357 
2358         if (config.method == GETHOSTBYNAME) {
2359             ASSERT_EQ(0, setNetworkForResolv(BYPASS_NETID));
2360             h_result = gethostbyname(host_name);
2361 
2362             EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
2363             ASSERT_FALSE(h_result == nullptr);
2364             ASSERT_EQ(4, h_result->h_length);
2365             ASSERT_FALSE(h_result->h_addr_list[0] == nullptr);
2366             EXPECT_EQ(ADDR4, ToString(h_result));
2367             EXPECT_TRUE(h_result->h_addr_list[1] == nullptr);
2368         } else if (config.method == GETADDRINFO) {
2369             ASSERT_EQ(0, setNetworkForResolv(BYPASS_NETID));
2370             ai_result = safe_getaddrinfo(host_name, nullptr, nullptr);
2371             EXPECT_TRUE(ai_result != nullptr);
2372 
2373             EXPECT_LE(1U, GetNumQueries(dns, host_name));
2374             // Could be A or AAAA
2375             const std::string result_str = ToString(ai_result);
2376             EXPECT_TRUE(result_str == ADDR4 || result_str == ADDR6)
2377                     << ", result_str='" << result_str << "'";
2378         } else if (config.method == GETADDRINFOFORNET) {
2379             addrinfo* raw_ai_result = nullptr;
2380             EXPECT_EQ(0, android_getaddrinfofornet(host_name, /*servname=*/nullptr,
2381                                                    /*hints=*/nullptr, BYPASS_NETID, MARK_UNSET,
2382                                                    &raw_ai_result));
2383             ai_result.reset(raw_ai_result);
2384 
2385             EXPECT_LE(1U, GetNumQueries(dns, host_name));
2386             // Could be A or AAAA
2387             const std::string result_str = ToString(ai_result);
2388             EXPECT_TRUE(result_str == ADDR4 || result_str == ADDR6)
2389                     << ", result_str='" << result_str << "'";
2390         }
2391 
2392         EXPECT_EQ(0, tls.queries());
2393 
2394         // Clear per-process resolv netid.
2395         ASSERT_EQ(0, setNetworkForResolv(NETID_UNSET));
2396         dns.clearQueries();
2397     }
2398 }
2399 
TEST_F(ResolverTest,StrictMode_NoTlsServers)2400 TEST_F(ResolverTest, StrictMode_NoTlsServers) {
2401     constexpr char host_name[] = "strictmode.notlsips.example.com.";
2402     const std::vector<DnsRecord> records = {
2403             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2404             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2405     };
2406 
2407     test::DNSResponder dns(kDefaultServer);
2408     StartDns(dns, records);
2409     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(
2410             ResolverParams::Builder()
2411                     .setPrivateDnsProvider(kDefaultIncorrectPrivateDnsHostName)
2412                     .build()));
2413 
2414     addrinfo* ai_result = nullptr;
2415     EXPECT_NE(0, getaddrinfo(host_name, nullptr, nullptr, &ai_result));
2416     EXPECT_EQ(0U, GetNumQueries(dns, host_name));
2417 }
2418 
2419 namespace {
2420 
getAsyncResponse(int fd,int * rcode,uint8_t * buf,int bufLen)2421 int getAsyncResponse(int fd, int* rcode, uint8_t* buf, int bufLen) {
2422     struct pollfd wait_fd[1];
2423     wait_fd[0].fd = fd;
2424     wait_fd[0].events = POLLIN;
2425     short revents;
2426 
2427     if (int ret = poll(wait_fd, 1, -1); ret <= 0) {
2428         return -1;
2429     }
2430     revents = wait_fd[0].revents;
2431     if (revents & POLLIN) {
2432         return resNetworkResult(fd, rcode, buf, bufLen);
2433     }
2434     return -1;
2435 }
2436 
toString(uint8_t * buf,int bufLen,int ipType)2437 std::string toString(uint8_t* buf, int bufLen, int ipType) {
2438     ns_msg handle;
2439     ns_rr rr;
2440 
2441     if (ns_initparse((const uint8_t*)buf, bufLen, &handle) >= 0) {
2442         if (ns_parserr(&handle, ns_s_an, 0, &rr) == 0) {
2443             const uint8_t* rdata = ns_rr_rdata(rr);
2444             char buffer[INET6_ADDRSTRLEN];
2445             if (inet_ntop(ipType, (const char*)rdata, buffer, sizeof(buffer))) {
2446                 return buffer;
2447             }
2448         }
2449     }
2450     return "";
2451 }
2452 
dns_open_proxy()2453 int dns_open_proxy() {
2454     int s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
2455     if (s == -1) {
2456         return -1;
2457     }
2458     const int one = 1;
2459     setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
2460 
2461     static const struct sockaddr_un proxy_addr = {
2462             .sun_family = AF_UNIX,
2463             .sun_path = "/dev/socket/dnsproxyd",
2464     };
2465 
2466     if (TEMP_FAILURE_RETRY(connect(s, (const struct sockaddr*)&proxy_addr, sizeof(proxy_addr))) !=
2467         0) {
2468         close(s);
2469         return -1;
2470     }
2471 
2472     return s;
2473 }
2474 
expectAnswersValid(int fd,int ipType,const std::string & expectedAnswer)2475 void expectAnswersValid(int fd, int ipType, const std::string& expectedAnswer) {
2476     int rcode = -1;
2477     uint8_t buf[MAXPACKET] = {};
2478 
2479     int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2480     EXPECT_GT(res, 0);
2481     EXPECT_EQ(expectedAnswer, toString(buf, res, ipType));
2482 }
2483 
expectAnswersNotValid(int fd,int expectedErrno)2484 void expectAnswersNotValid(int fd, int expectedErrno) {
2485     int rcode = -1;
2486     uint8_t buf[MAXPACKET] = {};
2487 
2488     int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2489     EXPECT_EQ(expectedErrno, res);
2490 }
2491 
2492 }  // namespace
2493 
TEST_F(ResolverTest,Async_NormalQueryV4V6)2494 TEST_F(ResolverTest, Async_NormalQueryV4V6) {
2495     constexpr char listen_addr[] = "127.0.0.4";
2496     constexpr char host_name[] = "howdy.example.com.";
2497     const std::vector<DnsRecord> records = {
2498             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2499             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2500     };
2501 
2502     test::DNSResponder dns(listen_addr);
2503     StartDns(dns, records);
2504     std::vector<std::string> servers = {listen_addr};
2505     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2506 
2507     int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2508     int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2509     EXPECT_TRUE(fd1 != -1);
2510     EXPECT_TRUE(fd2 != -1);
2511 
2512     uint8_t buf[MAXPACKET] = {};
2513     int rcode;
2514     int res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
2515     EXPECT_GT(res, 0);
2516     EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
2517 
2518     res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
2519     EXPECT_GT(res, 0);
2520     EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2521 
2522     EXPECT_EQ(2U, GetNumQueries(dns, host_name));
2523 
2524     // Re-query verify cache works
2525     fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2526     fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2527 
2528     EXPECT_TRUE(fd1 != -1);
2529     EXPECT_TRUE(fd2 != -1);
2530 
2531     res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
2532     EXPECT_GT(res, 0);
2533     EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
2534 
2535     res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
2536     EXPECT_GT(res, 0);
2537     EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2538 
2539     EXPECT_EQ(2U, GetNumQueries(dns, host_name));
2540 }
2541 
TEST_F(ResolverTest,Async_BadQuery)2542 TEST_F(ResolverTest, Async_BadQuery) {
2543     constexpr char listen_addr[] = "127.0.0.4";
2544     constexpr char host_name[] = "howdy.example.com.";
2545     const std::vector<DnsRecord> records = {
2546             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2547             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2548     };
2549 
2550     test::DNSResponder dns(listen_addr);
2551     StartDns(dns, records);
2552     std::vector<std::string> servers = {listen_addr};
2553     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2554 
2555     static struct {
2556         int fd;
2557         const char* dname;
2558         const int queryType;
2559         const int expectRcode;
2560     } kTestData[] = {
2561             {-1, "", ns_t_aaaa, 0},
2562             {-1, "as65ass46", ns_t_aaaa, 0},
2563             {-1, "454564564564", ns_t_aaaa, 0},
2564             {-1, "h645235", ns_t_a, 0},
2565             {-1, "www.google.com", ns_t_a, 0},
2566     };
2567 
2568     for (auto& td : kTestData) {
2569         SCOPED_TRACE(td.dname);
2570         td.fd = resNetworkQuery(TEST_NETID, td.dname, ns_c_in, td.queryType, 0);
2571         EXPECT_TRUE(td.fd != -1);
2572     }
2573 
2574     // dns_responder return empty resp(packet only contains query part) with no error currently
2575     for (const auto& td : kTestData) {
2576         uint8_t buf[MAXPACKET] = {};
2577         int rcode;
2578         SCOPED_TRACE(td.dname);
2579         int res = getAsyncResponse(td.fd, &rcode, buf, MAXPACKET);
2580         EXPECT_GT(res, 0);
2581         EXPECT_EQ(rcode, td.expectRcode);
2582     }
2583 }
2584 
TEST_F(ResolverTest,Async_EmptyAnswer)2585 TEST_F(ResolverTest, Async_EmptyAnswer) {
2586     constexpr char listen_addr[] = "127.0.0.4";
2587     constexpr char host_name[] = "howdy.example.com.";
2588     const std::vector<DnsRecord> records = {
2589             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2590             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2591     };
2592 
2593     test::DNSResponder dns(listen_addr);
2594     StartDns(dns, records);
2595     std::vector<std::string> servers = {listen_addr};
2596     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2597 
2598     // TODO: Disable retry to make this test explicit.
2599     auto& cv = dns.getCv();
2600     auto& cvMutex = dns.getCvMutex();
2601     int fd1;
2602     // Wait on the condition variable to ensure that the DNS server has handled our first query.
2603     {
2604         std::unique_lock lk(cvMutex);
2605         fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2606         EXPECT_TRUE(fd1 != -1);
2607         EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lk, std::chrono::seconds(1)));
2608     }
2609 
2610     ExpectDnsEvent(INetdEventListener::EVENT_RES_NSEND, 0, "howdy.example.com", {"::1.2.3.4"});
2611     dns.setResponseProbability(0.0);
2612 
2613     int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2614     EXPECT_TRUE(fd2 != -1);
2615     ExpectDnsEvent(INetdEventListener::EVENT_RES_NSEND, RCODE_TIMEOUT, "howdy.example.com", {});
2616 
2617     int fd3 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2618     EXPECT_TRUE(fd3 != -1);
2619     ExpectDnsEvent(INetdEventListener::EVENT_RES_NSEND, RCODE_TIMEOUT, "howdy.example.com", {});
2620 
2621     uint8_t buf[MAXPACKET] = {};
2622     int rcode;
2623 
2624     // expect no response
2625     int res = getAsyncResponse(fd3, &rcode, buf, MAXPACKET);
2626     EXPECT_EQ(-ETIMEDOUT, res);
2627 
2628     // expect no response
2629     memset(buf, 0, MAXPACKET);
2630     res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
2631     EXPECT_EQ(-ETIMEDOUT, res);
2632 
2633     dns.setResponseProbability(1.0);
2634 
2635     int fd4 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2636     EXPECT_TRUE(fd4 != -1);
2637     ExpectDnsEvent(INetdEventListener::EVENT_RES_NSEND, 0, "howdy.example.com", {"1.2.3.4"});
2638 
2639     memset(buf, 0, MAXPACKET);
2640     res = getAsyncResponse(fd4, &rcode, buf, MAXPACKET);
2641     EXPECT_GT(res, 0);
2642     EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2643 
2644     memset(buf, 0, MAXPACKET);
2645     res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
2646     EXPECT_GT(res, 0);
2647     EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
2648 }
2649 
TEST_F(ResolverTest,Async_MalformedQuery)2650 TEST_F(ResolverTest, Async_MalformedQuery) {
2651     constexpr char listen_addr[] = "127.0.0.4";
2652     constexpr char host_name[] = "howdy.example.com.";
2653     const std::vector<DnsRecord> records = {
2654             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2655             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2656     };
2657 
2658     test::DNSResponder dns(listen_addr);
2659     StartDns(dns, records);
2660     std::vector<std::string> servers = {listen_addr};
2661     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2662 
2663     int fd = dns_open_proxy();
2664     EXPECT_TRUE(fd > 0);
2665 
2666     const std::string badMsg = "16-52512#";
2667     static const struct {
2668         const std::string cmd;
2669         const int expectErr;
2670     } kTestData[] = {
2671             // Too few arguments
2672             {"resnsend " + badMsg + '\0', -EINVAL},
2673             // Bad netId
2674             {"resnsend badnetId 0 " + badMsg + '\0', -EINVAL},
2675             // Bad raw data
2676             {"resnsend " + std::to_string(TEST_NETID) + " 0 " + badMsg + '\0', -EILSEQ},
2677     };
2678 
2679     for (unsigned int i = 0; i < std::size(kTestData); i++) {
2680         auto& td = kTestData[i];
2681         SCOPED_TRACE(td.cmd);
2682         ssize_t rc = TEMP_FAILURE_RETRY(write(fd, td.cmd.c_str(), td.cmd.size()));
2683         EXPECT_EQ(rc, static_cast<ssize_t>(td.cmd.size()));
2684 
2685         int32_t tmp;
2686         rc = TEMP_FAILURE_RETRY(read(fd, &tmp, sizeof(tmp)));
2687         EXPECT_TRUE(rc > 0);
2688         EXPECT_EQ(static_cast<int>(ntohl(tmp)), td.expectErr);
2689     }
2690     // Normal query with answer buffer
2691     // This is raw data of query "howdy.example.com" type 1 class 1
2692     std::string query = "81sBAAABAAAAAAAABWhvd2R5B2V4YW1wbGUDY29tAAABAAE=";
2693     std::string cmd = "resnsend " + std::to_string(TEST_NETID) + " 0 " + query + '\0';
2694     ssize_t rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
2695     EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
2696 
2697     uint8_t smallBuf[1] = {};
2698     int rcode;
2699     rc = getAsyncResponse(fd, &rcode, smallBuf, 1);
2700     EXPECT_EQ(-EMSGSIZE, rc);
2701 
2702     // Do the normal test with large buffer again
2703     fd = dns_open_proxy();
2704     EXPECT_TRUE(fd > 0);
2705     rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
2706     EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
2707     uint8_t buf[MAXPACKET] = {};
2708     rc = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2709     EXPECT_EQ("1.2.3.4", toString(buf, rc, AF_INET));
2710 }
2711 
TEST_F(ResolverTest,Async_CacheFlags)2712 TEST_F(ResolverTest, Async_CacheFlags) {
2713     constexpr char listen_addr[] = "127.0.0.4";
2714     constexpr char host_name1[] = "howdy.example.com.";
2715     constexpr char host_name2[] = "howdy.example2.com.";
2716     constexpr char host_name3[] = "howdy.example3.com.";
2717     const std::vector<DnsRecord> records = {
2718             {host_name1, ns_type::ns_t_a, "1.2.3.4"}, {host_name1, ns_type::ns_t_aaaa, "::1.2.3.4"},
2719             {host_name2, ns_type::ns_t_a, "1.2.3.5"}, {host_name2, ns_type::ns_t_aaaa, "::1.2.3.5"},
2720             {host_name3, ns_type::ns_t_a, "1.2.3.6"}, {host_name3, ns_type::ns_t_aaaa, "::1.2.3.6"},
2721     };
2722 
2723     test::DNSResponder dns(listen_addr);
2724     StartDns(dns, records);
2725     std::vector<std::string> servers = {listen_addr};
2726     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2727 
2728     // ANDROID_RESOLV_NO_CACHE_STORE
2729     int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2730                               ANDROID_RESOLV_NO_CACHE_STORE);
2731     EXPECT_TRUE(fd1 != -1);
2732     int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2733                               ANDROID_RESOLV_NO_CACHE_STORE);
2734     EXPECT_TRUE(fd2 != -1);
2735     int fd3 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2736                               ANDROID_RESOLV_NO_CACHE_STORE);
2737     EXPECT_TRUE(fd3 != -1);
2738 
2739     expectAnswersValid(fd3, AF_INET, "1.2.3.4");
2740     expectAnswersValid(fd2, AF_INET, "1.2.3.4");
2741     expectAnswersValid(fd1, AF_INET, "1.2.3.4");
2742 
2743     // No cache exists, expect 3 queries
2744     EXPECT_EQ(3U, GetNumQueries(dns, host_name1));
2745 
2746     // Raise a query with no flags to ensure no cache exists. Also make an cache entry for the
2747     // query.
2748     fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2749 
2750     EXPECT_TRUE(fd1 != -1);
2751 
2752     expectAnswersValid(fd1, AF_INET, "1.2.3.4");
2753 
2754     // Expect 4 queries because there should be no cache before this query.
2755     EXPECT_EQ(4U, GetNumQueries(dns, host_name1));
2756 
2757     // Now we have the cache entry, re-query with ANDROID_RESOLV_NO_CACHE_STORE to ensure
2758     // that ANDROID_RESOLV_NO_CACHE_STORE implied ANDROID_RESOLV_NO_CACHE_LOOKUP.
2759     fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2760                           ANDROID_RESOLV_NO_CACHE_STORE);
2761     EXPECT_TRUE(fd1 != -1);
2762     expectAnswersValid(fd1, AF_INET, "1.2.3.4");
2763     // Expect 5 queries because we shouldn't do cache lookup for the query which has
2764     // ANDROID_RESOLV_NO_CACHE_STORE.
2765     EXPECT_EQ(5U, GetNumQueries(dns, host_name1));
2766 
2767     // ANDROID_RESOLV_NO_CACHE_LOOKUP
2768     fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2769                           ANDROID_RESOLV_NO_CACHE_LOOKUP);
2770     fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2771                           ANDROID_RESOLV_NO_CACHE_LOOKUP);
2772 
2773     EXPECT_TRUE(fd1 != -1);
2774     EXPECT_TRUE(fd2 != -1);
2775 
2776     expectAnswersValid(fd2, AF_INET, "1.2.3.4");
2777     expectAnswersValid(fd1, AF_INET, "1.2.3.4");
2778 
2779     // Cache was skipped, expect 2 more queries.
2780     EXPECT_EQ(7U, GetNumQueries(dns, host_name1));
2781 
2782     // Re-query verify cache works
2783     fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2784     EXPECT_TRUE(fd1 != -1);
2785     expectAnswersValid(fd1, AF_INET, "1.2.3.4");
2786 
2787     // Cache hits,  expect still 7 queries
2788     EXPECT_EQ(7U, GetNumQueries(dns, host_name1));
2789 
2790     // Start to verify if ANDROID_RESOLV_NO_CACHE_LOOKUP does write response into cache
2791     dns.clearQueries();
2792 
2793     fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa,
2794                           ANDROID_RESOLV_NO_CACHE_LOOKUP);
2795     fd2 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa,
2796                           ANDROID_RESOLV_NO_CACHE_LOOKUP);
2797 
2798     EXPECT_TRUE(fd1 != -1);
2799     EXPECT_TRUE(fd2 != -1);
2800 
2801     expectAnswersValid(fd2, AF_INET6, "::1.2.3.5");
2802     expectAnswersValid(fd1, AF_INET6, "::1.2.3.5");
2803 
2804     // Skip cache, expect 2 queries
2805     EXPECT_EQ(2U, GetNumQueries(dns, host_name2));
2806 
2807     // Re-query without flags
2808     fd1 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa, 0);
2809     fd2 = resNetworkQuery(TEST_NETID, "howdy.example2.com", ns_c_in, ns_t_aaaa, 0);
2810 
2811     EXPECT_TRUE(fd1 != -1);
2812     EXPECT_TRUE(fd2 != -1);
2813 
2814     expectAnswersValid(fd2, AF_INET6, "::1.2.3.5");
2815     expectAnswersValid(fd1, AF_INET6, "::1.2.3.5");
2816 
2817     // Cache hits, expect still 2 queries
2818     EXPECT_EQ(2U, GetNumQueries(dns, host_name2));
2819 
2820     // Test both ANDROID_RESOLV_NO_CACHE_STORE and ANDROID_RESOLV_NO_CACHE_LOOKUP are set
2821     dns.clearQueries();
2822 
2823     // Make sure that the cache of "howdy.example3.com" exists.
2824     fd1 = resNetworkQuery(TEST_NETID, "howdy.example3.com", ns_c_in, ns_t_aaaa, 0);
2825     EXPECT_TRUE(fd1 != -1);
2826     expectAnswersValid(fd1, AF_INET6, "::1.2.3.6");
2827     EXPECT_EQ(1U, GetNumQueries(dns, host_name3));
2828 
2829     // Re-query with testFlags
2830     const int testFlag = ANDROID_RESOLV_NO_CACHE_STORE | ANDROID_RESOLV_NO_CACHE_LOOKUP;
2831     fd1 = resNetworkQuery(TEST_NETID, "howdy.example3.com", ns_c_in, ns_t_aaaa, testFlag);
2832     EXPECT_TRUE(fd1 != -1);
2833     expectAnswersValid(fd1, AF_INET6, "::1.2.3.6");
2834     // Expect cache lookup is skipped.
2835     EXPECT_EQ(2U, GetNumQueries(dns, host_name3));
2836 
2837     // Do another query with testFlags
2838     fd1 = resNetworkQuery(TEST_NETID, "howdy.example3.com", ns_c_in, ns_t_a, testFlag);
2839     EXPECT_TRUE(fd1 != -1);
2840     expectAnswersValid(fd1, AF_INET, "1.2.3.6");
2841     // Expect cache lookup is skipped.
2842     EXPECT_EQ(3U, GetNumQueries(dns, host_name3));
2843 
2844     // Re-query with no flags
2845     fd1 = resNetworkQuery(TEST_NETID, "howdy.example3.com", ns_c_in, ns_t_a, 0);
2846     EXPECT_TRUE(fd1 != -1);
2847     expectAnswersValid(fd1, AF_INET, "1.2.3.6");
2848     // Expect no cache hit because cache storing is also skipped in previous query.
2849     EXPECT_EQ(4U, GetNumQueries(dns, host_name3));
2850 }
2851 
TEST_F(ResolverTest,Async_NoCacheStoreFlagDoesNotRefreshStaleCacheEntry)2852 TEST_F(ResolverTest, Async_NoCacheStoreFlagDoesNotRefreshStaleCacheEntry) {
2853     constexpr char listen_addr[] = "127.0.0.4";
2854     constexpr char host_name[] = "howdy.example.com.";
2855     const std::vector<DnsRecord> records = {
2856             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2857     };
2858 
2859     test::DNSResponder dns(listen_addr);
2860     StartDns(dns, records);
2861     std::vector<std::string> servers = {listen_addr};
2862     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2863 
2864     const unsigned SHORT_TTL_SEC = 1;
2865     dns.setTtl(SHORT_TTL_SEC);
2866 
2867     // Refer to b/148842821 for the purpose of below test steps.
2868     // Basically, this test is used to ensure stale cache case is handled
2869     // correctly with ANDROID_RESOLV_NO_CACHE_STORE.
2870     int fd = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2871     EXPECT_TRUE(fd != -1);
2872     expectAnswersValid(fd, AF_INET, "1.2.3.4");
2873 
2874     EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2875     dns.clearQueries();
2876 
2877     // Wait until cache expired
2878     sleep(SHORT_TTL_SEC + 0.5);
2879 
2880     // Now request the same hostname again.
2881     // We should see a new DNS query because the entry in cache has become stale.
2882     // Due to ANDROID_RESOLV_NO_CACHE_STORE, this query must *not* refresh that stale entry.
2883     fd = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2884                          ANDROID_RESOLV_NO_CACHE_STORE);
2885     EXPECT_TRUE(fd != -1);
2886     expectAnswersValid(fd, AF_INET, "1.2.3.4");
2887     EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2888     dns.clearQueries();
2889 
2890     // If the cache is still stale, we expect to see one more DNS query
2891     // (this time the cache will be refreshed, but we're not checking for it).
2892     fd = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2893     EXPECT_TRUE(fd != -1);
2894     expectAnswersValid(fd, AF_INET, "1.2.3.4");
2895     EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2896 }
2897 
TEST_F(ResolverTest,Async_NoRetryFlag)2898 TEST_F(ResolverTest, Async_NoRetryFlag) {
2899     constexpr char listen_addr0[] = "127.0.0.4";
2900     constexpr char listen_addr1[] = "127.0.0.6";
2901     constexpr char host_name[] = "howdy.example.com.";
2902     const std::vector<DnsRecord> records = {
2903             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2904             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2905     };
2906 
2907     test::DNSResponder dns0(listen_addr0);
2908     test::DNSResponder dns1(listen_addr1);
2909     StartDns(dns0, records);
2910     StartDns(dns1, records);
2911     ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr0, listen_addr1}));
2912 
2913     dns0.clearQueries();
2914     dns1.clearQueries();
2915 
2916     dns0.setResponseProbability(0.0);
2917     dns1.setResponseProbability(0.0);
2918 
2919     int fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a,
2920                               ANDROID_RESOLV_NO_RETRY);
2921     EXPECT_TRUE(fd1 != -1);
2922 
2923     int fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa,
2924                               ANDROID_RESOLV_NO_RETRY);
2925     EXPECT_TRUE(fd2 != -1);
2926 
2927     // expect no response
2928     expectAnswersNotValid(fd1, -ETIMEDOUT);
2929     expectAnswersNotValid(fd2, -ETIMEDOUT);
2930     ExpectDnsEvent(INetdEventListener::EVENT_RES_NSEND, RCODE_TIMEOUT, "howdy.example.com", {});
2931     ExpectDnsEvent(INetdEventListener::EVENT_RES_NSEND, RCODE_TIMEOUT, "howdy.example.com", {});
2932 
2933     // No retry case, expect total 2 queries. The server is selected randomly.
2934     EXPECT_EQ(2U, GetNumQueries(dns0, host_name) + GetNumQueries(dns1, host_name));
2935 
2936     dns0.clearQueries();
2937     dns1.clearQueries();
2938 
2939     fd1 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_a, 0);
2940     EXPECT_TRUE(fd1 != -1);
2941 
2942     fd2 = resNetworkQuery(TEST_NETID, "howdy.example.com", ns_c_in, ns_t_aaaa, 0);
2943     EXPECT_TRUE(fd2 != -1);
2944 
2945     // expect no response
2946     expectAnswersNotValid(fd1, -ETIMEDOUT);
2947     expectAnswersNotValid(fd2, -ETIMEDOUT);
2948     ExpectDnsEvent(INetdEventListener::EVENT_RES_NSEND, RCODE_TIMEOUT, "howdy.example.com", {});
2949     ExpectDnsEvent(INetdEventListener::EVENT_RES_NSEND, RCODE_TIMEOUT, "howdy.example.com", {});
2950 
2951     // Retry case, expect 4 queries
2952     EXPECT_EQ(4U, GetNumQueries(dns0, host_name));
2953     EXPECT_EQ(4U, GetNumQueries(dns1, host_name));
2954 }
2955 
TEST_F(ResolverTest,Async_VerifyQueryID)2956 TEST_F(ResolverTest, Async_VerifyQueryID) {
2957     constexpr char listen_addr[] = "127.0.0.4";
2958     constexpr char host_name[] = "howdy.example.com.";
2959     const std::vector<DnsRecord> records = {
2960             {host_name, ns_type::ns_t_a, "1.2.3.4"},
2961             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
2962     };
2963 
2964     test::DNSResponder dns(listen_addr);
2965     StartDns(dns, records);
2966     std::vector<std::string> servers = {listen_addr};
2967     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
2968 
2969     const uint8_t queryBuf1[] = {
2970             /* Header */
2971             0x55, 0x66, /* Transaction ID */
2972             0x01, 0x00, /* Flags */
2973             0x00, 0x01, /* Questions */
2974             0x00, 0x00, /* Answer RRs */
2975             0x00, 0x00, /* Authority RRs */
2976             0x00, 0x00, /* Additional RRs */
2977             /* Queries */
2978             0x05, 0x68, 0x6f, 0x77, 0x64, 0x79, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
2979             0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */
2980             0x00, 0x01,                   /* Type */
2981             0x00, 0x01                    /* Class */
2982     };
2983 
2984     int fd = resNetworkSend(TEST_NETID, queryBuf1, sizeof(queryBuf1), 0);
2985     EXPECT_TRUE(fd != -1);
2986 
2987     uint8_t buf[MAXPACKET] = {};
2988     int rcode;
2989 
2990     int res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
2991     EXPECT_GT(res, 0);
2992     EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
2993 
2994     auto hp = reinterpret_cast<HEADER*>(buf);
2995     EXPECT_EQ(21862U, htons(hp->id));
2996 
2997     EXPECT_EQ(1U, GetNumQueries(dns, host_name));
2998 
2999     const uint8_t queryBuf2[] = {
3000             /* Header */
3001             0x00, 0x53, /* Transaction ID */
3002             0x01, 0x00, /* Flags */
3003             0x00, 0x01, /* Questions */
3004             0x00, 0x00, /* Answer RRs */
3005             0x00, 0x00, /* Authority RRs */
3006             0x00, 0x00, /* Additional RRs */
3007             /* Queries */
3008             0x05, 0x68, 0x6f, 0x77, 0x64, 0x79, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
3009             0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */
3010             0x00, 0x01,                   /* Type */
3011             0x00, 0x01                    /* Class */
3012     };
3013 
3014     // Re-query verify cache works and query id is correct
3015     fd = resNetworkSend(TEST_NETID, queryBuf2, sizeof(queryBuf2), 0);
3016 
3017     EXPECT_TRUE(fd != -1);
3018 
3019     res = getAsyncResponse(fd, &rcode, buf, MAXPACKET);
3020     EXPECT_GT(res, 0);
3021     EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
3022 
3023     EXPECT_EQ(0x0053U, htons(hp->id));
3024 
3025     EXPECT_EQ(1U, GetNumQueries(dns, host_name));
3026 }
3027 
3028 // This test checks that the resolver should not generate the request containing OPT RR when using
3029 // cleartext DNS. If we query the DNS server not supporting EDNS0 and it reponds with
3030 // FORMERR_ON_EDNS, we will fallback to no EDNS0 and try again. If the server does no response, we
3031 // won't retry so that we get no answer.
TEST_F(ResolverTest,BrokenEdns)3032 TEST_F(ResolverTest, BrokenEdns) {
3033     typedef test::DNSResponder::Edns Edns;
3034     enum ExpectResult { EXPECT_FAILURE, EXPECT_SUCCESS };
3035 
3036     // Perform cleartext query in off mode.
3037     const char OFF[] = "off";
3038 
3039     // Perform cleartext query when there's no private DNS server validated in opportunistic mode.
3040     const char OPPORTUNISTIC_UDP[] = "opportunistic_udp";
3041 
3042     // Perform cleartext query when there is a private DNS server validated in opportunistic mode.
3043     const char OPPORTUNISTIC_FALLBACK_UDP[] = "opportunistic_fallback_udp";
3044 
3045     // Perform cyphertext query in opportunistic mode.
3046     const char OPPORTUNISTIC_TLS[] = "opportunistic_tls";
3047 
3048     // Perform cyphertext query in strict mode.
3049     const char STRICT[] = "strict";
3050 
3051     const char GETHOSTBYNAME[] = "gethostbyname";
3052     const char GETADDRINFO[] = "getaddrinfo";
3053     const char ADDR4[] = "192.0.2.1";
3054     test::DNSResponder dns(kDefaultServer, "53", ns_rcode::ns_r_servfail);
3055     test::DnsTlsFrontend tls(kDefaultServer, "853", kDefaultServer, "53");
3056     ASSERT_TRUE(dns.startServer());
3057 
3058     // clang-format off
3059     static const struct TestConfig {
3060         std::string mode;
3061         std::string method;
3062         Edns edns;
3063         ExpectResult expectResult;
3064 
3065         std::string asHostName() const {
3066             const char* ednsString;
3067             switch (edns) {
3068                 case Edns::ON:
3069                     ednsString = "ednsOn";
3070                     break;
3071                 case Edns::FORMERR_ON_EDNS:
3072                     ednsString = "ednsFormerr";
3073                     break;
3074                 case Edns::DROP:
3075                     ednsString = "ednsDrop";
3076                     break;
3077                 default:
3078                     ednsString = "";
3079                     break;
3080             }
3081             return fmt::format("{}.{}.{}.", mode, method, ednsString);
3082         }
3083     } testConfigs[] = {
3084             // In OPPORTUNISTIC_TLS, if the DNS server doesn't support EDNS0 but TLS, the lookup
3085             // fails. Could such server exist? if so, we might need to fix it to fallback to
3086             // cleartext query. If the server still make no response for the queries with EDNS0, we
3087             // might also need to fix it to retry without EDNS0.
3088             // Another thing is that {OPPORTUNISTIC_TLS, Edns::DROP} and {STRICT, Edns::DROP} are
3089             // commented out since TLS timeout is not configurable.
3090             // TODO: Uncomment them after TLS timeout is configurable.
3091             {OFF,                        GETHOSTBYNAME, Edns::ON,      EXPECT_SUCCESS},
3092             {OPPORTUNISTIC_UDP,          GETHOSTBYNAME, Edns::ON,      EXPECT_SUCCESS},
3093             {OPPORTUNISTIC_FALLBACK_UDP, GETHOSTBYNAME, Edns::ON,      EXPECT_SUCCESS},
3094             {OPPORTUNISTIC_TLS,          GETHOSTBYNAME, Edns::ON,      EXPECT_SUCCESS},
3095             {STRICT,                     GETHOSTBYNAME, Edns::ON,      EXPECT_SUCCESS},
3096             {OFF,                        GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
3097             {OPPORTUNISTIC_UDP,          GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
3098             {OPPORTUNISTIC_FALLBACK_UDP, GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
3099             {OPPORTUNISTIC_TLS,          GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
3100             {STRICT,                     GETHOSTBYNAME, Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
3101             {OFF,                        GETHOSTBYNAME, Edns::DROP,    EXPECT_SUCCESS},
3102             {OPPORTUNISTIC_UDP,          GETHOSTBYNAME, Edns::DROP,    EXPECT_SUCCESS},
3103 
3104             // The failure is due to no retry on timeout. Maybe fix it?
3105             {OPPORTUNISTIC_FALLBACK_UDP, GETHOSTBYNAME, Edns::DROP,    EXPECT_FAILURE},
3106 
3107             //{OPPORTUNISTIC_TLS,        GETHOSTBYNAME, Edns::DROP,    EXPECT_FAILURE},
3108             //{STRICT,                   GETHOSTBYNAME, Edns::DROP,    EXPECT_FAILURE},
3109             {OFF,                        GETADDRINFO,   Edns::ON,      EXPECT_SUCCESS},
3110             {OPPORTUNISTIC_UDP,          GETADDRINFO,   Edns::ON,      EXPECT_SUCCESS},
3111             {OPPORTUNISTIC_FALLBACK_UDP, GETADDRINFO,   Edns::ON,      EXPECT_SUCCESS},
3112             {OPPORTUNISTIC_TLS,          GETADDRINFO,   Edns::ON,      EXPECT_SUCCESS},
3113             {STRICT,                     GETADDRINFO,   Edns::ON,      EXPECT_SUCCESS},
3114             {OFF,                        GETADDRINFO,   Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
3115             {OPPORTUNISTIC_UDP,          GETADDRINFO,   Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
3116             {OPPORTUNISTIC_FALLBACK_UDP, GETADDRINFO,   Edns::FORMERR_ON_EDNS, EXPECT_SUCCESS},
3117             {OPPORTUNISTIC_TLS,          GETADDRINFO,   Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
3118             {STRICT,                     GETADDRINFO,   Edns::FORMERR_ON_EDNS, EXPECT_FAILURE},
3119             {OFF,                        GETADDRINFO,   Edns::DROP,    EXPECT_SUCCESS},
3120             {OPPORTUNISTIC_UDP,          GETADDRINFO,   Edns::DROP,    EXPECT_SUCCESS},
3121 
3122             // The failure is due to no retry on timeout. Maybe fix it?
3123             {OPPORTUNISTIC_FALLBACK_UDP, GETADDRINFO,   Edns::DROP,    EXPECT_FAILURE},
3124 
3125             //{OPPORTUNISTIC_TLS, GETADDRINFO,   Edns::DROP,   EXPECT_FAILURE},
3126             //{STRICT,            GETADDRINFO,   Edns::DROP,   EXPECT_FAILURE},
3127     };
3128     // clang-format on
3129 
3130     for (const auto& config : testConfigs) {
3131         const std::string testHostName = config.asHostName();
3132         SCOPED_TRACE(testHostName);
3133 
3134         // Don't skip unusable DoT servers and disable revalidation for this test.
3135         ScopedSystemProperties sp1(kDotXportUnusableThresholdFlag, "-1");
3136         ScopedSystemProperties sp2(kDotRevalidationThresholdFlag, "-1");
3137         resetNetwork();
3138 
3139         const char* host_name = testHostName.c_str();
3140         dns.addMapping(host_name, ns_type::ns_t_a, ADDR4);
3141         dns.setEdns(config.edns);
3142 
3143         if (config.mode == OFF) {
3144             if (tls.running()) {
3145                 ASSERT_TRUE(tls.stopServer());
3146             }
3147             ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
3148         } else if (config.mode == OPPORTUNISTIC_UDP) {
3149             if (tls.running()) {
3150                 ASSERT_TRUE(tls.stopServer());
3151             }
3152             ASSERT_TRUE(mDnsClient.SetResolversFromParcel(ResolverParams::Builder().build()));
3153             EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), false));
3154         } else if (config.mode == OPPORTUNISTIC_TLS || config.mode == OPPORTUNISTIC_FALLBACK_UDP) {
3155             if (!tls.running()) {
3156                 ASSERT_TRUE(tls.startServer());
3157             }
3158             ASSERT_TRUE(mDnsClient.SetResolversFromParcel(ResolverParams::Builder().build()));
3159             EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
3160 
3161             if (config.mode == OPPORTUNISTIC_FALLBACK_UDP) {
3162                 // Force the resolver to fallback to cleartext queries.
3163                 ASSERT_TRUE(tls.stopServer());
3164             }
3165         } else if (config.mode == STRICT) {
3166             if (!tls.running()) {
3167                 ASSERT_TRUE(tls.startServer());
3168             }
3169             ASSERT_TRUE(mDnsClient.SetResolversFromParcel(
3170                     ResolverParams::Builder()
3171                             .setPrivateDnsProvider(kDefaultPrivateDnsHostName)
3172                             .build()));
3173             EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
3174         }
3175 
3176         if (config.method == GETHOSTBYNAME) {
3177             const hostent* h_result = gethostbyname(host_name);
3178             if (config.expectResult == EXPECT_SUCCESS) {
3179                 EXPECT_LE(1U, GetNumQueries(dns, host_name));
3180                 ASSERT_TRUE(h_result != nullptr);
3181                 ASSERT_EQ(4, h_result->h_length);
3182                 ASSERT_FALSE(h_result->h_addr_list[0] == nullptr);
3183                 EXPECT_EQ(ADDR4, ToString(h_result));
3184                 EXPECT_TRUE(h_result->h_addr_list[1] == nullptr);
3185                 ExpectDnsEvent(INetdEventListener::EVENT_GETHOSTBYNAME, 0, host_name, {ADDR4});
3186             } else {
3187                 EXPECT_EQ(0U, GetNumQueriesForType(dns, ns_type::ns_t_a, host_name));
3188                 ASSERT_TRUE(h_result == nullptr);
3189                 ASSERT_EQ(HOST_NOT_FOUND, h_errno);
3190                 int returnCode = (config.edns == Edns::DROP) ? RCODE_TIMEOUT : EAI_FAIL;
3191                 ExpectDnsEvent(INetdEventListener::EVENT_GETHOSTBYNAME, returnCode, host_name, {});
3192             }
3193         } else if (config.method == GETADDRINFO) {
3194             ScopedAddrinfo ai_result;
3195             addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
3196             ai_result = safe_getaddrinfo(host_name, nullptr, &hints);
3197             if (config.expectResult == EXPECT_SUCCESS) {
3198                 EXPECT_TRUE(ai_result != nullptr);
3199                 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
3200                 const std::string result_str = ToString(ai_result);
3201                 EXPECT_EQ(ADDR4, result_str);
3202                 ExpectDnsEvent(INetdEventListener::EVENT_GETADDRINFO, 0, host_name, {ADDR4});
3203             } else {
3204                 EXPECT_TRUE(ai_result == nullptr);
3205                 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
3206                 int returnCode = (config.edns == Edns::DROP) ? RCODE_TIMEOUT : EAI_FAIL;
3207                 ExpectDnsEvent(INetdEventListener::EVENT_GETADDRINFO, returnCode, host_name, {});
3208             }
3209         } else {
3210             FAIL() << "Unsupported query method: " << config.method;
3211         }
3212 
3213         tls.clearQueries();
3214         dns.clearQueries();
3215 
3216         // Set the configuration to OFF mode, so the resolver can validate private DNS servers in
3217         // every test config.
3218         ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
3219     }
3220 }
3221 
3222 // DNS-over-TLS validation success, but server does not respond to TLS query after a while.
3223 // Resolver should have a reasonable number of retries instead of spinning forever. We don't have
3224 // an efficient way to know if resolver is stuck in an infinite loop. However, test case will be
3225 // failed due to timeout.
TEST_F(ResolverTest,UnstableTls)3226 TEST_F(ResolverTest, UnstableTls) {
3227     const char CLEARTEXT_PORT[] = "53";
3228     const char TLS_PORT[] = "853";
3229     const char* host_name1 = "nonexistent1.example.com.";
3230     const char* host_name2 = "nonexistent2.example.com.";
3231 
3232     test::DNSResponder dns(kDefaultServer, CLEARTEXT_PORT, ns_rcode::ns_r_servfail);
3233     ASSERT_TRUE(dns.startServer());
3234     dns.setEdns(test::DNSResponder::Edns::FORMERR_ON_EDNS);
3235     test::DnsTlsFrontend tls(kDefaultServer, TLS_PORT, kDefaultServer, CLEARTEXT_PORT);
3236     ASSERT_TRUE(tls.startServer());
3237     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(ResolverParams::Builder().build()));
3238     EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
3239 
3240     // Shutdown TLS server to get an error. It's similar to no response case but without waiting.
3241     tls.stopServer();
3242 
3243     const hostent* h_result = gethostbyname(host_name1);
3244     EXPECT_EQ(1U, GetNumQueries(dns, host_name1));
3245     ASSERT_TRUE(h_result == nullptr);
3246     ASSERT_EQ(HOST_NOT_FOUND, h_errno);
3247 
3248     addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
3249     ScopedAddrinfo ai_result = safe_getaddrinfo(host_name2, nullptr, &hints);
3250     EXPECT_TRUE(ai_result == nullptr);
3251     EXPECT_EQ(1U, GetNumQueries(dns, host_name2));
3252 }
3253 
3254 // DNS-over-TLS validation success, but server does not respond to TLS query after a while.
3255 // Moreover, server responds RCODE=FORMERR even on non-EDNS query.
TEST_F(ResolverTest,BogusDnsServer)3256 TEST_F(ResolverTest, BogusDnsServer) {
3257     const char CLEARTEXT_PORT[] = "53";
3258     const char TLS_PORT[] = "853";
3259     const char* host_name1 = "nonexistent1.example.com.";
3260     const char* host_name2 = "nonexistent2.example.com.";
3261 
3262     test::DNSResponder dns(kDefaultServer, CLEARTEXT_PORT, ns_rcode::ns_r_servfail);
3263     ASSERT_TRUE(dns.startServer());
3264     test::DnsTlsFrontend tls(kDefaultServer, TLS_PORT, kDefaultServer, CLEARTEXT_PORT);
3265     ASSERT_TRUE(tls.startServer());
3266     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(ResolverParams::Builder().build()));
3267     EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
3268 
3269     // Shutdown TLS server to get an error. It's similar to no response case but without waiting.
3270     tls.stopServer();
3271     dns.setEdns(test::DNSResponder::Edns::FORMERR_UNCOND);
3272 
3273     const hostent* h_result = gethostbyname(host_name1);
3274     EXPECT_EQ(0U, GetNumQueries(dns, host_name1));
3275     ASSERT_TRUE(h_result == nullptr);
3276     ASSERT_EQ(HOST_NOT_FOUND, h_errno);
3277 
3278     addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
3279     ScopedAddrinfo ai_result = safe_getaddrinfo(host_name2, nullptr, &hints);
3280     EXPECT_TRUE(ai_result == nullptr);
3281     EXPECT_EQ(0U, GetNumQueries(dns, host_name2));
3282 }
3283 
TEST_F(ResolverTest,GetAddrInfo_Dns64Synthesize)3284 TEST_F(ResolverTest, GetAddrInfo_Dns64Synthesize) {
3285     constexpr char listen_addr[] = "::1";
3286     constexpr char host_name[] = "v4only.example.com.";
3287     const std::vector<DnsRecord> records = {
3288             {host_name, ns_type::ns_t_a, "1.2.3.4"},
3289     };
3290 
3291     test::DNSResponder dns(listen_addr);
3292     StartDns(dns, records);
3293 
3294     std::vector<std::string> servers = {listen_addr};
3295     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3296     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
3297 
3298     // If the socket type is not specified, every address will appear twice, once for
3299     // SOCK_STREAM and one for SOCK_DGRAM. Just pick one because the addresses for
3300     // the second query of different socket type are responded by the cache.
3301     // See android_getaddrinfofornetcontext in packages/modules/DnsResolver/getaddrinfo.cpp
3302     const addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM};
3303     ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, &hints);
3304     EXPECT_TRUE(result != nullptr);
3305     // Expect that there are two queries, one AAAA (which returns no records) and one A
3306     // (which returns 1.2.3.4).
3307     EXPECT_EQ(2U, GetNumQueries(dns, host_name));
3308     EXPECT_THAT(ToStrings(result), testing::ElementsAre("64:ff9b::102:304", "1.2.3.4"));
3309 
3310     // Stopping NAT64 prefix discovery disables synthesis.
3311     EXPECT_TRUE(mDnsClient.resolvService()->stopPrefix64Discovery(TEST_NETID).isOk());
3312     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_NOT_FOUND));
3313     dns.clearQueries();
3314 
3315     result = safe_getaddrinfo("v4only", nullptr, &hints);
3316     EXPECT_TRUE(result != nullptr);
3317     // Expect that there is one query, an AAAA (which returns no records), because the
3318     // A is already cached.
3319     EXPECT_EQ(1U, GetNumQueries(dns, host_name));
3320     EXPECT_EQ(ToString(result), "1.2.3.4");
3321 }
3322 
3323 // TODO: merge to #GetAddrInfo_Dns64Synthesize once DNSResponder supports multi DnsRecords for a
3324 // hostname.
TEST_F(ResolverTest,GetAddrInfo_Dns64SynthesizeMultiAnswers)3325 TEST_F(ResolverTest, GetAddrInfo_Dns64SynthesizeMultiAnswers) {
3326     test::DNSResponder dns(test::DNSResponder::MappingType::BINARY_PACKET);
3327     dns.addMappingBinaryPacket(kHelloExampleComQueryV4, kHelloExampleComResponsesV4);
3328     StartDns(dns, {});
3329     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
3330     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
3331 
3332     const addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM};
3333     ScopedAddrinfo result = safe_getaddrinfo(kHelloExampleCom, nullptr, &hints);
3334     ASSERT_FALSE(result == nullptr);
3335 
3336     // Synthesize AAAA if there's no AAAA answer and AF_UNSPEC is specified.
3337     EXPECT_THAT(ToStrings(result),
3338                 testing::ElementsAre("64:ff9b::102:304", "64:ff9b::808:808", "64:ff9b::5175:15ca",
3339                                      "1.2.3.4", "8.8.8.8", "81.117.21.202"));
3340 }
3341 
TEST_F(ResolverTest,GetAddrInfo_Dns64Canonname)3342 TEST_F(ResolverTest, GetAddrInfo_Dns64Canonname) {
3343     constexpr char listen_addr[] = "::1";
3344     constexpr char host_name[] = "v4only.example.com.";
3345     const std::vector<DnsRecord> records = {
3346             {host_name, ns_type::ns_t_a, "1.2.3.4"},
3347     };
3348 
3349     test::DNSResponder dns(listen_addr);
3350     StartDns(dns, records);
3351 
3352     std::vector<std::string> servers = {listen_addr};
3353     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3354     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
3355 
3356     // clang-format off
3357     static const struct TestConfig {
3358         int family;
3359         int flags;
3360         std::vector<std::string> expectedAddresses;
3361         const char* expectedCanonname;
3362 
3363         std::string asParameters() const {
3364             return fmt::format("family={}, flags={}", family, flags);
3365         }
3366     } testConfigs[]{
3367         {AF_UNSPEC,            0, {"64:ff9b::102:304", "1.2.3.4"}, nullptr},
3368         {AF_UNSPEC, AI_CANONNAME, {"64:ff9b::102:304", "1.2.3.4"}, "v4only.example.com"},
3369         {AF_INET6,             0, {"64:ff9b::102:304"}           , nullptr},
3370         {AF_INET6,  AI_CANONNAME, {"64:ff9b::102:304"}           , "v4only.example.com"},
3371     };
3372     // clang-format on
3373 
3374     for (const auto& config : testConfigs) {
3375         SCOPED_TRACE(config.asParameters());
3376 
3377         const addrinfo hints = {
3378                 .ai_family = config.family, .ai_flags = config.flags, .ai_socktype = SOCK_DGRAM};
3379         ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, &hints);
3380         ASSERT_TRUE(result != nullptr);
3381         EXPECT_THAT(ToStrings(result), testing::ElementsAreArray(config.expectedAddresses));
3382         for (const auto* ai = result.get(); ai != nullptr; ai = ai->ai_next) {
3383             EXPECT_STREQ(ai->ai_canonname, config.expectedCanonname);
3384         }
3385     }
3386 }
3387 
TEST_F(ResolverTest,GetAddrInfo_Dns64QuerySpecified)3388 TEST_F(ResolverTest, GetAddrInfo_Dns64QuerySpecified) {
3389     constexpr char listen_addr[] = "::1";
3390     constexpr char host_name[] = "v4only.example.com.";
3391     const std::vector<DnsRecord> records = {
3392             {host_name, ns_type::ns_t_a, "1.2.3.4"},
3393     };
3394 
3395     test::DNSResponder dns(listen_addr);
3396     StartDns(dns, records);
3397     const std::vector<std::string> servers = {listen_addr};
3398     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3399     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
3400 
3401     // Synthesize AAAA if AF_INET6 is specified and there is A record only. Make sure that A record
3402     // is not returned as well.
3403     addrinfo hints = {.ai_family = AF_INET6, .ai_socktype = SOCK_DGRAM};
3404     ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, &hints);
3405     EXPECT_TRUE(result != nullptr);
3406     // One for AAAA query without an answer and one for A query which is used for DNS64 synthesis.
3407     EXPECT_EQ(2U, GetNumQueries(dns, host_name));
3408     EXPECT_EQ(ToString(result), "64:ff9b::102:304");
3409     dns.clearQueries();
3410 
3411     // Don't synthesize AAAA if AF_INET is specified and there is A record only.
3412     hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
3413     result = safe_getaddrinfo("v4only", nullptr, &hints);
3414     EXPECT_TRUE(result != nullptr);
3415     EXPECT_EQ(0U /*cached in previous queries*/, GetNumQueries(dns, host_name));
3416     EXPECT_EQ(ToString(result), "1.2.3.4");
3417 }
3418 
TEST_F(ResolverTest,GetAddrInfo_Dns64QueryUnspecifiedV6)3419 TEST_F(ResolverTest, GetAddrInfo_Dns64QueryUnspecifiedV6) {
3420     constexpr char listen_addr[] = "::1";
3421     constexpr char host_name[] = "v4v6.example.com.";
3422     const std::vector<DnsRecord> records = {
3423             {host_name, ns_type::ns_t_a, "1.2.3.4"},
3424             {host_name, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
3425     };
3426 
3427     test::DNSResponder dns(listen_addr);
3428     StartDns(dns, records);
3429     const std::vector<std::string> servers = {listen_addr};
3430     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3431     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
3432 
3433     const addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM};
3434     ScopedAddrinfo result = safe_getaddrinfo("v4v6", nullptr, &hints);
3435     EXPECT_TRUE(result != nullptr);
3436     EXPECT_EQ(2U, GetNumQueries(dns, host_name));
3437 
3438     // Do not synthesize AAAA if there's at least one AAAA answer.
3439     EXPECT_THAT(ToStrings(result), testing::ElementsAre("2001:db8::102:304", "1.2.3.4"));
3440 }
3441 
TEST_F(ResolverTest,GetAddrInfo_Dns64QueryUnspecifiedNoV6)3442 TEST_F(ResolverTest, GetAddrInfo_Dns64QueryUnspecifiedNoV6) {
3443     constexpr char listen_addr[] = "::1";
3444     constexpr char host_name[] = "v4v6.example.com.";
3445     const std::vector<DnsRecord> records = {
3446             {host_name, ns_type::ns_t_a, "1.2.3.4"},
3447     };
3448 
3449     test::DNSResponder dns(listen_addr);
3450     StartDns(dns, records);
3451     const std::vector<std::string> servers = {listen_addr};
3452     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3453     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
3454 
3455     const addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM};
3456     ScopedAddrinfo result = safe_getaddrinfo("v4v6", nullptr, &hints);
3457     EXPECT_TRUE(result != nullptr);
3458     EXPECT_EQ(2U, GetNumQueries(dns, host_name));
3459 
3460     // Synthesize AAAA if there's no AAAA answer and AF_UNSPEC is specified.
3461     EXPECT_THAT(ToStrings(result), testing::ElementsAre("64:ff9b::102:304", "1.2.3.4"));
3462 }
3463 
TEST_F(ResolverTest,GetAddrInfo_Dns64QuerySpecialUseIPv4Addresses)3464 TEST_F(ResolverTest, GetAddrInfo_Dns64QuerySpecialUseIPv4Addresses) {
3465     constexpr char THIS_NETWORK[] = "this_network";
3466     constexpr char LOOPBACK[] = "loopback";
3467     constexpr char LINK_LOCAL[] = "link_local";
3468     constexpr char MULTICAST[] = "multicast";
3469     constexpr char LIMITED_BROADCAST[] = "limited_broadcast";
3470 
3471     constexpr char ADDR_THIS_NETWORK[] = "0.0.0.1";
3472     constexpr char ADDR_LOOPBACK[] = "127.0.0.1";
3473     constexpr char ADDR_LINK_LOCAL[] = "169.254.0.1";
3474     constexpr char ADDR_MULTICAST[] = "224.0.0.1";
3475     constexpr char ADDR_LIMITED_BROADCAST[] = "255.255.255.255";
3476 
3477     constexpr char listen_addr[] = "::1";
3478 
3479     test::DNSResponder dns(listen_addr);
3480     StartDns(dns, {});
3481     const std::vector<std::string> servers = {listen_addr};
3482     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3483     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
3484 
3485     // clang-format off
3486     static const struct TestConfig {
3487         std::string name;
3488         std::string addr;
3489 
3490         std::string asHostName() const { return fmt::format("{}.example.com.", name); }
3491     } testConfigs[]{
3492         {THIS_NETWORK,      ADDR_THIS_NETWORK},
3493         {LOOPBACK,          ADDR_LOOPBACK},
3494         {LINK_LOCAL,        ADDR_LINK_LOCAL},
3495         {MULTICAST,         ADDR_MULTICAST},
3496         {LIMITED_BROADCAST, ADDR_LIMITED_BROADCAST}
3497     };
3498     // clang-format on
3499 
3500     for (const auto& config : testConfigs) {
3501         const std::string testHostName = config.asHostName();
3502         SCOPED_TRACE(testHostName);
3503 
3504         const char* host_name = testHostName.c_str();
3505         dns.addMapping(host_name, ns_type::ns_t_a, config.addr.c_str());
3506 
3507         // Expect no result because AF_INET6 is specified and don't synthesize special use IPv4
3508         // address.
3509         addrinfo hints = {.ai_family = AF_INET6, .ai_socktype = SOCK_DGRAM};
3510         ScopedAddrinfo result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
3511         EXPECT_TRUE(result == nullptr);
3512         EXPECT_EQ(2U, GetNumQueries(dns, host_name));
3513         dns.clearQueries();
3514 
3515         // Expect special use IPv4 address only because AF_UNSPEC is specified and don't synthesize
3516         // special use IPv4 address.
3517         hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM};
3518         result = safe_getaddrinfo(config.name.c_str(), nullptr, &hints);
3519         EXPECT_TRUE(result != nullptr);
3520         // Expect IPv6 query only. IPv4 answer has been cached in previous query.
3521         EXPECT_EQ(1U, GetNumQueries(dns, host_name));
3522         EXPECT_EQ(ToString(result), config.addr);
3523         dns.clearQueries();
3524     }
3525 }
3526 
TEST_F(ResolverTest,GetAddrInfo_Dns64QueryWithNullArgumentHints)3527 TEST_F(ResolverTest, GetAddrInfo_Dns64QueryWithNullArgumentHints) {
3528     constexpr char listen_addr[] = "::1";
3529     constexpr char host_name[] = "v4only.example.com.";
3530     constexpr char host_name2[] = "v4v6.example.com.";
3531     const std::vector<DnsRecord> records = {
3532             {host_name, ns_type::ns_t_a, "1.2.3.4"},
3533             {host_name2, ns_type::ns_t_a, "1.2.3.4"},
3534             {host_name2, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
3535     };
3536 
3537     test::DNSResponder dns(listen_addr);
3538     StartDns(dns, records);
3539     const std::vector<std::string> servers = {listen_addr};
3540     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3541     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
3542 
3543     // Synthesize AAAA if there is A answer only and AF_UNSPEC (hints NULL) is specified.
3544     // Assign argument hints of getaddrinfo() as null is equivalent to set ai_family AF_UNSPEC,
3545     // ai_socktype 0 (any), and ai_protocol 0 (any). Note the setting ai_socktype 0 (any) causes
3546     // that every address will appear twice, once for SOCK_STREAM and one for SOCK_DGRAM.
3547     // See resolv_getaddrinfo in packages/modules/DnsResolver/getaddrinfo.cpp.
3548     ScopedAddrinfo result = safe_getaddrinfo("v4only", nullptr, nullptr);
3549     EXPECT_TRUE(result != nullptr);
3550     EXPECT_LE(2U, GetNumQueries(dns, host_name));
3551     EXPECT_THAT(ToStrings(result),
3552                 testing::ElementsAre("64:ff9b::102:304", "64:ff9b::102:304", "1.2.3.4", "1.2.3.4"));
3553     dns.clearQueries();
3554 
3555     // Do not synthesize AAAA if there's at least one AAAA answer.
3556     // The reason which the addresses appear twice is as mentioned above.
3557     result = safe_getaddrinfo("v4v6", nullptr, nullptr);
3558     EXPECT_TRUE(result != nullptr);
3559     EXPECT_LE(2U, GetNumQueries(dns, host_name2));
3560     EXPECT_THAT(ToStrings(result),
3561                 testing::UnorderedElementsAre("2001:db8::102:304", "2001:db8::102:304", "1.2.3.4",
3562                                               "1.2.3.4"));
3563 }
3564 
TEST_F(ResolverTest,GetAddrInfo_Dns64QueryNullArgumentNode)3565 TEST_F(ResolverTest, GetAddrInfo_Dns64QueryNullArgumentNode) {
3566     constexpr char ADDR_ANYADDR_V4[] = "0.0.0.0";
3567     constexpr char ADDR_ANYADDR_V6[] = "::";
3568     constexpr char ADDR_LOCALHOST_V4[] = "127.0.0.1";
3569     constexpr char ADDR_LOCALHOST_V6[] = "::1";
3570 
3571     constexpr char PORT_NAME_HTTP[] = "http";
3572     constexpr char PORT_NUMBER_HTTP[] = "80";
3573 
3574     constexpr char listen_addr[] = "::1";
3575 
3576     test::DNSResponder dns(listen_addr);
3577     StartDns(dns, {});
3578     const std::vector<std::string> servers = {listen_addr};
3579     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3580     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
3581 
3582     // clang-format off
3583     // If node is null, return address is listed by libc/getaddrinfo.c as follows.
3584     // - passive socket -> anyaddr (0.0.0.0 or ::)
3585     // - non-passive socket -> localhost (127.0.0.1 or ::1)
3586     static const struct TestConfig {
3587         int flag;
3588         std::string addr_v4;
3589         std::string addr_v6;
3590 
3591         std::string asParameters() const {
3592             return fmt::format("flag={}, addr_v4={}, addr_v6={}", flag, addr_v4,
3593                                 addr_v6);
3594         }
3595     } testConfigs[]{
3596         {0 /* non-passive */, ADDR_LOCALHOST_V4, ADDR_LOCALHOST_V6},
3597         {AI_PASSIVE,          ADDR_ANYADDR_V4,   ADDR_ANYADDR_V6}
3598     };
3599     // clang-format on
3600 
3601     for (const auto& config : testConfigs) {
3602         SCOPED_TRACE(config.asParameters());
3603 
3604         addrinfo hints = {
3605                 .ai_flags = config.flag,
3606                 .ai_family = AF_UNSPEC,  // any address family
3607                 .ai_socktype = 0,        // any type
3608                 .ai_protocol = 0,        // any protocol
3609         };
3610 
3611         // Assign hostname as null and service as port name.
3612         ScopedAddrinfo result = safe_getaddrinfo(nullptr, PORT_NAME_HTTP, &hints);
3613         ASSERT_TRUE(result != nullptr);
3614 
3615         // Can't be synthesized because it should not get into Netd.
3616         // Every address appears twice, once for SOCK_STREAM and one for SOCK_DGRAM because the
3617         // socket type is not specified.
3618         EXPECT_THAT(ToStrings(result),
3619                     testing::UnorderedElementsAre(config.addr_v4, config.addr_v4, config.addr_v6,
3620                                                   config.addr_v6));
3621 
3622         // Assign hostname as null and service as numeric port number.
3623         hints.ai_flags = config.flag | AI_NUMERICSERV;
3624         result = safe_getaddrinfo(nullptr, PORT_NUMBER_HTTP, &hints);
3625         ASSERT_TRUE(result != nullptr);
3626 
3627         // Can't be synthesized because it should not get into Netd.
3628         // The reason which the addresses appear twice is as mentioned above.
3629         EXPECT_THAT(ToStrings(result),
3630                     testing::UnorderedElementsAre(config.addr_v4, config.addr_v4, config.addr_v6,
3631                                                   config.addr_v6));
3632     }
3633 }
3634 
TEST_F(ResolverTest,GetHostByAddr_ReverseDnsQueryWithHavingNat64Prefix)3635 TEST_F(ResolverTest, GetHostByAddr_ReverseDnsQueryWithHavingNat64Prefix) {
3636     struct hostent* result = nullptr;
3637     struct in_addr v4addr;
3638     struct in6_addr v6addr;
3639 
3640     constexpr char listen_addr[] = "::1";
3641     constexpr char ptr_name[] = "v4v6.example.com.";
3642     // PTR record for IPv4 address 1.2.3.4
3643     constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
3644     // PTR record for IPv6 address 2001:db8::102:304
3645     constexpr char ptr_addr_v6[] =
3646             "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.";
3647     const std::vector<DnsRecord> records = {
3648             {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
3649             {ptr_addr_v6, ns_type::ns_t_ptr, ptr_name},
3650     };
3651 
3652     test::DNSResponder dns(listen_addr);
3653     StartDns(dns, records);
3654     const std::vector<std::string> servers = {listen_addr};
3655     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3656     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
3657 
3658     // Reverse IPv4 DNS query. Prefix should have no effect on it.
3659     inet_pton(AF_INET, "1.2.3.4", &v4addr);
3660     result = gethostbyaddr(&v4addr, sizeof(v4addr), AF_INET);
3661     ASSERT_TRUE(result != nullptr);
3662     std::string result_str = result->h_name ? result->h_name : "null";
3663     EXPECT_EQ(result_str, "v4v6.example.com");
3664 
3665     // Reverse IPv6 DNS query. Prefix should have no effect on it.
3666     inet_pton(AF_INET6, "2001:db8::102:304", &v6addr);
3667     result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
3668     ASSERT_TRUE(result != nullptr);
3669     result_str = result->h_name ? result->h_name : "null";
3670     EXPECT_EQ(result_str, "v4v6.example.com");
3671 }
3672 
TEST_F(ResolverTest,GetHostByAddr_ReverseDns64Query)3673 TEST_F(ResolverTest, GetHostByAddr_ReverseDns64Query) {
3674     constexpr char listen_addr[] = "::1";
3675     constexpr char ptr_name[] = "v4only.example.com.";
3676     // PTR record for IPv4 address 1.2.3.4
3677     constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
3678     // PTR record for IPv6 address 64:ff9b::1.2.3.4
3679     constexpr char ptr_addr_v6_nomapping[] =
3680             "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.";
3681     constexpr char ptr_name_v6_synthesis[] = "v6synthesis.example.com.";
3682     // PTR record for IPv6 address 64:ff9b::5.6.7.8
3683     constexpr char ptr_addr_v6_synthesis[] =
3684             "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.";
3685     const std::vector<DnsRecord> records = {
3686             {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
3687             {ptr_addr_v6_synthesis, ns_type::ns_t_ptr, ptr_name_v6_synthesis},
3688     };
3689 
3690     test::DNSResponder dns(listen_addr);
3691     StartDns(dns, records);
3692     // "ptr_addr_v6_nomapping" is not mapped in DNS server
3693     const std::vector<std::string> servers = {listen_addr};
3694     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3695     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
3696 
3697     // Synthesized PTR record doesn't exist on DNS server
3698     // Reverse IPv6 DNS64 query while DNS server doesn't have an answer for synthesized address.
3699     // After querying synthesized address failed, expect that prefix is removed from IPv6
3700     // synthesized address and do reverse IPv4 query instead.
3701     struct in6_addr v6addr;
3702     inet_pton(AF_INET6, "64:ff9b::1.2.3.4", &v6addr);
3703     struct hostent* result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
3704     ASSERT_TRUE(result != nullptr);
3705     EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_nomapping));  // PTR record not exist
3706     EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4));            // PTR record exist
3707     std::string result_str = result->h_name ? result->h_name : "null";
3708     EXPECT_EQ(result_str, "v4only.example.com");
3709     // Check that return address has been mapped from IPv4 to IPv6 address because Netd
3710     // removes NAT64 prefix and does IPv4 DNS reverse lookup in this case. Then, Netd
3711     // fakes the return IPv4 address as original queried IPv6 address.
3712     result_str = ToString(result);
3713     EXPECT_EQ(result_str, "64:ff9b::102:304");
3714     dns.clearQueries();
3715 
3716     // Synthesized PTR record exists on DNS server
3717     // Reverse IPv6 DNS64 query while DNS server has an answer for synthesized address.
3718     // Expect to Netd pass through synthesized address for DNS queries.
3719     inet_pton(AF_INET6, "64:ff9b::5.6.7.8", &v6addr);
3720     result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
3721     ASSERT_TRUE(result != nullptr);
3722     EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_synthesis));
3723     result_str = result->h_name ? result->h_name : "null";
3724     EXPECT_EQ(result_str, "v6synthesis.example.com");
3725 }
3726 
TEST_F(ResolverTest,GetHostByAddr_ReverseDns64QueryFromHostFile)3727 TEST_F(ResolverTest, GetHostByAddr_ReverseDns64QueryFromHostFile) {
3728     constexpr char host_name[] = "localhost";
3729     // The address is synthesized by prefix64:localhost.
3730     constexpr char host_addr[] = "64:ff9b::7f00:1";
3731     constexpr char listen_addr[] = "::1";
3732 
3733     test::DNSResponder dns(listen_addr);
3734     StartDns(dns, {});
3735     const std::vector<std::string> servers = {listen_addr};
3736     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3737     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
3738 
3739     // Using synthesized "localhost" address to be a trick for resolving host name
3740     // from host file /etc/hosts and "localhost" is the only name in /etc/hosts. Note that this is
3741     // not realistic: the code never synthesizes AAAA records for addresses in 127.0.0.0/8.
3742     struct in6_addr v6addr;
3743     inet_pton(AF_INET6, host_addr, &v6addr);
3744     struct hostent* result = gethostbyaddr(&v6addr, sizeof(v6addr), AF_INET6);
3745     ASSERT_TRUE(result != nullptr);
3746     // Expect no DNS queries; localhost is resolved via /etc/hosts.
3747     EXPECT_EQ(0U, GetNumQueries(dns, host_name));
3748 
3749     ASSERT_EQ(sizeof(in6_addr), (unsigned)result->h_length);
3750     ASSERT_EQ(AF_INET6, result->h_addrtype);
3751     std::string result_str = ToString(result);
3752     EXPECT_EQ(result_str, host_addr);
3753     result_str = result->h_name ? result->h_name : "null";
3754     EXPECT_EQ(result_str, host_name);
3755 }
3756 
TEST_F(ResolverTest,GetHostByAddr_cnamesClasslessReverseDelegation)3757 TEST_F(ResolverTest, GetHostByAddr_cnamesClasslessReverseDelegation) {
3758     // IPv4 addresses in the subnet with notation '/' or '-'.
3759     constexpr char addr_slash[] = "192.0.2.1";
3760     constexpr char addr_hyphen[] = "192.0.3.1";
3761 
3762     // Used to verify DNS reverse query for classless reverse lookup zone. See detail in RFC 2317
3763     // section 4.
3764     const static std::vector<DnsRecord> records = {
3765             // The records for reverse querying "192.0.2.1" in the subnet with notation '/'.
3766             {"1.2.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0/25.2.0.192.in-addr.arpa."},
3767             {"1.0/25.2.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
3768 
3769             // The records for reverse querying "192.0.3.1" in the subnet with notation '-'.
3770             {"1.3.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0-127.3.0.192.in-addr.arpa."},
3771             {"1.0-127.3.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
3772     };
3773 
3774     test::DNSResponder dns;
3775     StartDns(dns, records);
3776     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
3777 
3778     for (const auto& address : {addr_slash, addr_hyphen}) {
3779         SCOPED_TRACE(address);
3780 
3781         in_addr v4addr;
3782         ASSERT_TRUE(inet_pton(AF_INET, address, &v4addr));
3783         hostent* result = gethostbyaddr(&v4addr, sizeof(v4addr), AF_INET);
3784         ASSERT_TRUE(result != nullptr);
3785         EXPECT_STREQ("hello.example.com", result->h_name);
3786     }
3787 }
3788 
TEST_F(ResolverTest,GetNameInfo_ReverseDnsQueryWithHavingNat64Prefix)3789 TEST_F(ResolverTest, GetNameInfo_ReverseDnsQueryWithHavingNat64Prefix) {
3790     constexpr char listen_addr[] = "::1";
3791     constexpr char ptr_name[] = "v4v6.example.com.";
3792     // PTR record for IPv4 address 1.2.3.4
3793     constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
3794     // PTR record for IPv6 address 2001:db8::102:304
3795     constexpr char ptr_addr_v6[] =
3796             "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.";
3797     const std::vector<DnsRecord> records = {
3798             {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
3799             {ptr_addr_v6, ns_type::ns_t_ptr, ptr_name},
3800     };
3801 
3802     test::DNSResponder dns(listen_addr);
3803     StartDns(dns, records);
3804     const std::vector<std::string> servers = {listen_addr};
3805     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3806     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
3807 
3808     // clang-format off
3809     static const struct TestConfig {
3810         int flag;
3811         int family;
3812         std::string addr;
3813         std::string host;
3814 
3815         std::string asParameters() const {
3816             return fmt::format("flag={}, family={}, addr={}, host={}", flag, family, addr,
3817                                 host);
3818         }
3819     } testConfigs[]{
3820         {NI_NAMEREQD,    AF_INET,  "1.2.3.4",           "v4v6.example.com"},
3821         {NI_NUMERICHOST, AF_INET,  "1.2.3.4",           "1.2.3.4"},
3822         {0,              AF_INET,  "1.2.3.4",           "v4v6.example.com"},
3823         {0,              AF_INET,  "5.6.7.8",           "5.6.7.8"},           // unmapped
3824         {NI_NAMEREQD,    AF_INET6, "2001:db8::102:304", "v4v6.example.com"},
3825         {NI_NUMERICHOST, AF_INET6, "2001:db8::102:304", "2001:db8::102:304"},
3826         {0,              AF_INET6, "2001:db8::102:304", "v4v6.example.com"},
3827         {0,              AF_INET6, "2001:db8::506:708", "2001:db8::506:708"}, // unmapped
3828     };
3829     // clang-format on
3830 
3831     // Reverse IPv4/IPv6 DNS query. Prefix should have no effect on it.
3832     for (const auto& config : testConfigs) {
3833         SCOPED_TRACE(config.asParameters());
3834 
3835         int rv;
3836         char host[NI_MAXHOST];
3837         struct sockaddr_in sin;
3838         struct sockaddr_in6 sin6;
3839         if (config.family == AF_INET) {
3840             memset(&sin, 0, sizeof(sin));
3841             sin.sin_family = AF_INET;
3842             inet_pton(AF_INET, config.addr.c_str(), &sin.sin_addr);
3843             rv = getnameinfo((const struct sockaddr*)&sin, sizeof(sin), host, sizeof(host), nullptr,
3844                              0, config.flag);
3845             if (config.flag == NI_NAMEREQD) EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4));
3846         } else if (config.family == AF_INET6) {
3847             memset(&sin6, 0, sizeof(sin6));
3848             sin6.sin6_family = AF_INET6;
3849             inet_pton(AF_INET6, config.addr.c_str(), &sin6.sin6_addr);
3850             rv = getnameinfo((const struct sockaddr*)&sin6, sizeof(sin6), host, sizeof(host),
3851                              nullptr, 0, config.flag);
3852             if (config.flag == NI_NAMEREQD) EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6));
3853         }
3854         ASSERT_EQ(0, rv);
3855         std::string result_str = host;
3856         EXPECT_EQ(result_str, config.host);
3857         dns.clearQueries();
3858     }
3859 }
3860 
TEST_F(ResolverTest,GetNameInfo_ReverseDns64Query)3861 TEST_F(ResolverTest, GetNameInfo_ReverseDns64Query) {
3862     constexpr char listen_addr[] = "::1";
3863     constexpr char ptr_name[] = "v4only.example.com.";
3864     // PTR record for IPv4 address 1.2.3.4
3865     constexpr char ptr_addr_v4[] = "4.3.2.1.in-addr.arpa.";
3866     // PTR record for IPv6 address 64:ff9b::1.2.3.4
3867     constexpr char ptr_addr_v6_nomapping[] =
3868             "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.";
3869     constexpr char ptr_name_v6_synthesis[] = "v6synthesis.example.com.";
3870     // PTR record for IPv6 address 64:ff9b::5.6.7.8
3871     constexpr char ptr_addr_v6_synthesis[] =
3872             "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.";
3873     const std::vector<DnsRecord> records = {
3874             {ptr_addr_v4, ns_type::ns_t_ptr, ptr_name},
3875             {ptr_addr_v6_synthesis, ns_type::ns_t_ptr, ptr_name_v6_synthesis},
3876     };
3877 
3878     test::DNSResponder dns(listen_addr);
3879     StartDns(dns, records);
3880     const std::vector<std::string> servers = {listen_addr};
3881     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3882     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
3883 
3884     // clang-format off
3885     static const struct TestConfig {
3886         bool hasSynthesizedPtrRecord;
3887         int flag;
3888         std::string addr;
3889         std::string host;
3890 
3891         std::string asParameters() const {
3892             return fmt::format("hasSynthesizedPtrRecord={}, flag={}, addr={}, host={}",
3893                                 hasSynthesizedPtrRecord, flag, addr, host);
3894         }
3895     } testConfigs[]{
3896         {false, NI_NAMEREQD,    "64:ff9b::102:304", "v4only.example.com"},
3897         {false, NI_NUMERICHOST, "64:ff9b::102:304", "64:ff9b::102:304"},
3898         {false, 0,              "64:ff9b::102:304", "v4only.example.com"},
3899         {true,  NI_NAMEREQD,    "64:ff9b::506:708", "v6synthesis.example.com"},
3900         {true,  NI_NUMERICHOST, "64:ff9b::506:708", "64:ff9b::506:708"},
3901         {true,  0,              "64:ff9b::506:708", "v6synthesis.example.com"}
3902     };
3903     // clang-format on
3904 
3905     // hasSynthesizedPtrRecord = false
3906     //   Synthesized PTR record doesn't exist on DNS server
3907     //   Reverse IPv6 DNS64 query while DNS server doesn't have an answer for synthesized address.
3908     //   After querying synthesized address failed, expect that prefix is removed from IPv6
3909     //   synthesized address and do reverse IPv4 query instead.
3910     //
3911     // hasSynthesizedPtrRecord = true
3912     //   Synthesized PTR record exists on DNS server
3913     //   Reverse IPv6 DNS64 query while DNS server has an answer for synthesized address.
3914     //   Expect to just pass through synthesized address for DNS queries.
3915     for (const auto& config : testConfigs) {
3916         SCOPED_TRACE(config.asParameters());
3917 
3918         char host[NI_MAXHOST];
3919         struct sockaddr_in6 sin6;
3920         memset(&sin6, 0, sizeof(sin6));
3921         sin6.sin6_family = AF_INET6;
3922         inet_pton(AF_INET6, config.addr.c_str(), &sin6.sin6_addr);
3923         int rv = getnameinfo((const struct sockaddr*)&sin6, sizeof(sin6), host, sizeof(host),
3924                              nullptr, 0, config.flag);
3925         ASSERT_EQ(0, rv);
3926         if (config.flag == NI_NAMEREQD) {
3927             if (config.hasSynthesizedPtrRecord) {
3928                 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_synthesis));
3929             } else {
3930                 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v6_nomapping));  // PTR record not exist.
3931                 EXPECT_LE(1U, GetNumQueries(dns, ptr_addr_v4));            // PTR record exist.
3932             }
3933         }
3934         std::string result_str = host;
3935         EXPECT_EQ(result_str, config.host);
3936         dns.clearQueries();
3937     }
3938 }
3939 
TEST_F(ResolverTest,GetNameInfo_ReverseDns64QueryFromHostFile)3940 TEST_F(ResolverTest, GetNameInfo_ReverseDns64QueryFromHostFile) {
3941     constexpr char host_name[] = "localhost";
3942     // The address is synthesized by prefix64:localhost.
3943     constexpr char host_addr[] = "64:ff9b::7f00:1";
3944     constexpr char listen_addr[] = "::1";
3945 
3946     test::DNSResponder dns(listen_addr);
3947 
3948     StartDns(dns, {});
3949     const std::vector<std::string> servers = {listen_addr};
3950     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
3951     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
3952 
3953     // Using synthesized "localhost" address to be a trick for resolving host name
3954     // from host file /etc/hosts and "localhost" is the only name in /etc/hosts. Note that this is
3955     // not realistic: the code never synthesizes AAAA records for addresses in 127.0.0.0/8.
3956     char host[NI_MAXHOST];
3957     struct sockaddr_in6 sin6 = {.sin6_family = AF_INET6};
3958     inet_pton(AF_INET6, host_addr, &sin6.sin6_addr);
3959     int rv = getnameinfo((const struct sockaddr*)&sin6, sizeof(sin6), host, sizeof(host), nullptr,
3960                          0, NI_NAMEREQD);
3961     ASSERT_EQ(0, rv);
3962     // Expect no DNS queries; localhost is resolved via /etc/hosts.
3963     EXPECT_EQ(0U, GetNumQueries(dns, host_name));
3964 
3965     std::string result_str = host;
3966     EXPECT_EQ(result_str, host_name);
3967 }
3968 
TEST_F(ResolverTest,GetNameInfo_cnamesClasslessReverseDelegation)3969 TEST_F(ResolverTest, GetNameInfo_cnamesClasslessReverseDelegation) {
3970     // IPv4 addresses in the subnet with notation '/' or '-'.
3971     constexpr char addr_slash[] = "192.0.2.1";
3972     constexpr char addr_hyphen[] = "192.0.3.1";
3973 
3974     // Used to verify DNS reverse query for classless reverse lookup zone. See detail in RFC 2317
3975     // section 4.
3976     const static std::vector<DnsRecord> records = {
3977             // The records for reverse querying "192.0.2.1" in the subnet with notation '/'.
3978             {"1.2.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0/25.2.0.192.in-addr.arpa."},
3979             {"1.0/25.2.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
3980 
3981             // The records for reverse querying "192.0.3.1" in the subnet with notation '-'.
3982             {"1.3.0.192.in-addr.arpa.", ns_type::ns_t_cname, "1.0-127.3.0.192.in-addr.arpa."},
3983             {"1.0-127.3.0.192.in-addr.arpa.", ns_type::ns_t_ptr, kHelloExampleCom},
3984     };
3985 
3986     test::DNSResponder dns;
3987     StartDns(dns, records);
3988     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
3989 
3990     for (const auto& address : {addr_slash, addr_hyphen}) {
3991         SCOPED_TRACE(address);
3992 
3993         char host[NI_MAXHOST];
3994         sockaddr_in sin = {.sin_family = AF_INET};
3995         ASSERT_TRUE(inet_pton(AF_INET, address, &sin.sin_addr));
3996         int rv = getnameinfo((const sockaddr*)&sin, sizeof(sin), host, sizeof(host), nullptr, 0,
3997                              NI_NAMEREQD);
3998         ASSERT_EQ(0, rv);
3999         EXPECT_STREQ("hello.example.com", host);
4000     }
4001 }
4002 
TEST_F(ResolverTest,GetHostByName2_Dns64Synthesize)4003 TEST_F(ResolverTest, GetHostByName2_Dns64Synthesize) {
4004     constexpr char listen_addr[] = "::1";
4005     constexpr char host_name[] = "ipv4only.example.com.";
4006     const std::vector<DnsRecord> records = {
4007             {host_name, ns_type::ns_t_a, "1.2.3.4"},
4008     };
4009 
4010     test::DNSResponder dns(listen_addr);
4011     StartDns(dns, records);
4012     const std::vector<std::string> servers = {listen_addr};
4013     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
4014     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
4015 
4016     // Query an IPv4-only hostname. Expect that gets a synthesized address.
4017     struct hostent* result = gethostbyname2("ipv4only", AF_INET6);
4018     ASSERT_TRUE(result != nullptr);
4019     EXPECT_LE(1U, GetNumQueries(dns, host_name));
4020     std::string result_str = ToString(result);
4021     EXPECT_EQ(result_str, "64:ff9b::102:304");
4022 }
4023 
TEST_F(ResolverTest,GetHostByName2_DnsQueryWithHavingNat64Prefix)4024 TEST_F(ResolverTest, GetHostByName2_DnsQueryWithHavingNat64Prefix) {
4025     constexpr char host_name[] = "v4v6.example.com.";
4026     constexpr char listen_addr[] = "::1";
4027     const std::vector<DnsRecord> records = {
4028             {host_name, ns_type::ns_t_a, "1.2.3.4"},
4029             {host_name, ns_type::ns_t_aaaa, "2001:db8::1.2.3.4"},
4030     };
4031 
4032     test::DNSResponder dns(listen_addr);
4033     StartDns(dns, records);
4034     const std::vector<std::string> servers = {listen_addr};
4035     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
4036     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
4037 
4038     // IPv4 DNS query. Prefix should have no effect on it.
4039     struct hostent* result = gethostbyname2("v4v6", AF_INET);
4040     ASSERT_TRUE(result != nullptr);
4041     EXPECT_LE(1U, GetNumQueries(dns, host_name));
4042     std::string result_str = ToString(result);
4043     EXPECT_EQ(result_str, "1.2.3.4");
4044     dns.clearQueries();
4045 
4046     // IPv6 DNS query. Prefix should have no effect on it.
4047     result = gethostbyname2("v4v6", AF_INET6);
4048     ASSERT_TRUE(result != nullptr);
4049     EXPECT_LE(1U, GetNumQueries(dns, host_name));
4050     result_str = ToString(result);
4051     EXPECT_EQ(result_str, "2001:db8::102:304");
4052 }
4053 
TEST_F(ResolverTest,GetHostByName2_Dns64QuerySpecialUseIPv4Addresses)4054 TEST_F(ResolverTest, GetHostByName2_Dns64QuerySpecialUseIPv4Addresses) {
4055     constexpr char THIS_NETWORK[] = "this_network";
4056     constexpr char LOOPBACK[] = "loopback";
4057     constexpr char LINK_LOCAL[] = "link_local";
4058     constexpr char MULTICAST[] = "multicast";
4059     constexpr char LIMITED_BROADCAST[] = "limited_broadcast";
4060 
4061     constexpr char ADDR_THIS_NETWORK[] = "0.0.0.1";
4062     constexpr char ADDR_LOOPBACK[] = "127.0.0.1";
4063     constexpr char ADDR_LINK_LOCAL[] = "169.254.0.1";
4064     constexpr char ADDR_MULTICAST[] = "224.0.0.1";
4065     constexpr char ADDR_LIMITED_BROADCAST[] = "255.255.255.255";
4066 
4067     constexpr char listen_addr[] = "::1";
4068 
4069     test::DNSResponder dns(listen_addr);
4070     StartDns(dns, {});
4071     const std::vector<std::string> servers = {listen_addr};
4072     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
4073     ASSERT_TRUE(mDnsClient.resolvService()->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
4074 
4075     // clang-format off
4076     static const struct TestConfig {
4077         std::string name;
4078         std::string addr;
4079 
4080         std::string asHostName() const {
4081             return fmt::format("{}.example.com.", name);
4082         }
4083     } testConfigs[]{
4084         {THIS_NETWORK,      ADDR_THIS_NETWORK},
4085         {LOOPBACK,          ADDR_LOOPBACK},
4086         {LINK_LOCAL,        ADDR_LINK_LOCAL},
4087         {MULTICAST,         ADDR_MULTICAST},
4088         {LIMITED_BROADCAST, ADDR_LIMITED_BROADCAST}
4089     };
4090     // clang-format on
4091 
4092     for (const auto& config : testConfigs) {
4093         const std::string testHostName = config.asHostName();
4094         SCOPED_TRACE(testHostName);
4095 
4096         const char* host_name = testHostName.c_str();
4097         dns.addMapping(host_name, ns_type::ns_t_a, config.addr.c_str());
4098 
4099         struct hostent* result = gethostbyname2(config.name.c_str(), AF_INET6);
4100         EXPECT_LE(1U, GetNumQueries(dns, host_name));
4101 
4102         // In AF_INET6 case, don't synthesize special use IPv4 address.
4103         // Expect to have no answer
4104         EXPECT_EQ(nullptr, result);
4105 
4106         dns.clearQueries();
4107     }
4108 }
4109 
TEST_F(ResolverTest,PrefixDiscoveryBypassTls)4110 TEST_F(ResolverTest, PrefixDiscoveryBypassTls) {
4111     constexpr char listen_addr[] = "::1";
4112     constexpr char dns64_name[] = "ipv4only.arpa.";
4113     const std::vector<std::string> servers = {listen_addr};
4114 
4115     test::DNSResponder dns(listen_addr);
4116     StartDns(dns, {{dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"}});
4117     test::DnsTlsFrontend tls(listen_addr, "853", listen_addr, "53");
4118     ASSERT_TRUE(tls.startServer());
4119 
4120     for (const std::string_view dnsMode : {"OPPORTUNISTIC", "STRICT"}) {
4121         SCOPED_TRACE(fmt::format("testConfig: [{}]", dnsMode));
4122         auto builder = ResolverParams::Builder().setDnsServers(servers).setDotServers(servers);
4123         if (dnsMode == "STRICT") {
4124             builder.setPrivateDnsProvider(kDefaultPrivateDnsHostName);
4125         }
4126         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(builder.build()));
4127         EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
4128         EXPECT_TRUE(tls.waitForQueries(1));
4129         tls.clearQueries();
4130 
4131         // Start NAT64 prefix discovery.
4132         EXPECT_TRUE(mDnsClient.resolvService()->startPrefix64Discovery(TEST_NETID).isOk());
4133         EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
4134 
4135         // Verify that the DNS query for the NAT64 prefix bypassed private DNS.
4136         EXPECT_EQ(0, tls.queries()) << dns.dumpQueries();
4137         EXPECT_EQ(1U, GetNumQueries(dns, dns64_name)) << dns.dumpQueries();
4138 
4139         // Stop the prefix discovery to make DnsResolver send the prefix-removed event
4140         // earlier. Without this, DnsResolver still sends the event once the network
4141         // is destroyed; however, it will fail the next test if the test unexpectedly
4142         // receives the event that it doesn't want.
4143         EXPECT_TRUE(mDnsClient.resolvService()->stopPrefix64Discovery(TEST_NETID).isOk());
4144         EXPECT_TRUE(WaitForNat64Prefix(EXPECT_NOT_FOUND));
4145 
4146         dns.clearQueries();
4147         EXPECT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
4148     }
4149 
4150     EXPECT_EQ(0, sDnsMetricsListener->getUnexpectedNat64PrefixUpdates());
4151     EXPECT_EQ(0, sUnsolicitedEventListener->getUnexpectedNat64PrefixUpdates());
4152 }
4153 
TEST_F(ResolverTest,SetAndClearNat64Prefix)4154 TEST_F(ResolverTest, SetAndClearNat64Prefix) {
4155     constexpr char host_name[] = "v4.example.com.";
4156     constexpr char listen_addr[] = "::1";
4157     const std::vector<DnsRecord> records = {
4158             {host_name, ns_type::ns_t_a, "1.2.3.4"},
4159     };
4160 
4161     test::DNSResponder dns(listen_addr);
4162     StartDns(dns, records);
4163     const std::vector<std::string> servers = {listen_addr};
4164     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
4165 
4166     auto resolvService = mDnsClient.resolvService();
4167     addrinfo hints = {.ai_family = AF_INET6};
4168 
4169     // No NAT64 prefix, no AAAA record.
4170     ScopedAddrinfo result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
4171     ASSERT_TRUE(result == nullptr);
4172 
4173     // Set the prefix, and expect to get a synthesized AAAA record.
4174     EXPECT_TRUE(resolvService->setPrefix64(TEST_NETID, kNat64Prefix2).isOk());
4175     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
4176     ASSERT_FALSE(result == nullptr);
4177     EXPECT_EQ("2001:db8:6464::102:304", ToString(result));
4178 
4179     // Update the prefix, expect to see AAAA records from the new prefix.
4180     EXPECT_TRUE(resolvService->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
4181     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
4182     ASSERT_FALSE(result == nullptr);
4183     EXPECT_EQ("64:ff9b::102:304", ToString(result));
4184 
4185     // Non-/96 prefixes are ignored.
4186     auto status = resolvService->setPrefix64(TEST_NETID, "64:ff9b::/64");
4187     EXPECT_FALSE(status.isOk());
4188     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
4189     EXPECT_EQ(EINVAL, status.getServiceSpecificError());
4190 
4191     // Invalid prefixes are ignored.
4192     status = resolvService->setPrefix64(TEST_NETID, "192.0.2.0/24");
4193     EXPECT_FALSE(status.isOk());
4194     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
4195     EXPECT_EQ(EINVAL, status.getServiceSpecificError());
4196 
4197     status = resolvService->setPrefix64(TEST_NETID, "192.0.2.1");
4198     EXPECT_FALSE(status.isOk());
4199     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
4200     EXPECT_EQ(EINVAL, status.getServiceSpecificError());
4201 
4202     status = resolvService->setPrefix64(TEST_NETID, "hello");
4203     EXPECT_FALSE(status.isOk());
4204     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
4205     EXPECT_EQ(EINVAL, status.getServiceSpecificError());
4206 
4207     // DNS64 synthesis is still working.
4208     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
4209     ASSERT_FALSE(result == nullptr);
4210     EXPECT_EQ("64:ff9b::102:304", ToString(result));
4211 
4212     // Clear the prefix. No AAAA records any more.
4213     EXPECT_TRUE(resolvService->setPrefix64(TEST_NETID, "").isOk());
4214     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
4215     EXPECT_TRUE(result == nullptr);
4216 
4217     // Calling startPrefix64Discovery clears the prefix.
4218     EXPECT_TRUE(resolvService->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
4219     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
4220     ASSERT_FALSE(result == nullptr);
4221     EXPECT_EQ("64:ff9b::102:304", ToString(result));
4222 
4223     EXPECT_TRUE(resolvService->startPrefix64Discovery(TEST_NETID).isOk());
4224     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
4225     ASSERT_TRUE(result == nullptr);
4226 
4227     // setPrefix64 fails if prefix discovery is started, even if no prefix is yet discovered...
4228     status = resolvService->setPrefix64(TEST_NETID, kNat64Prefix);
4229     EXPECT_FALSE(status.isOk());
4230     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
4231     EXPECT_EQ(EEXIST, status.getServiceSpecificError());
4232 
4233     // .. and clearing the prefix also has no effect.
4234     status = resolvService->setPrefix64(TEST_NETID, "");
4235     EXPECT_FALSE(status.isOk());
4236     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
4237     EXPECT_EQ(ENOENT, status.getServiceSpecificError());
4238 
4239     // setPrefix64 succeeds again when prefix discovery is stopped.
4240     EXPECT_TRUE(resolvService->stopPrefix64Discovery(TEST_NETID).isOk());
4241     EXPECT_TRUE(resolvService->setPrefix64(TEST_NETID, kNat64Prefix).isOk());
4242     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
4243     ASSERT_FALSE(result == nullptr);
4244     EXPECT_EQ("64:ff9b::102:304", ToString(result));
4245 
4246     // Calling stopPrefix64Discovery clears the prefix.
4247     EXPECT_TRUE(resolvService->stopPrefix64Discovery(TEST_NETID).isOk());
4248     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
4249     ASSERT_TRUE(result == nullptr);
4250 
4251     // Set up NAT64 prefix discovery.
4252     constexpr char dns64_name[] = "ipv4only.arpa.";
4253     const std::vector<DnsRecord> newRecords = {
4254             {host_name, ns_type::ns_t_a, "1.2.3.4"},
4255             {dns64_name, ns_type::ns_t_aaaa, "64:ff9b::192.0.0.170"},
4256     };
4257     dns.stopServer();
4258     StartDns(dns, newRecords);
4259 
4260     EXPECT_TRUE(resolvService->startPrefix64Discovery(TEST_NETID).isOk());
4261     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_FOUND));
4262     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
4263     ASSERT_FALSE(result == nullptr);
4264     EXPECT_EQ("64:ff9b::102:304", ToString(result));
4265 
4266     // setPrefix64 fails if NAT64 prefix discovery has succeeded, and the discovered prefix
4267     // continues to be used.
4268     status = resolvService->setPrefix64(TEST_NETID, kNat64Prefix2);
4269     EXPECT_FALSE(status.isOk());
4270     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
4271     EXPECT_EQ(EEXIST, status.getServiceSpecificError());
4272 
4273     // Clearing the prefix also has no effect if discovery is started.
4274     status = resolvService->setPrefix64(TEST_NETID, "");
4275     EXPECT_FALSE(status.isOk());
4276     EXPECT_EQ(EX_SERVICE_SPECIFIC, status.getExceptionCode());
4277     EXPECT_EQ(ENOENT, status.getServiceSpecificError());
4278 
4279     result = safe_getaddrinfo("v4.example.com", nullptr, &hints);
4280     ASSERT_FALSE(result == nullptr);
4281     EXPECT_EQ("64:ff9b::102:304", ToString(result));
4282 
4283     EXPECT_TRUE(resolvService->stopPrefix64Discovery(TEST_NETID).isOk());
4284     EXPECT_TRUE(WaitForNat64Prefix(EXPECT_NOT_FOUND));
4285 
4286     EXPECT_EQ(0, sDnsMetricsListener->getUnexpectedNat64PrefixUpdates());
4287     EXPECT_EQ(0, sUnsolicitedEventListener->getUnexpectedNat64PrefixUpdates());
4288 }
4289 
4290 namespace {
4291 
4292 class ScopedSetNetworkForProcess {
4293   public:
ScopedSetNetworkForProcess(unsigned netId)4294     explicit ScopedSetNetworkForProcess(unsigned netId) {
4295         mStoredNetId = getNetworkForProcess();
4296         if (netId == mStoredNetId) return;
4297         EXPECT_EQ(0, setNetworkForProcess(netId));
4298     }
~ScopedSetNetworkForProcess()4299     ~ScopedSetNetworkForProcess() { EXPECT_EQ(0, setNetworkForProcess(mStoredNetId)); }
4300 
4301   private:
4302     unsigned mStoredNetId;
4303 };
4304 
4305 class ScopedSetNetworkForResolv {
4306   public:
ScopedSetNetworkForResolv(unsigned netId)4307     explicit ScopedSetNetworkForResolv(unsigned netId) { EXPECT_EQ(0, setNetworkForResolv(netId)); }
~ScopedSetNetworkForResolv()4308     ~ScopedSetNetworkForResolv() { EXPECT_EQ(0, setNetworkForResolv(NETID_UNSET)); }
4309 };
4310 
sendCommand(int fd,const std::string & cmd)4311 void sendCommand(int fd, const std::string& cmd) {
4312     ssize_t rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size() + 1));
4313     EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size() + 1));
4314 }
4315 
readBE32(int fd)4316 int32_t readBE32(int fd) {
4317     int32_t tmp;
4318     int n = TEMP_FAILURE_RETRY(read(fd, &tmp, sizeof(tmp)));
4319     EXPECT_TRUE(n > 0);
4320     return ntohl(tmp);
4321 }
4322 
readResponseCode(int fd)4323 int readResponseCode(int fd) {
4324     char buf[4];
4325     int n = TEMP_FAILURE_RETRY(read(fd, &buf, sizeof(buf)));
4326     EXPECT_TRUE(n > 0);
4327     // The format of response code is that 4 bytes for the code & null.
4328     buf[3] = '\0';
4329     int result;
4330     EXPECT_TRUE(ParseInt(buf, &result));
4331     return result;
4332 }
4333 
checkAndClearUseLocalNameserversFlag(unsigned * netid)4334 bool checkAndClearUseLocalNameserversFlag(unsigned* netid) {
4335     if (netid == nullptr || ((*netid) & NETID_USE_LOCAL_NAMESERVERS) == 0) {
4336         return false;
4337     }
4338     *netid = (*netid) & ~NETID_USE_LOCAL_NAMESERVERS;
4339     return true;
4340 }
4341 
makeUidRangeParcel(int start,int stop)4342 aidl::android::net::UidRangeParcel makeUidRangeParcel(int start, int stop) {
4343     aidl::android::net::UidRangeParcel res;
4344     res.start = start;
4345     res.stop = stop;
4346 
4347     return res;
4348 }
4349 
expectNetIdWithLocalNameserversFlag(unsigned netId)4350 void expectNetIdWithLocalNameserversFlag(unsigned netId) {
4351     unsigned dnsNetId = 0;
4352     EXPECT_EQ(0, getNetworkForDns(&dnsNetId));
4353     EXPECT_TRUE(checkAndClearUseLocalNameserversFlag(&dnsNetId));
4354     EXPECT_EQ(netId, static_cast<unsigned>(dnsNetId));
4355 }
4356 
expectDnsNetIdEquals(unsigned netId)4357 void expectDnsNetIdEquals(unsigned netId) {
4358     unsigned dnsNetId = 0;
4359     EXPECT_EQ(0, getNetworkForDns(&dnsNetId));
4360     EXPECT_EQ(netId, static_cast<unsigned>(dnsNetId));
4361 }
4362 
expectDnsNetIdIsDefaultNetwork(INetd * netdService)4363 void expectDnsNetIdIsDefaultNetwork(INetd* netdService) {
4364     int currentNetid;
4365     EXPECT_TRUE(netdService->networkGetDefault(&currentNetid).isOk());
4366     expectDnsNetIdEquals(currentNetid);
4367 }
4368 
expectDnsNetIdWithVpn(INetd * netdService,unsigned vpnNetId,unsigned expectedNetId)4369 void expectDnsNetIdWithVpn(INetd* netdService, unsigned vpnNetId, unsigned expectedNetId) {
4370     if (DnsResponderClient::isRemoteVersionSupported(netdService, 6)) {
4371         const auto& config = DnsResponderClient::makeNativeNetworkConfig(
4372                 vpnNetId, NativeNetworkType::VIRTUAL, INetd::PERMISSION_NONE, /*secure=*/false);
4373         EXPECT_TRUE(netdService->networkCreate(config).isOk());
4374     } else {
4375 #pragma clang diagnostic push
4376 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
4377         EXPECT_TRUE(netdService->networkCreateVpn(vpnNetId, false /* secure */).isOk());
4378 #pragma clang diagnostic pop
4379     }
4380 
4381     uid_t uid = getuid();
4382     // Add uid to VPN
4383     EXPECT_TRUE(netdService->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
4384     expectDnsNetIdEquals(expectedNetId);
4385     EXPECT_TRUE(netdService->networkDestroy(vpnNetId).isOk());
4386 }
4387 
4388 }  // namespace
4389 
TEST_F(ResolverTest,getDnsNetId)4390 TEST_F(ResolverTest, getDnsNetId) {
4391     // We've called setNetworkForProcess in SetupOemNetwork, so reset to default first.
4392     setNetworkForProcess(NETID_UNSET);
4393 
4394     expectDnsNetIdIsDefaultNetwork(mDnsClient.netdService());
4395     expectDnsNetIdWithVpn(mDnsClient.netdService(), TEST_VPN_NETID, TEST_VPN_NETID);
4396 
4397     // Test with setNetworkForProcess
4398     {
4399         ScopedSetNetworkForProcess scopedSetNetworkForProcess(TEST_NETID);
4400         expectDnsNetIdEquals(TEST_NETID);
4401     }
4402 
4403     // Test with setNetworkForProcess with NETID_USE_LOCAL_NAMESERVERS
4404     {
4405         ScopedSetNetworkForProcess scopedSetNetworkForProcess(TEST_NETID |
4406                                                               NETID_USE_LOCAL_NAMESERVERS);
4407         expectNetIdWithLocalNameserversFlag(TEST_NETID);
4408     }
4409 
4410     // Test with setNetworkForResolv
4411     {
4412         ScopedSetNetworkForResolv scopedSetNetworkForResolv(TEST_NETID);
4413         expectDnsNetIdEquals(TEST_NETID);
4414     }
4415 
4416     // Test with setNetworkForResolv with NETID_USE_LOCAL_NAMESERVERS
4417     {
4418         ScopedSetNetworkForResolv scopedSetNetworkForResolv(TEST_NETID |
4419                                                             NETID_USE_LOCAL_NAMESERVERS);
4420         expectNetIdWithLocalNameserversFlag(TEST_NETID);
4421     }
4422 
4423     // Test with setNetworkForResolv under bypassable vpn
4424     {
4425         ScopedSetNetworkForResolv scopedSetNetworkForResolv(TEST_NETID);
4426         expectDnsNetIdWithVpn(mDnsClient.netdService(), TEST_VPN_NETID, TEST_NETID);
4427     }
4428 
4429     // Create socket connected to DnsProxyListener
4430     int fd = dns_open_proxy();
4431     EXPECT_TRUE(fd > 0);
4432     unique_fd ufd(fd);
4433 
4434     // Test command with wrong netId
4435     sendCommand(fd, "getdnsnetid abc");
4436     EXPECT_EQ(ResponseCode::DnsProxyQueryResult, readResponseCode(fd));
4437     EXPECT_EQ(-EINVAL, readBE32(fd));
4438 
4439     // Test unsupported command
4440     sendCommand(fd, "getdnsnetidNotSupported");
4441     // Keep in sync with FrameworkListener.cpp (500, "Command not recognized")
4442     EXPECT_EQ(500, readResponseCode(fd));
4443 }
4444 
TEST_F(ResolverTest,BlockDnsQueryWithUidRule)4445 TEST_F(ResolverTest, BlockDnsQueryWithUidRule) {
4446     SKIP_IF_BPF_NOT_SUPPORTED;
4447     constexpr char listen_addr1[] = "127.0.0.4";
4448     constexpr char listen_addr2[] = "::1";
4449     constexpr char host_name[] = "howdy.example.com.";
4450     const std::vector<DnsRecord> records = {
4451             {host_name, ns_type::ns_t_a, "1.2.3.4"},
4452             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
4453     };
4454     INetd* netdService = mDnsClient.netdService();
4455 
4456     test::DNSResponder dns1(listen_addr1);
4457     test::DNSResponder dns2(listen_addr2);
4458     StartDns(dns1, records);
4459     StartDns(dns2, records);
4460 
4461     std::vector<std::string> servers = {listen_addr1, listen_addr2};
4462     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
4463     dns1.clearQueries();
4464     dns2.clearQueries();
4465 
4466     ScopeBlockedUIDRule scopeBlockUidRule(netdService, TEST_UID);
4467     // Dns Query
4468     int fd1 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_a, 0);
4469     int fd2 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_aaaa, 0);
4470     EXPECT_TRUE(fd1 != -1);
4471     EXPECT_TRUE(fd2 != -1);
4472 
4473     uint8_t buf1[MAXPACKET] = {};
4474     uint8_t buf2[MAXPACKET] = {};
4475     int rcode;
4476     int res2 = getAsyncResponse(fd2, &rcode, buf2, MAXPACKET);
4477     int res1 = getAsyncResponse(fd1, &rcode, buf1, MAXPACKET);
4478     // If API level >= 30 (R+), these queries should be blocked.
4479     if (isAtLeastR) {
4480         EXPECT_EQ(res2, -ECONNREFUSED);
4481         EXPECT_EQ(res1, -ECONNREFUSED);
4482         ExpectDnsEvent(INetdEventListener::EVENT_RES_NSEND, EAI_SYSTEM, "howdy.example.com", {});
4483         ExpectDnsEvent(INetdEventListener::EVENT_RES_NSEND, EAI_SYSTEM, "howdy.example.com", {});
4484     } else {
4485         EXPECT_GT(res2, 0);
4486         EXPECT_EQ("::1.2.3.4", toString(buf2, res2, AF_INET6));
4487         EXPECT_GT(res1, 0);
4488         EXPECT_EQ("1.2.3.4", toString(buf1, res1, AF_INET));
4489         // To avoid flaky test, do not evaluate DnsEvent since event order is not guaranteed.
4490     }
4491 }
4492 
TEST_F(ResolverTest,GetAddrinfo_BlockDnsQueryWithUidRule)4493 TEST_F(ResolverTest, GetAddrinfo_BlockDnsQueryWithUidRule) {
4494     SKIP_IF_BPF_NOT_SUPPORTED;
4495     constexpr char listen_addr1[] = "127.0.0.4";
4496     constexpr char listen_addr2[] = "::1";
4497     constexpr char host_name[] = "howdy.example.com.";
4498     const std::vector<DnsRecord> records = {
4499             {host_name, ns_type::ns_t_a, "1.2.3.4"},
4500             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
4501     };
4502     test::DNSResponder dns1(listen_addr1);
4503     test::DNSResponder dns2(listen_addr2);
4504     StartDns(dns1, records);
4505     StartDns(dns2, records);
4506 
4507     std::vector<std::string> servers = {listen_addr1, listen_addr2};
4508     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
4509 
4510     const addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM};
4511 
4512     static struct {
4513         const char* hname;
4514         const int expectedErrorCode;
4515     } kTestData[] = {
4516             {host_name, (isAtLeastT() && fs::exists(DNS_HELPER)) ? EAI_FAIL : EAI_NODATA},
4517             // To test the query with search domain.
4518             {"howdy", (isAtLeastT() && fs::exists(DNS_HELPER)) ? EAI_FAIL : EAI_AGAIN},
4519     };
4520 
4521     INetd* netdService = mDnsClient.netdService();
4522     for (auto& td : kTestData) {
4523         SCOPED_TRACE(td.hname);
4524         ScopeBlockedUIDRule scopeBlockUidRule(netdService, TEST_UID);
4525         // If API level >= 30 (R+), these queries should be blocked.
4526         if (isAtLeastR) {
4527             addrinfo* result = nullptr;
4528             // getaddrinfo() in bionic would convert all errors to EAI_NODATA
4529             // except EAI_SYSTEM.
4530             EXPECT_EQ(EAI_NODATA, getaddrinfo(td.hname, nullptr, &hints, &result));
4531             ExpectDnsEvent(INetdEventListener::EVENT_GETADDRINFO, td.expectedErrorCode, td.hname,
4532                            {});
4533         } else {
4534             ScopedAddrinfo result = safe_getaddrinfo(td.hname, nullptr, &hints);
4535             EXPECT_NE(nullptr, result);
4536             EXPECT_THAT(ToStrings(result),
4537                         testing::UnorderedElementsAreArray({"1.2.3.4", "::1.2.3.4"}));
4538             // To avoid flaky test, do not evaluate DnsEvent since event order is not guaranteed.
4539         }
4540     }
4541 }
4542 
TEST_F(ResolverTest,EnforceDnsUid)4543 TEST_F(ResolverTest, EnforceDnsUid) {
4544     SKIP_IF_BPF_NOT_SUPPORTED;
4545     constexpr char listen_addr1[] = "127.0.0.4";
4546     constexpr char listen_addr2[] = "::1";
4547     constexpr char host_name[] = "howdy.example.com.";
4548     const std::vector<DnsRecord> records = {
4549             {host_name, ns_type::ns_t_a, "1.2.3.4"},
4550             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
4551     };
4552     INetd* netdService = mDnsClient.netdService();
4553 
4554     test::DNSResponder dns1(listen_addr1);
4555     test::DNSResponder dns2(listen_addr2);
4556     StartDns(dns1, records);
4557     StartDns(dns2, records);
4558 
4559     // switch uid of DNS queries from applications to AID_DNS
4560     ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
4561     parcel.servers = {listen_addr1, listen_addr2};
4562     ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(parcel).isOk());
4563 
4564     uint8_t buf[MAXPACKET] = {};
4565     uint8_t buf2[MAXPACKET] = {};
4566     int rcode;
4567     {
4568         ScopeBlockedUIDRule scopeBlockUidRule(netdService, TEST_UID);
4569         // Dns Queries should be blocked
4570         const int fd1 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_a, 0);
4571         const int fd2 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_aaaa, 0);
4572         EXPECT_TRUE(fd1 != -1);
4573         EXPECT_TRUE(fd2 != -1);
4574 
4575         const int res2 = getAsyncResponse(fd2, &rcode, buf2, MAXPACKET);
4576         const int res1 = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
4577         // If API level >= 30 (R+), the query should be blocked.
4578         if (isAtLeastR) {
4579             EXPECT_EQ(res2, -ECONNREFUSED);
4580             EXPECT_EQ(res1, -ECONNREFUSED);
4581         } else {
4582             EXPECT_GT(res2, 0);
4583             EXPECT_EQ("::1.2.3.4", toString(buf2, res2, AF_INET6));
4584             EXPECT_GT(res1, 0);
4585             EXPECT_EQ("1.2.3.4", toString(buf, res1, AF_INET));
4586         }
4587     }
4588 
4589     memset(buf, 0, MAXPACKET);
4590     ResolverOptionsParcel resolverOptions;
4591     resolverOptions.enforceDnsUid = true;
4592     if (!mIsResolverOptionIPCSupported) {
4593         parcel.resolverOptions = resolverOptions;
4594         ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(parcel).isOk());
4595     } else {
4596         ASSERT_TRUE(mDnsClient.resolvService()
4597                             ->setResolverOptions(parcel.netId, resolverOptions)
4598                             .isOk());
4599     }
4600 
4601     {
4602         ScopeBlockedUIDRule scopeBlockUidRule(netdService, TEST_UID);
4603         // Dns Queries should NOT be blocked
4604         int fd1 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_a, 0);
4605         int fd2 = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_aaaa, 0);
4606         EXPECT_TRUE(fd1 != -1);
4607         EXPECT_TRUE(fd2 != -1);
4608 
4609         int res = getAsyncResponse(fd2, &rcode, buf, MAXPACKET);
4610         EXPECT_EQ("::1.2.3.4", toString(buf, res, AF_INET6));
4611 
4612         memset(buf, 0, MAXPACKET);
4613         res = getAsyncResponse(fd1, &rcode, buf, MAXPACKET);
4614         EXPECT_EQ("1.2.3.4", toString(buf, res, AF_INET));
4615 
4616         // @TODO: So far we know that uid of DNS queries are no more set to DNS requester. But we
4617         // don't check if they are actually being set to AID_DNS, because system uids are always
4618         // allowed in bpf_owner_match(). Audit by firewallSetUidRule(AID_DNS) + sending queries is
4619         // infeasible. Fix it if the behavior of bpf_owner_match() is changed in the future, or if
4620         // we have better idea to deal with this.
4621     }
4622 }
4623 
TEST_F(ResolverTest,ConnectTlsServerTimeout)4624 TEST_F(ResolverTest, ConnectTlsServerTimeout) {
4625     constexpr char hostname1[] = "query1.example.com.";
4626     constexpr char hostname2[] = "query2.example.com.";
4627     const std::vector<DnsRecord> records = {
4628             {hostname1, ns_type::ns_t_a, "1.2.3.4"},
4629             {hostname2, ns_type::ns_t_a, "1.2.3.5"},
4630     };
4631 
4632     // TODO: Remove it after b/254186357 is clarified.
4633     ASSERT_TRUE(mDnsClient.resolvService()
4634                         ->setLogSeverity(aidl::android::net::IDnsResolver::DNS_RESOLVER_LOG_VERBOSE)
4635                         .isOk());
4636 
4637     static const struct TestConfig {
4638         bool asyncHandshake;
4639         int maxRetries;
4640 
4641         // if asyncHandshake:
4642         //   expectedTimeout = Min(DotQueryTimeoutMs, dotConnectTimeoutMs * maxRetries)
4643         // otherwise:
4644         //   expectedTimeout = dotConnectTimeoutMs
4645         int expectedTimeout;
4646     } testConfigs[] = {
4647             // Test mis-configured dot_maxtries flag.
4648             {false, 0, 1000}, {true, 0, 1000},
4649 
4650             {false, 1, 1000}, {false, 3, 1000}, {true, 1, 1000}, {true, 3, 3000},
4651     };
4652 
4653     for (const auto& config : testConfigs) {
4654         SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", config.asyncHandshake, config.maxRetries));
4655 
4656         // Because a DnsTlsTransport lasts at least 5 minutes in spite of network
4657         // destroyed, let the resolver creates an unique DnsTlsTransport every time
4658         // so that the DnsTlsTransport won't interfere the other tests.
4659         const std::string addr = getUniqueIPv4Address();
4660         test::DNSResponder dns(addr);
4661         StartDns(dns, records);
4662         test::DnsTlsFrontend tls(addr, "853", addr, "53");
4663         ASSERT_TRUE(tls.startServer());
4664 
4665         // The resolver will adjust the timeout value to 1000ms since the value is too small.
4666         ScopedSystemProperties sp1(kDotConnectTimeoutMsFlag, "100");
4667 
4668         // Infinite timeout.
4669         ScopedSystemProperties sp2(kDotQueryTimeoutMsFlag, "-1");
4670 
4671         ScopedSystemProperties sp3(kDotAsyncHandshakeFlag, config.asyncHandshake ? "1" : "0");
4672         ScopedSystemProperties sp4(kDotMaxretriesFlag, std::to_string(config.maxRetries));
4673 
4674         // Don't skip unusable DoT servers and disable revalidation for this test.
4675         ScopedSystemProperties sp5(kDotXportUnusableThresholdFlag, "-1");
4676         ScopedSystemProperties sp6(kDotRevalidationThresholdFlag, "-1");
4677         resetNetwork();
4678 
4679         // Set up resolver to opportunistic mode.
4680         auto parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
4681         parcel.servers = {addr};
4682         parcel.tlsServers = {addr};
4683         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
4684         EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
4685         EXPECT_TRUE(tls.waitForQueries(1));
4686         tls.clearQueries();
4687         dns.clearQueries();
4688 
4689         // The server becomes unresponsive to the handshake request.
4690         tls.setHangOnHandshakeForTesting(true);
4691 
4692         // Expect the things happening in getaddrinfo():
4693         //   1. Connect to the private DNS server.
4694         //   2. SSL handshake times out.
4695         //   3. Fallback to UDP transport, and then get the answer.
4696         const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
4697         auto [result, timeTakenMs] = safe_getaddrinfo_time_taken(hostname1, nullptr, hints);
4698 
4699         EXPECT_NE(nullptr, result);
4700         EXPECT_EQ(0, tls.queries());
4701         EXPECT_EQ(1U, GetNumQueries(dns, hostname1));
4702         EXPECT_EQ(records.at(0).addr, ToString(result));
4703 
4704         // A loose upper bound is set by adding 1000ms buffer time. Theoretically, getaddrinfo()
4705         // should just take a bit more than expetTimeout milliseconds.
4706         EXPECT_GE(timeTakenMs, config.expectedTimeout);
4707         EXPECT_LE(timeTakenMs, config.expectedTimeout + 1000);
4708 
4709         // Set the server to be responsive. Verify that the resolver will attempt to reconnect
4710         // to the server and then get the result within the timeout.
4711         tls.setHangOnHandshakeForTesting(false);
4712         std::tie(result, timeTakenMs) = safe_getaddrinfo_time_taken(hostname2, nullptr, hints);
4713 
4714         EXPECT_NE(nullptr, result);
4715         EXPECT_TRUE(tls.waitForQueries(1));
4716         EXPECT_EQ(1U, GetNumQueries(dns, hostname2));
4717         EXPECT_EQ(records.at(1).addr, ToString(result));
4718 
4719         EXPECT_LE(timeTakenMs, 1000);
4720     }
4721 
4722     // TODO: Remove it after b/254186357 is clarified.
4723     ASSERT_TRUE(mDnsClient.resolvService()
4724                         ->setLogSeverity(aidl::android::net::IDnsResolver::DNS_RESOLVER_LOG_INFO)
4725                         .isOk());
4726 }
4727 
TEST_F(ResolverTest,ConnectTlsServerTimeout_ConcurrentQueries)4728 TEST_F(ResolverTest, ConnectTlsServerTimeout_ConcurrentQueries) {
4729     constexpr uint32_t cacheFlag = ANDROID_RESOLV_NO_CACHE_LOOKUP;
4730     constexpr char hostname[] = "hello.example.com.";
4731     const std::vector<DnsRecord> records = {
4732             {hostname, ns_type::ns_t_a, "1.2.3.4"},
4733     };
4734     int testConfigCount = 0;
4735 
4736     static const struct TestConfig {
4737         bool asyncHandshake;
4738         int dotConnectTimeoutMs;
4739         int dotQueryTimeoutMs;
4740         int maxRetries;
4741         int concurrency;
4742 
4743         // if asyncHandshake:
4744         //   expectedTimeout = Min(DotQueryTimeoutMs, dotConnectTimeoutMs * maxRetries)
4745         // otherwise:
4746         //   expectedTimeout = dotConnectTimeoutMs * concurrency
4747         int expectedTimeout;
4748     } testConfigs[] = {
4749             // clang-format off
4750             {false, 1000, 3000, 1, 5,  5000},
4751             {false, 1000, 3000, 3, 5,  5000},
4752             {false, 2000, 1500, 3, 2,  4000},
4753             {true,  1000, 3000, 1, 5,  1000},
4754             {true,  2500, 1500, 1, 10, 1500},
4755             {true,  1000, 5000, 3, 5,  3000},
4756             // clang-format on
4757     };
4758 
4759     // Launch query threads. Expected behaviors are:
4760     // - when dot_async_handshake is disabled, one of the query threads triggers a
4761     //   handshake and then times out. Then same as another query thread, and so forth.
4762     // - when dot_async_handshake is enabled, only one handshake is triggered, and then
4763     //   all of the query threads time out at the same time.
4764     for (const auto& config : testConfigs) {
4765         testConfigCount++;
4766         ScopedSystemProperties sp1(kDotQueryTimeoutMsFlag,
4767                                    std::to_string(config.dotQueryTimeoutMs));
4768         ScopedSystemProperties sp2(kDotConnectTimeoutMsFlag,
4769                                    std::to_string(config.dotConnectTimeoutMs));
4770         ScopedSystemProperties sp3(kDotAsyncHandshakeFlag, config.asyncHandshake ? "1" : "0");
4771         ScopedSystemProperties sp4(kDotMaxretriesFlag, std::to_string(config.maxRetries));
4772 
4773         // Don't skip unusable DoT servers and disable revalidation for this test.
4774         ScopedSystemProperties sp5(kDotXportUnusableThresholdFlag, "-1");
4775         ScopedSystemProperties sp6(kDotRevalidationThresholdFlag, "-1");
4776         resetNetwork();
4777 
4778         for (const std::string_view dnsMode : {"OPPORTUNISTIC", "STRICT"}) {
4779             SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", testConfigCount, dnsMode));
4780 
4781             // Because a DnsTlsTransport lasts at least 5 minutes in spite of network
4782             // destroyed, let the resolver creates an unique DnsTlsTransport every time
4783             // so that the DnsTlsTransport won't interfere the other tests.
4784             const std::string addr = getUniqueIPv4Address();
4785             test::DNSResponder dns(addr);
4786             StartDns(dns, records);
4787             test::DnsTlsFrontend tls(addr, "853", addr, "53");
4788             ASSERT_TRUE(tls.startServer());
4789 
4790             auto parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
4791             parcel.servers = {addr};
4792             parcel.tlsServers = {addr};
4793             if (dnsMode == "STRICT") parcel.tlsName = kDefaultPrivateDnsHostName;
4794             ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
4795             EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
4796             EXPECT_TRUE(tls.waitForQueries(1));
4797 
4798             // The server becomes unresponsive to the handshake request.
4799             tls.setHangOnHandshakeForTesting(true);
4800 
4801             Stopwatch s;
4802             std::vector<std::thread> threads(config.concurrency);
4803             for (std::thread& thread : threads) {
4804                 thread = std::thread([&]() {
4805                     int fd = resNetworkQuery(TEST_NETID, hostname, ns_c_in, ns_t_a, cacheFlag);
4806                     dnsMode == "STRICT" ? expectAnswersNotValid(fd, -ETIMEDOUT)
4807                                         : expectAnswersValid(fd, AF_INET, "1.2.3.4");
4808                 });
4809             }
4810             for (std::thread& thread : threads) {
4811                 thread.join();
4812             }
4813 
4814             const int timeTakenMs = s.timeTakenUs() / 1000;
4815             // A loose upper bound is set by adding 1000ms buffer time. Theoretically, it should
4816             // just take a bit more than expetTimeout milliseconds for the result.
4817             EXPECT_GE(timeTakenMs, config.expectedTimeout);
4818             EXPECT_LE(timeTakenMs, config.expectedTimeout + 1000);
4819 
4820             // Recover the server from being unresponsive and try again.
4821             tls.setHangOnHandshakeForTesting(false);
4822             int fd = resNetworkQuery(TEST_NETID, hostname, ns_c_in, ns_t_a, cacheFlag);
4823             if (dnsMode == "STRICT" && config.asyncHandshake &&
4824                 config.dotQueryTimeoutMs < (config.dotConnectTimeoutMs * config.maxRetries)) {
4825                 // In this case, the connection handshake is supposed to be in progress. Queries
4826                 // sent before the handshake finishes will time out (either due to connect timeout
4827                 // or query timeout).
4828                 expectAnswersNotValid(fd, -ETIMEDOUT);
4829             } else {
4830                 expectAnswersValid(fd, AF_INET, "1.2.3.4");
4831             }
4832         }
4833     }
4834 }
4835 
4836 // Tests that the DoT query timeout is configurable via the feature flag "dot_query_timeout_ms".
4837 // The test DoT server is configured to postpone DNS queries for DOT_SERVER_UNRESPONSIVE_TIME_MS
4838 // (2s). If the feature flag is set to a positive value smaller than
4839 // DOT_SERVER_UNRESPONSIVE_TIME_MS, DoT queries should timeout.
TEST_F(ResolverTest,QueryTlsServerTimeout)4840 TEST_F(ResolverTest, QueryTlsServerTimeout) {
4841     constexpr int DOT_SERVER_UNRESPONSIVE_TIME_MS = 2000;
4842     constexpr int TIMING_TOLERANCE_MS = 500;
4843     constexpr char hostname1[] = "query1.example.com.";
4844     const std::vector<DnsRecord> records = {
4845             {hostname1, ns_type::ns_t_a, "1.2.3.4"},
4846     };
4847 
4848     static const struct TestConfig {
4849         std::string dnsMode;
4850         int queryTimeoutMs;
4851         int expectResultTimedOut;
4852         int expectedTimeTakenMs;
4853     } testConfigs[] = {
4854             // clang-format off
4855             {"OPPORTUNISTIC",   -1, false, DOT_SERVER_UNRESPONSIVE_TIME_MS},
4856             {"OPPORTUNISTIC", 1000, false,                            1000},
4857             {"STRICT",          -1, false, DOT_SERVER_UNRESPONSIVE_TIME_MS},
4858             // `expectResultTimedOut` is true in the following testcase because in strict mode
4859             // DnsResolver doesn't try Do53 servers after the DoT query is timed out.
4860             {"STRICT",        1000,  true,                            1000},
4861             // clang-format on
4862     };
4863     for (const auto& config : testConfigs) {
4864         SCOPED_TRACE(fmt::format("testConfig: [{}] [{}]", config.dnsMode, config.queryTimeoutMs));
4865 
4866         const std::string addr = getUniqueIPv4Address();
4867         test::DNSResponder dns(addr);
4868         StartDns(dns, records);
4869         test::DnsTlsFrontend tls(addr, "853", addr, "53");
4870         ASSERT_TRUE(tls.startServer());
4871 
4872         ScopedSystemProperties sp(kDotQueryTimeoutMsFlag, std::to_string(config.queryTimeoutMs));
4873 
4874         // Don't skip unusable DoT servers and disable revalidation for this test.
4875         ScopedSystemProperties sp2(kDotXportUnusableThresholdFlag, "-1");
4876         ScopedSystemProperties sp3(kDotRevalidationThresholdFlag, "-1");
4877         resetNetwork();
4878 
4879         auto parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
4880         parcel.servers = {addr};
4881         parcel.tlsServers = {addr};
4882         if (config.dnsMode == "STRICT") parcel.tlsName = kDefaultPrivateDnsHostName;
4883 
4884         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
4885         EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
4886         EXPECT_TRUE(tls.waitForQueries(1));
4887         tls.clearQueries();
4888 
4889         // Set the DoT server to be unresponsive to DNS queries for
4890         // `DOT_SERVER_UNRESPONSIVE_TIME_MS` ms.
4891         tls.setDelayQueries(999);
4892         tls.setDelayQueriesTimeout(DOT_SERVER_UNRESPONSIVE_TIME_MS);
4893 
4894         // Send a DNS query, and then check the result and the response time.
4895         Stopwatch s;
4896         int fd = resNetworkQuery(TEST_NETID, hostname1, ns_c_in, ns_t_a,
4897                                  ANDROID_RESOLV_NO_CACHE_LOOKUP);
4898         if (config.expectResultTimedOut) {
4899             expectAnswersNotValid(fd, -ETIMEDOUT);
4900         } else {
4901             expectAnswersValid(fd, AF_INET, "1.2.3.4");
4902         }
4903         const int timeTakenMs = s.getTimeAndResetUs() / 1000;
4904         EXPECT_NEAR(config.expectedTimeTakenMs, timeTakenMs, TIMING_TOLERANCE_MS);
4905         EXPECT_TRUE(tls.waitForQueries(1));
4906     }
4907 }
4908 
4909 // Tests that the DnsResolver can skip using unusable DoT servers if dot_xport_unusable_threshold
4910 // flag is set. In this test, we make test DoT servers unresponsive during connection handshake,
4911 // so the DnsResolver will skip using a DoT server if the number of timed out queries reaches
4912 // the threshold.
TEST_F(ResolverTest,SkipUnusableTlsServer)4913 TEST_F(ResolverTest, SkipUnusableTlsServer) {
4914     constexpr int DOT_CONNECT_TIMEOUT_MS = 1000;
4915 
4916     static const struct TestConfig {
4917         int dotXportUnusableThreshold;
4918         int queries;
4919         int expectedQueriesSentToDot1;
4920         int expectedQueriesSentToDot2;
4921     } testConfigs[] = {
4922             // clang-format off
4923             // expectedQueriesSentToDot2 is 0 because dot_quick_fallback flag is set.
4924             {-1,  3, 3, 0},
4925             { 1,  3, 1, 1},
4926             { 3, 10, 3, 3},
4927             // clang-format on
4928     };
4929 
4930     for (const auto& config : testConfigs) {
4931         SCOPED_TRACE(fmt::format("testConfig: [{}, {}, {}, {}]", config.dotXportUnusableThreshold,
4932                                  config.queries, config.expectedQueriesSentToDot1,
4933                                  config.expectedQueriesSentToDot2));
4934 
4935         const std::string addr1 = getUniqueIPv4Address();
4936         const std::string addr2 = getUniqueIPv4Address();
4937         test::DNSResponder dns1(addr1);
4938         test::DNSResponder dns2(addr2);
4939         test::DnsTlsFrontend dot1(addr1, "853", addr1, "53");
4940         test::DnsTlsFrontend dot2(addr2, "853", addr2, "53");
4941         dns1.addMapping(kHelloExampleCom, ns_type::ns_t_aaaa, kHelloExampleComAddrV6);
4942         dns2.addMapping(kHelloExampleCom, ns_type::ns_t_aaaa, kHelloExampleComAddrV6);
4943         ASSERT_TRUE(dns1.startServer());
4944         ASSERT_TRUE(dns2.startServer());
4945         ASSERT_TRUE(dot1.startServer());
4946         ASSERT_TRUE(dot2.startServer());
4947 
4948         ScopedSystemProperties sp1(kDotConnectTimeoutMsFlag,
4949                                    std::to_string(DOT_CONNECT_TIMEOUT_MS));
4950         ScopedSystemProperties sp2(kDotXportUnusableThresholdFlag,
4951                                    std::to_string(config.dotXportUnusableThreshold));
4952         ScopedSystemProperties sp3(kDotQuickFallbackFlag, "1");
4953         ScopedSystemProperties sp4(kDotRevalidationThresholdFlag, "-1");
4954         resetNetwork();
4955 
4956         // Private DNS opportunistic mode.
4957         auto parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
4958         parcel.servers = {addr1, addr2};
4959         parcel.tlsServers = {addr1, addr2};
4960         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
4961 
4962         EXPECT_TRUE(WaitForPrivateDnsValidation(dot1.listen_address(), true));
4963         EXPECT_TRUE(WaitForPrivateDnsValidation(dot2.listen_address(), true));
4964         EXPECT_TRUE(dot1.waitForQueries(1));
4965         EXPECT_TRUE(dot2.waitForQueries(1));
4966         dot1.clearQueries();
4967         dot2.clearQueries();
4968         dot1.clearConnectionsCount();
4969         dot2.clearConnectionsCount();
4970 
4971         // Set the DoT servers as unresponsive to connection handshake.
4972         dot1.setHangOnHandshakeForTesting(true);
4973         dot2.setHangOnHandshakeForTesting(true);
4974 
4975         // Send sequential queries
4976         for (int i = 0; i < config.queries; i++) {
4977             int fd = resNetworkQuery(TEST_NETID, kHelloExampleCom, ns_c_in, ns_t_aaaa,
4978                                      ANDROID_RESOLV_NO_CACHE_LOOKUP);
4979             expectAnswersValid(fd, AF_INET6, kHelloExampleComAddrV6);
4980         }
4981 
4982         if (GetProperty(kDotAsyncHandshakeFlag, "0") == "0") {
4983             EXPECT_EQ(dot1.acceptConnectionsCount(), config.expectedQueriesSentToDot1);
4984             EXPECT_EQ(dot2.acceptConnectionsCount(), config.expectedQueriesSentToDot2);
4985         } else {
4986             // If the flag dot_async_handshake is set to 1, the DnsResolver will try
4987             // DoT connection establishment at most |retries| times.
4988             const int retries = std::stoi(GetProperty(kDotMaxretriesFlag, "3"));
4989             EXPECT_EQ(dot1.acceptConnectionsCount(), config.expectedQueriesSentToDot1 * retries);
4990             EXPECT_EQ(dot2.acceptConnectionsCount(), config.expectedQueriesSentToDot2 * retries);
4991         }
4992     }
4993 }
4994 
4995 // Verifies that the DnsResolver re-validates the DoT server when several DNS queries to
4996 // the server fails in a row.
TEST_F(ResolverTest,TlsServerRevalidation)4997 TEST_F(ResolverTest, TlsServerRevalidation) {
4998     constexpr uint32_t cacheFlag = ANDROID_RESOLV_NO_CACHE_LOOKUP;
4999     constexpr int dotXportUnusableThreshold = 10;
5000     constexpr int dotQueryTimeoutMs = 1000;
5001     constexpr char hostname[] = "hello.example.com.";
5002     const std::vector<DnsRecord> records = {
5003             {hostname, ns_type::ns_t_a, "1.2.3.4"},
5004     };
5005 
5006     static const struct TestConfig {
5007         std::string dnsMode;
5008         int validationThreshold;
5009         int queries;
5010 
5011         // Expected behavior in the DnsResolver.
5012         bool expectRevalidationHappen;
5013         bool expectDotUnusable;
5014     } testConfigs[] = {
5015             // clang-format off
5016             {"OPPORTUNISTIC", -1,  5, false, false},
5017             {"OPPORTUNISTIC", -1, 10, false,  true},
5018             {"OPPORTUNISTIC",  5,  5,  true, false},
5019             {"OPPORTUNISTIC",  5, 10,  true,  true},
5020             {"STRICT",        -1,  5, false, false},
5021             {"STRICT",        -1, 10, false, false},
5022             {"STRICT",         5,  5, false, false},
5023             {"STRICT",         5, 10, false, false},
5024             // clang-format on
5025     };
5026 
5027     for (const auto& config : testConfigs) {
5028         SCOPED_TRACE(fmt::format("testConfig: [{}, {}, {}]", config.dnsMode,
5029                                  config.validationThreshold, config.queries));
5030         const int queries = config.queries;
5031         const int delayQueriesTimeout = dotQueryTimeoutMs + 1000;
5032 
5033         ScopedSystemProperties sp1(kDotRevalidationThresholdFlag,
5034                                    std::to_string(config.validationThreshold));
5035         ScopedSystemProperties sp2(kDotXportUnusableThresholdFlag,
5036                                    std::to_string(dotXportUnusableThreshold));
5037         ScopedSystemProperties sp3(kDotQueryTimeoutMsFlag, std::to_string(dotQueryTimeoutMs));
5038         resetNetwork();
5039 
5040         // This test is sensitive to the number of queries sent in DoT validation.
5041         int latencyFactor;
5042         int latencyOffsetMs;
5043         if (isAtLeastR) {
5044             // The feature is enabled by default in R.
5045             latencyFactor = std::stoi(GetProperty(kDotValidationLatencyFactorFlag, "3"));
5046             latencyOffsetMs = std::stoi(GetProperty(kDotValidationLatencyOffsetMsFlag, "100"));
5047         } else {
5048             // The feature is disabled by default in Q.
5049             latencyFactor = std::stoi(GetProperty(kDotValidationLatencyFactorFlag, "-1"));
5050             latencyOffsetMs = std::stoi(GetProperty(kDotValidationLatencyOffsetMsFlag, "-1"));
5051         }
5052         const bool dotValidationExtraProbes = (config.dnsMode == "OPPORTUNISTIC") &&
5053                                               (latencyFactor >= 0 && latencyOffsetMs >= 0 &&
5054                                                latencyFactor + latencyOffsetMs != 0);
5055 
5056         const std::string addr = getUniqueIPv4Address();
5057         test::DNSResponder dns(addr);
5058         StartDns(dns, records);
5059         test::DnsTlsFrontend tls(addr, "853", addr, "53");
5060         ASSERT_TRUE(tls.startServer());
5061 
5062         auto parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
5063         parcel.servers = {addr};
5064         parcel.tlsServers = {addr};
5065         if (config.dnsMode == "STRICT") parcel.tlsName = kDefaultPrivateDnsHostName;
5066         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
5067         EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
5068         if (dotValidationExtraProbes) {
5069             EXPECT_TRUE(tls.waitForQueries(2));
5070         } else {
5071             EXPECT_TRUE(tls.waitForQueries(1));
5072         }
5073         tls.clearQueries();
5074         dns.clearQueries();
5075 
5076         // Expect the things happening in order:
5077         // 1. Configure the DoT server to postpone |queries + 1| DNS queries.
5078         // 2. Send |queries| DNS queries, they will time out in 1 second.
5079         // 3. 1 second later, the DoT server still waits for one more DNS query until
5080         //    |delayQueriesTimeout| times out.
5081         // 4. (opportunistic mode only) Meanwhile, DoT revalidation happens. The DnsResolver
5082         //    creates a new connection and sends a query to the DoT server.
5083         // 5. 1 second later, |delayQueriesTimeout| times out. The DoT server flushes all of the
5084         //    postponed DNS queries, and handles the query which comes from the revalidation.
5085         // 6. (opportunistic mode only) The revalidation succeeds.
5086         // 7. Send another DNS query, and expect it will succeed.
5087         // 8. (opportunistic mode only) If the DoT server has been deemed as unusable, the
5088         //    DnsResolver skips trying the DoT server.
5089 
5090         // Step 1.
5091         tls.setDelayQueries(queries + 1);
5092         tls.setDelayQueriesTimeout(delayQueriesTimeout);
5093 
5094         // Step 2.
5095         std::vector<std::thread> threads1(queries);
5096         for (std::thread& thread : threads1) {
5097             thread = std::thread([&]() {
5098                 int fd = resNetworkQuery(TEST_NETID, hostname, ns_c_in, ns_t_a, cacheFlag);
5099                 config.dnsMode == "STRICT" ? expectAnswersNotValid(fd, -ETIMEDOUT)
5100                                            : expectAnswersValid(fd, AF_INET, "1.2.3.4");
5101             });
5102         }
5103 
5104         // Step 3 and 4.
5105         for (std::thread& thread : threads1) {
5106             thread.join();
5107         }
5108 
5109         // Recover the config to make the revalidation can succeed.
5110         tls.setDelayQueries(1);
5111 
5112         // Step 5 and 6.
5113         int expectedDotQueries = queries;
5114         int extraDnsProbe = 0;
5115         if (config.expectRevalidationHappen) {
5116             EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
5117             expectedDotQueries++;
5118 
5119             if (dotValidationExtraProbes) {
5120                 expectedDotQueries++;
5121                 extraDnsProbe = 1;
5122             }
5123         }
5124 
5125         // Step 7 and 8.
5126         int fd = resNetworkQuery(TEST_NETID, hostname, ns_c_in, ns_t_a, cacheFlag);
5127         expectAnswersValid(fd, AF_INET, "1.2.3.4");
5128         expectedDotQueries++;
5129 
5130         const int expectedDo53Queries =
5131                 expectedDotQueries +
5132                 (config.dnsMode == "OPPORTUNISTIC" ? (queries + extraDnsProbe) : 0);
5133 
5134         if (config.expectDotUnusable) {
5135             // A DoT server can be deemed as unusable only in opportunistic mode. When it happens,
5136             // the DnsResolver doesn't use the DoT server for a certain period of time.
5137             expectedDotQueries--;
5138         }
5139 
5140         // This code makes the test more robust to race condition.
5141         EXPECT_TRUE(tls.waitForQueries(expectedDotQueries));
5142 
5143         EXPECT_EQ(dns.queries().size(), static_cast<unsigned>(expectedDo53Queries));
5144         EXPECT_EQ(tls.queries(), expectedDotQueries);
5145     }
5146 }
5147 
5148 // Verifies that private DNS validation fails if DoT server is much slower than cleartext server.
TEST_F(ResolverTest,TlsServerValidation_UdpProbe)5149 TEST_F(ResolverTest, TlsServerValidation_UdpProbe) {
5150     constexpr char backend_addr[] = "127.0.0.3";
5151     test::DNSResponder backend(backend_addr);
5152     backend.setResponseDelayMs(200);
5153     ASSERT_TRUE(backend.startServer());
5154 
5155     static const struct TestConfig {
5156         int latencyFactor;
5157         int latencyOffsetMs;
5158         bool udpProbeLost;
5159         size_t expectedUdpProbes;
5160         bool expectedValidationPass;
5161     } testConfigs[] = {
5162             // clang-format off
5163             {-1, -1,  false, 0, true},
5164             {0,  0,   false, 0, true},
5165             {1,  10,  false, 1, false},
5166             {1,  10,  true,  2, false},
5167             {5,  300, false, 1, true},
5168             {5,  300, true,  2, true},
5169             // clang-format on
5170     };
5171 
5172     for (const auto& config : testConfigs) {
5173         SCOPED_TRACE(fmt::format("testConfig: [{}, {}, {}]", config.latencyFactor,
5174                                  config.latencyOffsetMs, config.udpProbeLost));
5175 
5176         const std::string addr = getUniqueIPv4Address();
5177         test::DNSResponder dns(addr, "53", static_cast<ns_rcode>(-1));
5178         test::DnsTlsFrontend tls(addr, "853", backend_addr, "53");
5179         dns.setResponseDelayMs(10);
5180         ASSERT_TRUE(dns.startServer());
5181         ASSERT_TRUE(tls.startServer());
5182 
5183         ScopedSystemProperties sp1(kDotValidationLatencyFactorFlag,
5184                                    std::to_string(config.latencyFactor));
5185         ScopedSystemProperties sp2(kDotValidationLatencyOffsetMsFlag,
5186                                    std::to_string(config.latencyOffsetMs));
5187         resetNetwork();
5188 
5189         std::unique_ptr<std::thread> thread;
5190         if (config.udpProbeLost) {
5191             thread.reset(new std::thread([&dns]() {
5192                 // Simulate that the first UDP probe is lost and the second UDP probe succeeds.
5193                 dns.setResponseProbability(0.0);
5194                 std::this_thread::sleep_for(std::chrono::seconds(2));
5195                 dns.setResponseProbability(1.0);
5196             }));
5197         }
5198 
5199         // Set up opportunistic mode, and wait for the validation complete.
5200         auto parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
5201         parcel.servers = {addr};
5202         parcel.tlsServers = {addr};
5203         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
5204 
5205         // The timeout of WaitForPrivateDnsValidation is 5 seconds which is still enough for
5206         // the testcase of UDP probe lost because the retry of UDP probe happens after 3 seconds.
5207         EXPECT_TRUE(
5208                 WaitForPrivateDnsValidation(tls.listen_address(), config.expectedValidationPass));
5209         EXPECT_EQ(dns.queries().size(), config.expectedUdpProbes);
5210         dns.clearQueries();
5211 
5212         // Test that Private DNS validation always pass in strict mode.
5213         parcel.tlsName = kDefaultPrivateDnsHostName;
5214         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
5215         EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
5216         EXPECT_EQ(dns.queries().size(), 0U);
5217 
5218         if (thread) {
5219             thread->join();
5220             thread.reset();
5221         }
5222     }
5223 }
5224 
5225 // Verifies that DNS queries can quick fall back to UDP if the first DoT server is unresponsive.
TEST_F(ResolverTest,DotQuickFallback)5226 TEST_F(ResolverTest, DotQuickFallback) {
5227     constexpr int DOT_CONNECT_TIMEOUT_MS = 1000;
5228     const std::string addr1 = getUniqueIPv4Address();
5229     const std::string addr2 = getUniqueIPv4Address();
5230     test::DNSResponder dns1(addr1);
5231     test::DNSResponder dns2(addr2);
5232     test::DnsTlsFrontend dot1(addr1, "853", addr1, "53");
5233     test::DnsTlsFrontend dot2(addr2, "853", addr2, "53");
5234 
5235     dns1.addMapping(kHelloExampleCom, ns_type::ns_t_aaaa, kHelloExampleComAddrV6);
5236     dns2.addMapping(kHelloExampleCom, ns_type::ns_t_aaaa, kHelloExampleComAddrV6);
5237     ASSERT_TRUE(dns1.startServer());
5238     ASSERT_TRUE(dns2.startServer());
5239     ASSERT_TRUE(dot1.startServer());
5240     ASSERT_TRUE(dot2.startServer());
5241 
5242     static const struct TestConfig {
5243         std::string privateDnsMode;
5244         int dotQuickFallbackFlag;
5245     } testConfigs[] = {
5246             // clang-format off
5247             {"OPPORTUNISTIC", 0},
5248             {"OPPORTUNISTIC", 1},
5249             {"STRICT",        0},
5250             {"STRICT",        1},
5251             // clang-format on
5252     };
5253 
5254     for (const auto& config : testConfigs) {
5255         SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", config.privateDnsMode,
5256                                  config.dotQuickFallbackFlag));
5257 
5258         const bool canQuickFallback =
5259                 (config.dotQuickFallbackFlag == 1) && (config.privateDnsMode == "OPPORTUNISTIC");
5260         ScopedSystemProperties sp1(kDotConnectTimeoutMsFlag,
5261                                    std::to_string(DOT_CONNECT_TIMEOUT_MS));
5262         ScopedSystemProperties sp2(kDotQuickFallbackFlag,
5263                                    std::to_string(config.dotQuickFallbackFlag));
5264 
5265         // Disable revalidation because we are reusing the same IP address of DoT servers.
5266         ScopedSystemProperties sp3(kDotRevalidationThresholdFlag, "-1");
5267 
5268         // TODO: Remove the flags and fix the test.
5269         ScopedSystemProperties sp4(kDotAsyncHandshakeFlag, "0");
5270         ScopedSystemProperties sp5(kDotMaxretriesFlag, "3");
5271         resetNetwork();
5272 
5273         resetNetwork();
5274 
5275         auto parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
5276         parcel.servers = {addr1, addr2};
5277         parcel.tlsServers = {addr1, addr2};
5278         parcel.tlsName = (config.privateDnsMode == "STRICT") ? kDefaultPrivateDnsHostName : "";
5279         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
5280 
5281         EXPECT_TRUE(WaitForPrivateDnsValidation(dot1.listen_address(), true));
5282         EXPECT_TRUE(WaitForPrivateDnsValidation(dot2.listen_address(), true));
5283         EXPECT_TRUE(dot1.waitForQueries(1));
5284         EXPECT_TRUE(dot2.waitForQueries(1));
5285         dot1.clearQueries();
5286         dot2.clearQueries();
5287         dot1.clearConnectionsCount();
5288         dot2.clearConnectionsCount();
5289 
5290         // Set the DoT server unresponsive to connection handshake.
5291         dot1.setHangOnHandshakeForTesting(true);
5292 
5293         int fd = resNetworkQuery(TEST_NETID, kHelloExampleCom, ns_c_in, ns_t_aaaa,
5294                                  ANDROID_RESOLV_NO_CACHE_LOOKUP);
5295         expectAnswersValid(fd, AF_INET6, kHelloExampleComAddrV6);
5296 
5297         EXPECT_EQ(dot1.acceptConnectionsCount(), 1);
5298         EXPECT_EQ(dot2.acceptConnectionsCount(), canQuickFallback ? 0 : 1);
5299         EXPECT_TRUE(dot2.waitForQueries(canQuickFallback ? 0 : 1));
5300 
5301         dot1.setHangOnHandshakeForTesting(false);
5302     }
5303 }
5304 
TEST_F(ResolverTest,FlushNetworkCache)5305 TEST_F(ResolverTest, FlushNetworkCache) {
5306     SKIP_IF_REMOTE_VERSION_LESS_THAN(mDnsClient.resolvService(), 4);
5307     test::DNSResponder dns;
5308     StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, kHelloExampleComAddrV4}});
5309     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
5310 
5311     const hostent* result = gethostbyname("hello");
5312     EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, kHelloExampleCom));
5313     std::function<bool()> HasTheExpectedResult = [result]() -> bool {
5314         if (result == nullptr) return false;
5315         EXPECT_EQ(4, result->h_length);
5316         if (result->h_addr_list[0] == nullptr) return false;
5317         EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
5318         EXPECT_TRUE(result->h_addr_list[1] == nullptr);
5319         return true;
5320     };
5321     ASSERT_TRUE(HasTheExpectedResult());
5322 
5323     // get result from cache
5324     result = gethostbyname("hello");
5325     EXPECT_EQ(1U, GetNumQueriesForType(dns, ns_type::ns_t_a, kHelloExampleCom));
5326     ASSERT_TRUE(HasTheExpectedResult());
5327 
5328     EXPECT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
5329 
5330     result = gethostbyname("hello");
5331     EXPECT_EQ(2U, GetNumQueriesForType(dns, ns_type::ns_t_a, kHelloExampleCom));
5332     ASSERT_TRUE(HasTheExpectedResult());
5333 }
5334 
TEST_F(ResolverTest,FlushNetworkCache_random)5335 TEST_F(ResolverTest, FlushNetworkCache_random) {
5336     SKIP_IF_REMOTE_VERSION_LESS_THAN(mDnsClient.resolvService(), 4);
5337     constexpr int num_flush = 10;
5338     constexpr int num_queries = 20;
5339     test::DNSResponder dns;
5340     StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, kHelloExampleComAddrV4}});
5341     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
5342     const addrinfo hints = {.ai_family = AF_INET};
5343 
5344     std::thread t([this]() {
5345         for (int i = 0; i < num_flush; ++i) {
5346             unsigned delay = arc4random_uniform(10 * 1000);  // 10ms
5347             usleep(delay);
5348             EXPECT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
5349         }
5350     });
5351 
5352     for (int i = 0; i < num_queries; ++i) {
5353         ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
5354         EXPECT_TRUE(result != nullptr);
5355         EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
5356     }
5357     t.join();
5358 }
5359 
5360 // flush cache while one query is wait-for-response, another is pending.
TEST_F(ResolverTest,FlushNetworkCache_concurrent)5361 TEST_F(ResolverTest, FlushNetworkCache_concurrent) {
5362     SKIP_IF_REMOTE_VERSION_LESS_THAN(mDnsClient.resolvService(), 4);
5363     const char* listen_addr1 = "127.0.0.9";
5364     const char* listen_addr2 = "127.0.0.10";
5365     test::DNSResponder dns1(listen_addr1);
5366     test::DNSResponder dns2(listen_addr2);
5367     StartDns(dns1, {{kHelloExampleCom, ns_type::ns_t_a, kHelloExampleComAddrV4}});
5368     StartDns(dns2, {{kHelloExampleCom, ns_type::ns_t_a, kHelloExampleComAddrV4}});
5369     addrinfo hints = {.ai_family = AF_INET};
5370 
5371     // step 1: set server#1 into deferred responding mode
5372     dns1.setDeferredResp(true);
5373     std::thread t1([&listen_addr1, &hints, this]() {
5374         ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr1}));
5375         // step 3: query
5376         ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
5377         // step 9: check result
5378         EXPECT_TRUE(result != nullptr);
5379         EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
5380     });
5381 
5382     // step 2: wait for the query to reach the server
5383     while (GetNumQueries(dns1, kHelloExampleCom) == 0) {
5384         usleep(1000);  // 1ms
5385     }
5386 
5387     std::thread t2([&listen_addr2, &hints, &dns2, this]() {
5388         ASSERT_TRUE(mDnsClient.SetResolversForNetwork({listen_addr2}));
5389         // step 5: query (should be blocked in resolver)
5390         ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
5391         // step 7: check result
5392         EXPECT_TRUE(result != nullptr);
5393         EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
5394         EXPECT_EQ(1U, GetNumQueriesForType(dns2, ns_type::ns_t_a, kHelloExampleCom));
5395     });
5396 
5397     // step 4: wait a bit for the 2nd query to enter pending state
5398     usleep(100 * 1000);  // 100ms
5399     // step 6: flush cache (will unblock pending queries)
5400     EXPECT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
5401     t2.join();
5402 
5403     // step 8: resume server#1
5404     dns1.setDeferredResp(false);
5405     t1.join();
5406 
5407     // step 10: verify if result is correctly cached
5408     dns2.clearQueries();
5409     ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
5410     EXPECT_EQ(0U, GetNumQueries(dns2, kHelloExampleCom));
5411     EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
5412 }
5413 
5414 // TODO: Perhaps to have a boundary conditions test for TCP and UDP.
TEST_F(ResolverTest,TcpQueryWithOversizePayload)5415 TEST_F(ResolverTest, TcpQueryWithOversizePayload) {
5416     test::DNSResponder dns;
5417     StartDns(dns, {{kHelloExampleCom, ns_type::ns_t_a, kHelloExampleComAddrV4}});
5418     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
5419 
5420     int fd = dns_open_proxy();
5421     ASSERT_TRUE(fd > 0);
5422 
5423     // Sending DNS query over TCP once the packet sizes exceed 512 bytes.
5424     // The raw data is combined with Question section and Additional section
5425     // Question section : query "hello.example.com", type A, class IN
5426     // Additional section : type OPT (41), Option PADDING, Option Length 546
5427     // Padding option which allows DNS clients and servers to artificially
5428     // increase the size of a DNS message by a variable number of bytes.
5429     // See also RFC7830, section 3
5430     const std::string query =
5431             "+c0BAAABAAAAAAABBWhlbGxvB2V4YW1wbGUDY29tAAABAAEAACkgAAAAgAACJgAMAiIAAAAAAAAAAAAAAAAAA"
5432             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
5433             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
5434             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
5435             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
5436             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
5437             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
5438             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
5439             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
5440             "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
5441     const std::string cmd =
5442             "resnsend " + std::to_string(TEST_NETID) + " 0 " /* ResNsendFlags */ + query + '\0';
5443     ssize_t rc = TEMP_FAILURE_RETRY(write(fd, cmd.c_str(), cmd.size()));
5444     EXPECT_EQ(rc, static_cast<ssize_t>(cmd.size()));
5445     expectAnswersValid(fd, AF_INET, kHelloExampleComAddrV4);
5446     EXPECT_EQ(1U, GetNumQueriesForProtocol(dns, IPPROTO_TCP, kHelloExampleCom));
5447     EXPECT_EQ(0U, GetNumQueriesForProtocol(dns, IPPROTO_UDP, kHelloExampleCom));
5448 }
5449 
TEST_F(ResolverTest,TruncatedRspMode)5450 TEST_F(ResolverTest, TruncatedRspMode) {
5451     constexpr char listen_addr[] = "127.0.0.4";
5452     constexpr char listen_addr2[] = "127.0.0.5";
5453     constexpr char listen_srv[] = "53";
5454 
5455     test::DNSResponder dns(listen_addr, listen_srv, static_cast<ns_rcode>(-1));
5456     test::DNSResponder dns2(listen_addr2, listen_srv, static_cast<ns_rcode>(-1));
5457     // dns supports UDP only, dns2 support UDP and TCP
5458     dns.setResponseProbability(0.0, IPPROTO_TCP);
5459     StartDns(dns, kLargeCnameChainRecords);
5460     StartDns(dns2, kLargeCnameChainRecords);
5461 
5462     const struct TestConfig {
5463         const std::optional<int32_t> tcMode;
5464         const bool ret;
5465         const unsigned numQueries;
5466         std::string asParameters() const {
5467             return fmt::format("tcMode: {}, ret: {}, numQueries: {}", tcMode.value_or(-1),
5468                                ret ? "true" : "false", numQueries);
5469         }
5470     } testConfigs[]{
5471             // clang-format off
5472             {std::nullopt,                                      true,  0}, /* mode unset */
5473             {aidl::android::net::IDnsResolver::TC_MODE_DEFAULT, true,  0}, /* default mode */
5474             {-666,                                              false, 0}, /* invalid input */
5475             {aidl::android::net::IDnsResolver::TC_MODE_UDP_TCP, true,  1}, /* alternative mode */
5476             // clang-format on
5477     };
5478 
5479     for (const auto& config : testConfigs) {
5480         SCOPED_TRACE(config.asParameters());
5481 
5482         ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
5483         parcel.servers = {listen_addr, listen_addr2};
5484         ResolverOptionsParcel resolverOptions;
5485         if (config.tcMode.has_value()) resolverOptions.tcMode = config.tcMode.value();
5486         if (!mIsResolverOptionIPCSupported) {
5487             parcel.resolverOptions = resolverOptions;
5488             ASSERT_EQ(mDnsClient.resolvService()->setResolverConfiguration(parcel).isOk(),
5489                       config.ret);
5490         } else {
5491             ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(parcel).isOk());
5492         }
5493         if (mIsResolverOptionIPCSupported) {
5494             ASSERT_EQ(mDnsClient.resolvService()
5495                               ->setResolverOptions(parcel.netId, resolverOptions)
5496                               .isOk(),
5497                       config.ret);
5498         }
5499 
5500         const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
5501         ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
5502         ASSERT_TRUE(result != nullptr);
5503         EXPECT_EQ(ToString(result), kHelloExampleComAddrV4);
5504         // TC_MODE_DEFAULT: resolver retries on TCP-only on each name server.
5505         // TC_MODE_UDP_TCP: resolver retries on TCP on the same server, falls back to UDP from next.
5506         ASSERT_EQ(GetNumQueriesForProtocol(dns, IPPROTO_UDP, kHelloExampleCom), 1U);
5507         ASSERT_EQ(GetNumQueriesForProtocol(dns, IPPROTO_TCP, kHelloExampleCom), 1U);
5508         ASSERT_EQ(GetNumQueriesForProtocol(dns2, IPPROTO_UDP, kHelloExampleCom), config.numQueries);
5509         ASSERT_EQ(GetNumQueriesForProtocol(dns2, IPPROTO_TCP, kHelloExampleCom), 1U);
5510 
5511         dns.clearQueries();
5512         dns2.clearQueries();
5513         ASSERT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
5514 
5515         // Clear the stats to make the resolver always choose the same server for the first query.
5516         parcel.servers.clear();
5517         parcel.tlsServers.clear();
5518         if (!mIsResolverOptionIPCSupported) {
5519             ASSERT_EQ(mDnsClient.resolvService()->setResolverConfiguration(parcel).isOk(),
5520                       config.ret);
5521         } else {
5522             ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(parcel).isOk());
5523         }
5524     }
5525 }
5526 
TEST_F(ResolverTest,RepeatedSetup_ResolverStatusRemains)5527 TEST_F(ResolverTest, RepeatedSetup_ResolverStatusRemains) {
5528     constexpr char unusable_listen_addr[] = "127.0.0.3";
5529     constexpr char listen_addr[] = "127.0.0.4";
5530     constexpr char hostname[] = "a.hello.query.";
5531     const auto repeatedSetResolversFromParcel = [&](const ResolverParamsParcel& parcel) {
5532         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
5533         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
5534         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
5535     };
5536 
5537     test::DNSResponder dns(listen_addr);
5538     StartDns(dns, {{hostname, ns_type::ns_t_a, "1.2.3.3"}});
5539     test::DnsTlsFrontend tls1(listen_addr, "853", listen_addr, "53");
5540     ASSERT_TRUE(tls1.startServer());
5541 
5542     // Private DNS off mode.
5543     ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
5544     parcel.servers = {unusable_listen_addr, listen_addr};
5545     parcel.tlsServers.clear();
5546     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
5547 
5548     // Send a query.
5549     const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
5550     EXPECT_NE(safe_getaddrinfo(hostname, nullptr, &hints), nullptr);
5551 
5552     // Check the stats as expected.
5553     const std::vector<NameserverStats> expectedCleartextDnsStats = {
5554             NameserverStats(unusable_listen_addr).setInternalErrors(1),
5555             NameserverStats(listen_addr).setSuccesses(1).setRttAvg(1),
5556     };
5557     EXPECT_TRUE(expectStatsEqualTo(expectedCleartextDnsStats));
5558     EXPECT_EQ(GetNumQueries(dns, hostname), 1U);
5559 
5560     // The stats is supposed to remain as long as the list of cleartext DNS servers is unchanged.
5561     static const struct TestConfig {
5562         std::vector<std::string> servers;
5563         std::vector<std::string> tlsServers;
5564         std::string tlsName;
5565     } testConfigs[] = {
5566             // Private DNS opportunistic mode.
5567             {{listen_addr, unusable_listen_addr}, {listen_addr, unusable_listen_addr}, ""},
5568             {{unusable_listen_addr, listen_addr}, {unusable_listen_addr, listen_addr}, ""},
5569 
5570             // Private DNS strict mode.
5571             {{listen_addr, unusable_listen_addr}, {"127.0.0.100"}, kDefaultPrivateDnsHostName},
5572             {{unusable_listen_addr, listen_addr}, {"127.0.0.100"}, kDefaultPrivateDnsHostName},
5573 
5574             // Private DNS off mode.
5575             {{unusable_listen_addr, listen_addr}, {}, ""},
5576             {{listen_addr, unusable_listen_addr}, {}, ""},
5577     };
5578 
5579     for (const auto& config : testConfigs) {
5580         SCOPED_TRACE(fmt::format("testConfig: [{}] [{}] [{}]", fmt::join(config.servers, ","),
5581                                  fmt::join(config.tlsServers, ","), config.tlsName));
5582         parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
5583         parcel.servers = config.servers;
5584         parcel.tlsServers = config.tlsServers;
5585         parcel.tlsName = config.tlsName;
5586         repeatedSetResolversFromParcel(parcel);
5587         EXPECT_TRUE(expectStatsEqualTo(expectedCleartextDnsStats));
5588 
5589         // The stats remains when the list of search domains changes.
5590         parcel.domains.push_back("tmp.domains");
5591         repeatedSetResolversFromParcel(parcel);
5592         EXPECT_TRUE(expectStatsEqualTo(expectedCleartextDnsStats));
5593 
5594         // The stats remains when the parameters change (except maxSamples).
5595         parcel.sampleValiditySeconds++;
5596         parcel.successThreshold++;
5597         parcel.minSamples++;
5598         parcel.baseTimeoutMsec++;
5599         parcel.retryCount++;
5600         repeatedSetResolversFromParcel(parcel);
5601         EXPECT_TRUE(expectStatsEqualTo(expectedCleartextDnsStats));
5602     }
5603 
5604     // The cache remains.
5605     EXPECT_NE(safe_getaddrinfo(hostname, nullptr, &hints), nullptr);
5606     EXPECT_EQ(GetNumQueries(dns, hostname), 1U);
5607 }
5608 
TEST_F(ResolverTest,RepeatedSetup_NoRedundantPrivateDnsValidation)5609 TEST_F(ResolverTest, RepeatedSetup_NoRedundantPrivateDnsValidation) {
5610     const std::string addr1 = getUniqueIPv4Address();  // For a workable DNS server.
5611     const std::string addr2 = getUniqueIPv4Address();  // For an unresponsive DNS server.
5612     const std::string unusable_addr = getUniqueIPv4Address();
5613     const auto waitForPrivateDnsStateUpdated = []() {
5614         // A buffer time for the PrivateDnsConfiguration instance to update its map,
5615         // mPrivateDnsValidateThreads, which is used for tracking validation threads.
5616         // Since there is a time gap between when PrivateDnsConfiguration reports
5617         // onPrivateDnsValidationEvent and when PrivateDnsConfiguration updates the map, this is a
5618         // workaround to avoid the test starts a subsequent resolver setup during the time gap.
5619         // TODO: Report onPrivateDnsValidationEvent after all the relevant updates are complete.
5620         // Reference to b/152009023.
5621         std::this_thread::sleep_for(20ms);
5622     };
5623 
5624     test::DNSResponder dns1(addr1);
5625     test::DNSResponder dns2(addr2);
5626     StartDns(dns1, {});
5627     StartDns(dns2, {});
5628     test::DnsTlsFrontend workableTls(addr1, "853", addr1, "53");
5629     test::DnsTlsFrontend unresponsiveTls(addr2, "853", addr2, "53");
5630     unresponsiveTls.setHangOnHandshakeForTesting(true);
5631     ASSERT_TRUE(workableTls.startServer());
5632     ASSERT_TRUE(unresponsiveTls.startServer());
5633 
5634     // First setup.
5635     ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
5636     parcel.servers = {addr1, addr2, unusable_addr};
5637     parcel.tlsServers = {addr1, addr2, unusable_addr};
5638     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
5639 
5640     // Check the validation status before proceed. The validation for `unresponsiveTls`
5641     // should be running, and the other two should be finished.
5642     EXPECT_TRUE(WaitForPrivateDnsValidation(workableTls.listen_address(), true));
5643     EXPECT_TRUE(WaitForPrivateDnsValidation(unusable_addr, false));
5644     EXPECT_TRUE(PollForCondition([&]() { return unresponsiveTls.acceptConnectionsCount() == 1; }));
5645     unresponsiveTls.clearConnectionsCount();
5646 
5647     static const struct TestConfig {
5648         std::vector<std::string> tlsServers;
5649         std::string tlsName;
5650     } testConfigs[] = {
5651             {{addr1, addr2, unusable_addr}, ""},
5652             {{unusable_addr, addr1, addr2}, ""},
5653             {{unusable_addr, addr1, addr2}, kDefaultPrivateDnsHostName},
5654             {{addr1, addr2, unusable_addr}, kDefaultPrivateDnsHostName},
5655     };
5656 
5657     std::string TlsNameLastTime;
5658     for (const auto& config : testConfigs) {
5659         SCOPED_TRACE(fmt::format("testConfig: [{}] [{}]", fmt::join(config.tlsServers, ","),
5660                                  config.tlsName));
5661         parcel.servers = config.tlsServers;
5662         parcel.tlsServers = config.tlsServers;
5663         parcel.tlsName = config.tlsName;
5664         parcel.caCertificate = config.tlsName.empty() ? "" : kCaCert;
5665 
5666         const bool dnsModeChanged = (TlsNameLastTime != config.tlsName);
5667         bool validationAttemptToUnresponsiveTls = false;
5668 
5669         waitForPrivateDnsStateUpdated();
5670         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
5671 
5672         for (const auto& serverAddr : parcel.tlsServers) {
5673             SCOPED_TRACE(serverAddr);
5674             if (serverAddr == workableTls.listen_address()) {
5675                 if (dnsModeChanged) {
5676                     // Despite the identical IP address, the server is regarded as a different
5677                     // server when DnsTlsServer.name is different. The resolver treats it as a
5678                     // different object and begins the validation process.
5679                     EXPECT_TRUE(WaitForPrivateDnsValidation(serverAddr, true));
5680                 }
5681             } else if (serverAddr == unresponsiveTls.listen_address()) {
5682                 if (dnsModeChanged) {
5683                     // Despite the identical IP address, the server is regarded as a different
5684                     // server when DnsTlsServer.name is different. The resolver treats it as a
5685                     // different object and begins the validation process.
5686                     validationAttemptToUnresponsiveTls = true;
5687 
5688                     // This is the limitation from DnsTlsFrontend. DnsTlsFrontend can't operate
5689                     // concurrently. As soon as there's another connection request,
5690                     // DnsTlsFrontend resets the unique_fd to the new connection.
5691                     EXPECT_TRUE(WaitForPrivateDnsValidation(serverAddr, false));
5692                 }
5693             } else {
5694                 // Must be unusable_addr.
5695                 // In opportunistic mode, when a validation for a private DNS server fails, the
5696                 // resolver just marks the server as failed and doesn't re-evaluate it, but the
5697                 // server can be re-evaluated when setResolverConfiguration() is called.
5698                 // However, in strict mode, the resolver automatically re-evaluates the server and
5699                 // marks the server as in_progress until the validation succeeds, so repeated setup
5700                 // makes no effect.
5701                 if (dnsModeChanged || config.tlsName.empty() /* not in strict mode */) {
5702                     EXPECT_TRUE(WaitForPrivateDnsValidation(serverAddr, false));
5703                 }
5704             }
5705         }
5706 
5707         // Repeated setups make no effect in strict mode.
5708         waitForPrivateDnsStateUpdated();
5709         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
5710         if (config.tlsName.empty()) {
5711             EXPECT_TRUE(WaitForPrivateDnsValidation(unusable_addr, false));
5712         }
5713         waitForPrivateDnsStateUpdated();
5714         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
5715         if (config.tlsName.empty()) {
5716             EXPECT_TRUE(WaitForPrivateDnsValidation(unusable_addr, false));
5717         }
5718 
5719         if (validationAttemptToUnresponsiveTls) {
5720             EXPECT_TRUE(PollForCondition(
5721                     [&]() { return unresponsiveTls.acceptConnectionsCount() > 0; }));
5722         } else {
5723             EXPECT_EQ(unresponsiveTls.acceptConnectionsCount(), 0);
5724         }
5725 
5726         TlsNameLastTime = config.tlsName;
5727         unresponsiveTls.clearConnectionsCount();
5728     }
5729 
5730     // Check that all the validation results are caught.
5731     // Note: it doesn't mean no validation being in progress.
5732     EXPECT_FALSE(hasUncaughtPrivateDnsValidation(addr1));
5733     EXPECT_FALSE(hasUncaughtPrivateDnsValidation(addr2));
5734     EXPECT_FALSE(hasUncaughtPrivateDnsValidation(unusable_addr));
5735 }
5736 
TEST_F(ResolverTest,RepeatedSetup_KeepChangingPrivateDnsServers)5737 TEST_F(ResolverTest, RepeatedSetup_KeepChangingPrivateDnsServers) {
5738     enum TlsServerState { WORKING, UNSUPPORTED, UNRESPONSIVE };
5739     const std::string addr1 = getUniqueIPv4Address();
5740     const std::string addr2 = getUniqueIPv4Address();
5741     const auto waitForPrivateDnsStateUpdated = []() {
5742         // A buffer time for PrivateDnsConfiguration to update its state. It prevents this test
5743         // being flaky. See b/152009023 for the reason.
5744         std::this_thread::sleep_for(20ms);
5745     };
5746 
5747     test::DNSResponder dns1(addr1);
5748     test::DNSResponder dns2(addr2);
5749     StartDns(dns1, {});
5750     StartDns(dns2, {});
5751     test::DnsTlsFrontend tls1(addr1, "853", addr1, "53");
5752     test::DnsTlsFrontend tls2(addr2, "853", addr2, "53");
5753     ASSERT_TRUE(tls1.startServer());
5754     ASSERT_TRUE(tls2.startServer());
5755 
5756     static const struct TestConfig {
5757         std::string tlsServer;
5758         std::string tlsName;
5759         bool expectNothingHappenWhenServerUnsupported;
5760         bool expectNothingHappenWhenServerUnresponsive;
5761         std::string asTestName() const {
5762             return fmt::format("{}, {}, {}, {}", tlsServer, tlsName,
5763                                expectNothingHappenWhenServerUnsupported,
5764                                expectNothingHappenWhenServerUnresponsive);
5765         }
5766     } testConfigs[] = {
5767             {{addr1}, "", false, false},
5768             {{addr2}, "", false, false},
5769             {{addr1}, "", false, true},
5770             {{addr2}, "", false, true},
5771 
5772             // expectNothingHappenWhenServerUnresponsive is false in the two cases because of the
5773             // limitation from DnsTlsFrontend which can't operate concurrently.
5774             {{addr1}, kDefaultPrivateDnsHostName, false, false},
5775             {{addr2}, kDefaultPrivateDnsHostName, false, false},
5776             {{addr1}, kDefaultPrivateDnsHostName, true, true},
5777             {{addr2}, kDefaultPrivateDnsHostName, true, true},
5778 
5779             // expectNothingHappenWhenServerUnresponsive is true in the two cases because of the
5780             // limitation from DnsTlsFrontend which can't operate concurrently.
5781             {{addr1}, "", true, false},
5782             {{addr2}, "", true, false},
5783             {{addr1}, "", true, true},
5784             {{addr2}, "", true, true},
5785     };
5786 
5787     for (const auto& serverState : {WORKING, UNSUPPORTED, UNRESPONSIVE}) {
5788         int testIndex = 0;
5789         for (const auto& config : testConfigs) {
5790             SCOPED_TRACE(fmt::format("serverState:{} testIndex:{} testConfig:[{}]",
5791                                      static_cast<int>(serverState), testIndex++,
5792                                      config.asTestName()));
5793             auto& tls = (config.tlsServer == addr1) ? tls1 : tls2;
5794 
5795             if (serverState == UNSUPPORTED && tls.running()) ASSERT_TRUE(tls.stopServer());
5796             if (serverState != UNSUPPORTED && !tls.running()) ASSERT_TRUE(tls.startServer());
5797 
5798             tls.setHangOnHandshakeForTesting(serverState == UNRESPONSIVE);
5799             const int connectCountsBefore = tls.acceptConnectionsCount();
5800 
5801             waitForPrivateDnsStateUpdated();
5802             ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
5803             parcel.servers = {config.tlsServer};
5804             parcel.tlsServers = {config.tlsServer};
5805             parcel.tlsName = config.tlsName;
5806             parcel.caCertificate = config.tlsName.empty() ? "" : kCaCert;
5807             ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
5808 
5809             if (serverState == WORKING) {
5810                 EXPECT_TRUE(WaitForPrivateDnsValidation(config.tlsServer, true));
5811             } else if (serverState == UNSUPPORTED) {
5812                 if (config.expectNothingHappenWhenServerUnsupported) {
5813                     // It's possible that the resolver hasn't yet started to
5814                     // connect. Wait a while.
5815                     // TODO: See if we can get rid of the hard waiting time, such as comparing
5816                     // the CountDiff across two tests.
5817                     std::this_thread::sleep_for(100ms);
5818                     EXPECT_EQ(tls.acceptConnectionsCount(), connectCountsBefore);
5819                 } else {
5820                     EXPECT_TRUE(WaitForPrivateDnsValidation(config.tlsServer, false));
5821                 }
5822             } else {
5823                 // Must be UNRESPONSIVE.
5824                 // DnsTlsFrontend is the only signal for checking whether or not the resolver starts
5825                 // another validation when the server is unresponsive.
5826 
5827                 // Wait for a while to avoid running the checker code too early.
5828                 std::this_thread::sleep_for(200ms);
5829                 if (!config.expectNothingHappenWhenServerUnresponsive) {
5830                     EXPECT_TRUE(WaitForPrivateDnsValidation(config.tlsServer, false));
5831                 }
5832                 const auto condition = [&]() {
5833                     const int connectCountsAfter = tls.acceptConnectionsCount();
5834                     return config.expectNothingHappenWhenServerUnresponsive
5835                                    ? (connectCountsAfter == connectCountsBefore)
5836                                    : (connectCountsAfter > connectCountsBefore);
5837                 };
5838                 EXPECT_TRUE(PollForCondition(condition));
5839             }
5840         }
5841 
5842         // Set to off mode to reset the PrivateDnsConfiguration state.
5843         ResolverParamsParcel setupOffmode = DnsResponderClient::GetDefaultResolverParamsParcel();
5844         setupOffmode.tlsServers.clear();
5845         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(setupOffmode));
5846     }
5847 
5848     // Check that all the validation results are caught.
5849     // Note: it doesn't mean no validation being in progress.
5850     EXPECT_FALSE(hasUncaughtPrivateDnsValidation(addr1));
5851     EXPECT_FALSE(hasUncaughtPrivateDnsValidation(addr2));
5852 }
5853 
TEST_F(ResolverTest,PermissionCheckOnCertificateInjection)5854 TEST_F(ResolverTest, PermissionCheckOnCertificateInjection) {
5855     ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
5856     parcel.caCertificate = kCaCert;
5857     ASSERT_TRUE(mDnsClient.resolvService()->setResolverConfiguration(parcel).isOk());
5858 
5859     for (const uid_t uid : {AID_SYSTEM, TEST_UID}) {
5860         ScopedChangeUID scopedChangeUID(uid);
5861         auto status = mDnsClient.resolvService()->setResolverConfiguration(parcel);
5862         EXPECT_EQ(status.getExceptionCode(), EX_SECURITY);
5863     }
5864 }
5865 
5866 // Parameterized tests.
5867 // TODO: Merge the existing tests as parameterized test if possible.
5868 // TODO: Perhaps move parameterized tests to an independent file.
5869 enum class CallType { GETADDRINFO, GETHOSTBYNAME };
5870 class ResolverParameterizedTest : public ResolverTest,
5871                                   public testing::WithParamInterface<CallType> {
5872   protected:
VerifyQueryHelloExampleComV4(const test::DNSResponder & dns,const CallType calltype,const bool verifyNumQueries=true)5873     void VerifyQueryHelloExampleComV4(const test::DNSResponder& dns, const CallType calltype,
5874                                       const bool verifyNumQueries = true) {
5875         if (calltype == CallType::GETADDRINFO) {
5876             const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
5877             ScopedAddrinfo result = safe_getaddrinfo("hello", nullptr, &hints);
5878             ASSERT_TRUE(result != nullptr);
5879             EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
5880         } else if (calltype == CallType::GETHOSTBYNAME) {
5881             const hostent* result = gethostbyname("hello");
5882             ASSERT_TRUE(result != nullptr);
5883             ASSERT_EQ(4, result->h_length);
5884             ASSERT_FALSE(result->h_addr_list[0] == nullptr);
5885             EXPECT_EQ(kHelloExampleComAddrV4, ToString(result));
5886             EXPECT_TRUE(result->h_addr_list[1] == nullptr);
5887         } else {
5888             FAIL() << "Unsupported call type: " << static_cast<uint32_t>(calltype);
5889         }
5890         if (verifyNumQueries) EXPECT_EQ(1U, GetNumQueries(dns, kHelloExampleCom));
5891     }
5892 };
5893 
5894 INSTANTIATE_TEST_SUITE_P(QueryCallTest, ResolverParameterizedTest,
5895                          testing::Values(CallType::GETADDRINFO, CallType::GETHOSTBYNAME),
__anon6dfd3fcb1d02(const testing::TestParamInfo<CallType>& info) 5896                          [](const testing::TestParamInfo<CallType>& info) {
5897                              switch (info.param) {
5898                                  case CallType::GETADDRINFO:
5899                                      return "GetAddrInfo";
5900                                  case CallType::GETHOSTBYNAME:
5901                                      return "GetHostByName";
5902                                  default:
5903                                      return "InvalidParameter";  // Should not happen.
5904                              }
5905                          });
5906 
TEST_P(ResolverParameterizedTest,AuthoritySectionAndAdditionalSection)5907 TEST_P(ResolverParameterizedTest, AuthoritySectionAndAdditionalSection) {
5908     // DNS response may have more information in authority section and additional section.
5909     // Currently, getanswer() of packages/modules/DnsResolver/getaddrinfo.cpp doesn't parse the
5910     // content of authority section and additional section. Test these sections if they crash
5911     // the resolver, just in case. See also RFC 1035 section 4.1.
5912     const auto& calltype = GetParam();
5913     test::DNSHeader header(kDefaultDnsHeader);
5914 
5915     // Create a DNS response which has a authoritative nameserver record in authority
5916     // section and its relevant address record in additional section.
5917     //
5918     // Question
5919     //   hello.example.com.     IN      A
5920     // Answer
5921     //   hello.example.com.     IN      A   1.2.3.4
5922     // Authority:
5923     //   hello.example.com.     IN      NS  ns1.example.com.
5924     // Additional:
5925     //   ns1.example.com.       IN      A   5.6.7.8
5926     //
5927     // A response may have only question, answer, and authority section. Current testing response
5928     // should be able to cover this condition.
5929 
5930     // Question section.
5931     test::DNSQuestion question{
5932             .qname = {.name = kHelloExampleCom},
5933             .qtype = ns_type::ns_t_a,
5934             .qclass = ns_c_in,
5935     };
5936     header.questions.push_back(std::move(question));
5937 
5938     // Answer section.
5939     test::DNSRecord recordAnswer{
5940             .name = {.name = kHelloExampleCom},
5941             .rtype = ns_type::ns_t_a,
5942             .rclass = ns_c_in,
5943             .ttl = 0,  // no cache
5944     };
5945     EXPECT_TRUE(test::DNSResponder::fillRdata(kHelloExampleComAddrV4, recordAnswer));
5946     header.answers.push_back(std::move(recordAnswer));
5947 
5948     // Authority section.
5949     test::DNSRecord recordAuthority{
5950             .name = {.name = kHelloExampleCom},
5951             .rtype = ns_type::ns_t_ns,
5952             .rclass = ns_c_in,
5953             .ttl = 0,  // no cache
5954     };
5955     EXPECT_TRUE(test::DNSResponder::fillRdata("ns1.example.com.", recordAuthority));
5956     header.authorities.push_back(std::move(recordAuthority));
5957 
5958     // Additional section.
5959     test::DNSRecord recordAdditional{
5960             .name = {.name = "ns1.example.com."},
5961             .rtype = ns_type::ns_t_a,
5962             .rclass = ns_c_in,
5963             .ttl = 0,  // no cache
5964     };
5965     EXPECT_TRUE(test::DNSResponder::fillRdata("5.6.7.8", recordAdditional));
5966     header.additionals.push_back(std::move(recordAdditional));
5967 
5968     // Start DNS server.
5969     test::DNSResponder dns(test::DNSResponder::MappingType::DNS_HEADER);
5970     dns.addMappingDnsHeader(kHelloExampleCom, ns_type::ns_t_a, header);
5971     ASSERT_TRUE(dns.startServer());
5972     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
5973     dns.clearQueries();
5974 
5975     // Expect that get the address and the resolver doesn't crash.
5976     VerifyQueryHelloExampleComV4(dns, calltype);
5977 }
5978 
TEST_P(ResolverParameterizedTest,MessageCompression)5979 TEST_P(ResolverParameterizedTest, MessageCompression) {
5980     const auto& calltype = GetParam();
5981 
5982     // The response with compressed domain name by a pointer. See RFC 1035 section 4.1.4.
5983     //
5984     // Ignoring the other fields of the message, the domain name of question section and answer
5985     // section are presented as:
5986     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
5987     // 12 |           5           |           h           |
5988     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
5989     // 14 |           e           |           l           |
5990     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
5991     // 16 |           l           |           o           |
5992     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
5993     // 18 |           7           |           e           |
5994     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
5995     // 20 |           x           |           a           |
5996     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
5997     // 22 |           m           |           p           |
5998     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
5999     // 24 |           l           |           e           |
6000     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6001     // 26 |           3           |           c           |
6002     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6003     // 28 |           o           |           m           |
6004     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6005     // 30 |           0           |          ...          |
6006     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6007     //
6008     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6009     // 35 | 1  1|                12                       |
6010     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6011     const std::vector<uint8_t> kResponseAPointer = {
6012             /* Header */
6013             0x00, 0x00, /* Transaction ID: 0x0000 */
6014             0x81, 0x80, /* Flags: qr rd ra */
6015             0x00, 0x01, /* Questions: 1 */
6016             0x00, 0x01, /* Answer RRs: 1 */
6017             0x00, 0x00, /* Authority RRs: 0 */
6018             0x00, 0x00, /* Additional RRs: 0 */
6019             /* Queries */
6020             0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
6021             0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name: hello.example.com */
6022             0x00, 0x01,                   /* Type: A */
6023             0x00, 0x01,                   /* Class: IN */
6024             /* Answers */
6025             0xc0, 0x0c,             /* Name: hello.example.com (a pointer) */
6026             0x00, 0x01,             /* Type: A */
6027             0x00, 0x01,             /* Class: IN */
6028             0x00, 0x00, 0x00, 0x00, /* Time to live: 0 */
6029             0x00, 0x04,             /* Data length: 4 */
6030             0x01, 0x02, 0x03, 0x04  /* Address: 1.2.3.4 */
6031     };
6032 
6033     // The response with compressed domain name by a sequence of labels ending with a pointer. See
6034     // RFC 1035 section 4.1.4.
6035     //
6036     // Ignoring the other fields of the message, the domain name of question section and answer
6037     // section are presented as:
6038     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6039     // 12 |           5           |           h           |
6040     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6041     // 14 |           e           |           l           |
6042     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6043     // 16 |           l           |           o           |
6044     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6045     // 18 |           7           |           e           |
6046     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6047     // 20 |           x           |           a           |
6048     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6049     // 22 |           m           |           p           |
6050     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6051     // 24 |           l           |           e           |
6052     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6053     // 26 |           3           |           c           |
6054     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6055     // 28 |           o           |           m           |
6056     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6057     // 30 |           0           |          ...          |
6058     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6059     //
6060     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6061     // 35 |           5           |           h           |
6062     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6063     // 37 |           e           |           l           |
6064     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6065     // 39 |           l           |           o           |
6066     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6067     // 41 | 1  1|                18                       |
6068     //    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
6069     const std::vector<uint8_t> kResponseLabelEndingWithAPointer = {
6070             /* Header */
6071             0x00, 0x00, /* Transaction ID: 0x0000 */
6072             0x81, 0x80, /* Flags: qr rd ra */
6073             0x00, 0x01, /* Questions: 1 */
6074             0x00, 0x01, /* Answer RRs: 1 */
6075             0x00, 0x00, /* Authority RRs: 0 */
6076             0x00, 0x00, /* Additional RRs: 0 */
6077             /* Queries */
6078             0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
6079             0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name: hello.example.com */
6080             0x00, 0x01,                   /* Type: A */
6081             0x00, 0x01,                   /* Class: IN */
6082             /* Answers */
6083             0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0xc0,
6084             0x12,                   /* Name: hello.example.com (a label ending with a pointer) */
6085             0x00, 0x01,             /* Type: A */
6086             0x00, 0x01,             /* Class: IN */
6087             0x00, 0x00, 0x00, 0x00, /* Time to live: 0 */
6088             0x00, 0x04,             /* Data length: 4 */
6089             0x01, 0x02, 0x03, 0x04  /* Address: 1.2.3.4 */
6090     };
6091 
6092     for (const auto& response : {kResponseAPointer, kResponseLabelEndingWithAPointer}) {
6093         SCOPED_TRACE(fmt::format("Hex dump: {}", toHex(makeSlice(response))));
6094 
6095         test::DNSResponder dns(test::DNSResponder::MappingType::BINARY_PACKET);
6096         dns.addMappingBinaryPacket(kHelloExampleComQueryV4, response);
6097         StartDns(dns, {});
6098         ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
6099 
6100         // Expect no cache because the TTL of testing responses are 0.
6101         VerifyQueryHelloExampleComV4(dns, calltype);
6102     }
6103 }
6104 
TEST_P(ResolverParameterizedTest,TruncatedResponse)6105 TEST_P(ResolverParameterizedTest, TruncatedResponse) {
6106     const auto& calltype = GetParam();
6107 
6108     test::DNSResponder dns;
6109     StartDns(dns, kLargeCnameChainRecords);
6110     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
6111 
6112     // Expect UDP response is truncated. The resolver retries over TCP. See RFC 1035 section 4.2.1.
6113     VerifyQueryHelloExampleComV4(dns, calltype, false);
6114     EXPECT_EQ(1U, GetNumQueriesForProtocol(dns, IPPROTO_UDP, kHelloExampleCom));
6115     EXPECT_EQ(1U, GetNumQueriesForProtocol(dns, IPPROTO_TCP, kHelloExampleCom));
6116 }
6117 
6118 // Tests that the DnsResolver can keep listening to the DNS response from previous DNS servers.
6119 // Test scenarios (The timeout for each server is 1 second):
6120 //   1. (During the first iteration of DNS servers) While waiting for the DNS response from the
6121 //      second server, the DnsResolver receives the DNS response from the first server.
6122 //   2. (During the second iteration of DNS servers) While waiting for the DNS response from the
6123 //      second server, the DnsResolver receives the DNS response from the first server.
TEST_F(ResolverTest,KeepListeningUDP)6124 TEST_F(ResolverTest, KeepListeningUDP) {
6125     constexpr char listen_addr1[] = "127.0.0.4";
6126     constexpr char listen_addr2[] = "127.0.0.5";
6127     constexpr char host_name[] = "howdy.example.com.";
6128     const std::vector<DnsRecord> records = {
6129             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
6130     };
6131     auto builder =
6132             ResolverParams::Builder().setDnsServers({listen_addr1, listen_addr2}).setDotServers({});
6133 
6134     test::DNSResponder neverRespondDns(listen_addr2, "53", static_cast<ns_rcode>(-1));
6135     neverRespondDns.setResponseProbability(0.0);
6136     StartDns(neverRespondDns, records);
6137     test::DNSResponder delayedDns(listen_addr1);
6138     StartDns(delayedDns, records);
6139 
6140     const struct TestConfig {
6141         int retryCount;
6142         int delayTimeMs;
6143         int expectedDns1Successes;
6144         int expectedDns1Timeouts;
6145         int expectedDns2Timeouts;
6146     } testConfigs[]{
6147             {1, 1500, 1, 1, 0},
6148             // Actually, there will be two timeouts and one success for DNS1. However, the
6149             // DnsResolver doesn't record the stats during the second iteration of DNS servers, so
6150             // the success and timeout of DNS1 is 0 and 1, respectively.
6151             {2, 3500, 0, 1, 1},
6152     };
6153     for (const std::string_view callType : {"getaddrinfo", "resnsend"}) {
6154         for (const auto& cfg : testConfigs) {
6155             SCOPED_TRACE(fmt::format("callType={}, retryCount={}, delayTimeMs={}", callType,
6156                                      cfg.retryCount, cfg.delayTimeMs));
6157             const std::array<int, IDnsResolver::RESOLVER_PARAMS_COUNT> params = {
6158                     300, 25, 8, 8, 1000 /* BASE_TIMEOUT_MSEC */, cfg.retryCount /* retry count */};
6159 
6160             ScopedSystemProperties sp(kKeepListeningUdpFlag, "1");
6161             resetNetwork();
6162             ASSERT_TRUE(mDnsClient.SetResolversFromParcel(builder.setParams(params).build()));
6163 
6164             delayedDns.setDeferredResp(true);
6165             std::thread thread([&]() {
6166                 std::this_thread::sleep_for(std::chrono::milliseconds(cfg.delayTimeMs));
6167                 delayedDns.setDeferredResp(false);
6168             });
6169 
6170             if (callType == "getaddrinfo") {
6171                 const addrinfo hints = {.ai_family = AF_INET6, .ai_socktype = SOCK_DGRAM};
6172                 ScopedAddrinfo result = safe_getaddrinfo(host_name, nullptr, &hints);
6173                 EXPECT_EQ("::1.2.3.4", ToString(result));
6174             } else {
6175                 int fd = resNetworkQuery(TEST_NETID, host_name, ns_c_in, ns_t_aaaa, 0);
6176                 expectAnswersValid(fd, AF_INET6, "::1.2.3.4");
6177             }
6178             const std::vector<NameserverStats> expectedCleartextDnsStats = {
6179                     NameserverStats(listen_addr1)
6180                             .setSuccesses(cfg.expectedDns1Successes)
6181                             .setTimeouts(cfg.expectedDns1Timeouts)
6182                             .setRttAvg(cfg.retryCount == 1 ? 1500 : -1),
6183                     NameserverStats(listen_addr2)
6184                             .setTimeouts(cfg.expectedDns2Timeouts)
6185                             .setRttAvg(-1),
6186             };
6187             EXPECT_TRUE(expectStatsEqualTo(expectedCleartextDnsStats));
6188             thread.join();
6189         }
6190     }
6191 }
6192 
TEST_F(ResolverTest,GetAddrInfoParallelLookupTimeout)6193 TEST_F(ResolverTest, GetAddrInfoParallelLookupTimeout) {
6194     constexpr char host_name[] = "howdy.example.com.";
6195     constexpr int TIMING_TOLERANCE_MS = 200;
6196     constexpr int DNS_TIMEOUT_MS = 1000;
6197     const std::vector<DnsRecord> records = {
6198             {host_name, ns_type::ns_t_a, "1.2.3.4"},
6199             {host_name, ns_type::ns_t_aaaa, "::1.2.3.4"},
6200     };
6201     const std::array<int, IDnsResolver::RESOLVER_PARAMS_COUNT> params = {
6202             300, 25, 8, 8, DNS_TIMEOUT_MS /* BASE_TIMEOUT_MSEC */, 1 /* retry count */};
6203     test::DNSResponder neverRespondDns(kDefaultServer, "53", static_cast<ns_rcode>(-1));
6204     neverRespondDns.setResponseProbability(0.0);
6205     StartDns(neverRespondDns, records);
6206 
6207     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(
6208             ResolverParams::Builder().setDotServers({}).setParams(params).build()));
6209     neverRespondDns.clearQueries();
6210 
6211     // Use a never respond DNS server to verify if the A/AAAA queries are sent in parallel.
6212     // The resolver parameters are set to timeout 1s and retry 1 times.
6213     // So we expect the safe_getaddrinfo_time_taken() might take ~1s to
6214     // return when parallel lookup is enabled. And the DNS server should receive 2 queries.
6215     const addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM};
6216     auto [result, timeTakenMs] = safe_getaddrinfo_time_taken(host_name, nullptr, hints);
6217 
6218     EXPECT_TRUE(result == nullptr);
6219     EXPECT_NEAR(DNS_TIMEOUT_MS, timeTakenMs, TIMING_TOLERANCE_MS)
6220             << "took time should approximate equal timeout";
6221     EXPECT_EQ(2U, GetNumQueries(neverRespondDns, host_name));
6222     ExpectDnsEvent(INetdEventListener::EVENT_GETADDRINFO, RCODE_TIMEOUT, host_name, {});
6223 }
6224 
TEST_F(ResolverTest,GetAddrInfoParallelLookupSleepTime)6225 TEST_F(ResolverTest, GetAddrInfoParallelLookupSleepTime) {
6226     constexpr int TIMING_TOLERANCE_MS = 200;
6227     const std::vector<DnsRecord> records = {
6228             {kHelloExampleCom, ns_type::ns_t_a, kHelloExampleComAddrV4},
6229             {kHelloExampleCom, ns_type::ns_t_aaaa, kHelloExampleComAddrV6},
6230     };
6231     const std::array<int, IDnsResolver::RESOLVER_PARAMS_COUNT> params = {
6232             300, 25, 8, 8, 1000 /* BASE_TIMEOUT_MSEC */, 1 /* retry count */};
6233     test::DNSResponder dns(kDefaultServer);
6234     StartDns(dns, records);
6235     constexpr int PARALLEL_LOOKUP_SLEEP_TIME_MS = 500;
6236     ScopedSystemProperties sp2(kParallelLookupSleepTimeFlag,
6237                                std::to_string(PARALLEL_LOOKUP_SLEEP_TIME_MS));
6238     // Re-setup test network to make experiment flag take effect.
6239     resetNetwork();
6240 
6241     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(
6242             ResolverParams::Builder().setDotServers({}).setParams(params).build()));
6243     dns.clearQueries();
6244 
6245     // Expect the safe_getaddrinfo_time_taken() might take ~500ms to return because we set
6246     // parallel_lookup_sleep_time to 500ms.
6247     const addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM};
6248     auto [result, timeTakenMs] = safe_getaddrinfo_time_taken(kHelloExampleCom, nullptr, hints);
6249 
6250     EXPECT_NE(nullptr, result);
6251     EXPECT_THAT(ToStrings(result), testing::UnorderedElementsAreArray(
6252                                            {kHelloExampleComAddrV4, kHelloExampleComAddrV6}));
6253     EXPECT_NEAR(PARALLEL_LOOKUP_SLEEP_TIME_MS, timeTakenMs, TIMING_TOLERANCE_MS)
6254             << "took time should approximate equal timeout";
6255     EXPECT_EQ(2U, GetNumQueries(dns, kHelloExampleCom));
6256 
6257     // Expect the PARALLEL_LOOKUP_SLEEP_TIME_MS won't affect the query under cache hit case.
6258     dns.clearQueries();
6259     std::tie(result, timeTakenMs) = safe_getaddrinfo_time_taken(kHelloExampleCom, nullptr, hints);
6260     EXPECT_NE(nullptr, result);
6261     EXPECT_THAT(ToStrings(result), testing::UnorderedElementsAreArray(
6262                                            {kHelloExampleComAddrV4, kHelloExampleComAddrV6}));
6263     EXPECT_GT(PARALLEL_LOOKUP_SLEEP_TIME_MS, timeTakenMs);
6264     EXPECT_EQ(0U, GetNumQueries(dns, kHelloExampleCom));
6265 }
6266 
TEST_F(ResolverTest,BlockDnsQueryUidDoesNotLeadToBadServer)6267 TEST_F(ResolverTest, BlockDnsQueryUidDoesNotLeadToBadServer) {
6268     SKIP_IF_BPF_NOT_SUPPORTED;
6269     constexpr char listen_addr1[] = "127.0.0.4";
6270     constexpr char listen_addr2[] = "::1";
6271     test::DNSResponder dns1(listen_addr1);
6272     test::DNSResponder dns2(listen_addr2);
6273     StartDns(dns1, {});
6274     StartDns(dns2, {});
6275 
6276     std::vector<std::string> servers = {listen_addr1, listen_addr2};
6277     ASSERT_TRUE(mDnsClient.SetResolversForNetwork(servers));
6278     dns1.clearQueries();
6279     dns2.clearQueries();
6280     {
6281         ScopeBlockedUIDRule scopeBlockUidRule(mDnsClient.netdService(), TEST_UID);
6282         // Start querying ten times.
6283         for (int i = 0; i < 10; i++) {
6284             std::string hostName = fmt::format("blocked{}.com", i);
6285             const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
6286             // The query result between R+ and Q would be different, but we don't really care
6287             // about the result here because this test is only used to ensure blocked uid rule
6288             // won't cause bad servers.
6289             safe_getaddrinfo(hostName.c_str(), nullptr, &hints);
6290         }
6291     }
6292     ResolverParamsParcel setupParams = DnsResponderClient::GetDefaultResolverParamsParcel();
6293     // If api level >= 30 (R+), expect all query packets to be blocked, hence we should not see any
6294     // of their stats show up. Otherwise, all queries should succeed.
6295     const std::vector<NameserverStats> expectedDnsStats = {
6296             NameserverStats(listen_addr1)
6297                     .setSuccesses(isAtLeastR ? 0 : setupParams.maxSamples)
6298                     .setRttAvg(isAtLeastR ? -1 : 1),
6299             NameserverStats(listen_addr2),
6300     };
6301     expectStatsEqualTo(expectedDnsStats);
6302     // If api level >= 30 (R+), expect server won't receive any queries,
6303     // otherwise expect 20 == 10 * (setupParams.domains.size() + 1) queries.
6304     EXPECT_EQ(dns1.queries().size(), isAtLeastR ? 0U : 10 * (setupParams.domains.size() + 1));
6305     EXPECT_EQ(dns2.queries().size(), 0U);
6306 }
6307 
TEST_F(ResolverTest,DnsServerSelection)6308 TEST_F(ResolverTest, DnsServerSelection) {
6309     test::DNSResponder dns1("127.0.0.3");
6310     test::DNSResponder dns2("127.0.0.4");
6311     test::DNSResponder dns3("127.0.0.5");
6312 
6313     dns1.setResponseDelayMs(10);
6314     dns2.setResponseDelayMs(50);
6315     dns3.setResponseDelayMs(100);
6316     StartDns(dns1, {{kHelloExampleCom, ns_type::ns_t_a, kHelloExampleComAddrV4}});
6317     StartDns(dns2, {{kHelloExampleCom, ns_type::ns_t_a, kHelloExampleComAddrV4}});
6318     StartDns(dns3, {{kHelloExampleCom, ns_type::ns_t_a, kHelloExampleComAddrV4}});
6319 
6320     // NOTE: the servers must be sorted alphabetically.
6321     std::vector<std::string> serverList = {
6322             dns1.listen_address(),
6323             dns2.listen_address(),
6324             dns3.listen_address(),
6325     };
6326 
6327     do {
6328         SCOPED_TRACE(fmt::format("testConfig: [{}]", fmt::join(serverList, ", ")));
6329         const int queryNum = 50;
6330         int64_t accumulatedTime = 0;
6331 
6332         // The flag can be reset any time. It's better to re-setup the flag in each iteration.
6333         ScopedSystemProperties scopedSystemProperties(kSortNameserversFlag, "1");
6334 
6335         // Restart the testing network to 1) make the flag take effect and 2) reset the statistics.
6336         resetNetwork();
6337 
6338         // DnsServerSelection doesn't apply to private DNS.
6339         ResolverParamsParcel setupParams = DnsResponderClient::GetDefaultResolverParamsParcel();
6340         setupParams.servers = serverList;
6341         setupParams.tlsServers.clear();
6342         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(setupParams));
6343 
6344         // DNSResponder doesn't handle queries concurrently, so don't allow more than
6345         // one in-flight query.
6346         for (int i = 0; i < queryNum; i++) {
6347             Stopwatch s;
6348             int fd = resNetworkQuery(TEST_NETID, kHelloExampleCom, ns_c_in, ns_t_a,
6349                                      ANDROID_RESOLV_NO_CACHE_LOOKUP);
6350             expectAnswersValid(fd, AF_INET, kHelloExampleComAddrV4);
6351             accumulatedTime += s.timeTakenUs();
6352         }
6353 
6354         const int dns1Count = dns1.queries().size();
6355         const int dns2Count = dns2.queries().size();
6356         const int dns3Count = dns3.queries().size();
6357 
6358         // All of the servers have ever been selected. In addition, the less latency server
6359         // is selected more frequently.
6360         EXPECT_GT(dns1Count, 0);
6361         EXPECT_GT(dns2Count, 0);
6362         EXPECT_GT(dns3Count, 0);
6363         EXPECT_GE(dns1Count, dns2Count);
6364         EXPECT_GE(dns2Count, dns3Count);
6365 
6366         const int averageTime = accumulatedTime / queryNum;
6367         LOG(INFO) << "ResolverTest#DnsServerSelection: averageTime " << averageTime << "us";
6368 
6369         dns1.clearQueries();
6370         dns2.clearQueries();
6371         dns3.clearQueries();
6372     } while (std::next_permutation(serverList.begin(), serverList.end()));
6373 }
6374 
TEST_F(ResolverTest,MultipleDotQueriesInOnePacket)6375 TEST_F(ResolverTest, MultipleDotQueriesInOnePacket) {
6376     constexpr char hostname1[] = "query1.example.com.";
6377     constexpr char hostname2[] = "query2.example.com.";
6378     const std::vector<DnsRecord> records = {
6379             {hostname1, ns_type::ns_t_a, "1.2.3.4"},
6380             {hostname2, ns_type::ns_t_a, "1.2.3.5"},
6381     };
6382 
6383     const std::string addr = getUniqueIPv4Address();
6384     test::DNSResponder dns(addr);
6385     StartDns(dns, records);
6386     test::DnsTlsFrontend tls(addr, "853", addr, "53");
6387     ASSERT_TRUE(tls.startServer());
6388 
6389     // Set up resolver to strict mode.
6390     auto parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
6391     parcel.servers = {addr};
6392     parcel.tlsServers = {addr};
6393     parcel.tlsName = kDefaultPrivateDnsHostName;
6394     parcel.caCertificate = kCaCert;
6395     ASSERT_TRUE(mDnsClient.SetResolversFromParcel(parcel));
6396     EXPECT_TRUE(WaitForPrivateDnsValidation(tls.listen_address(), true));
6397     EXPECT_TRUE(tls.waitForQueries(1));
6398     tls.clearQueries();
6399     dns.clearQueries();
6400 
6401     const auto queryAndCheck = [&](const std::string& hostname,
6402                                    const std::vector<DnsRecord>& records) {
6403         SCOPED_TRACE(hostname);
6404 
6405         const addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
6406         auto [result, timeTakenMs] = safe_getaddrinfo_time_taken(hostname.c_str(), nullptr, hints);
6407 
6408         std::vector<std::string> expectedAnswers;
6409         for (const auto& r : records) {
6410             if (r.host_name == hostname) expectedAnswers.push_back(r.addr);
6411         }
6412 
6413         EXPECT_LE(timeTakenMs, 200);
6414         ASSERT_NE(result, nullptr);
6415         EXPECT_THAT(ToStrings(result), testing::UnorderedElementsAreArray(expectedAnswers));
6416     };
6417 
6418     // Set tls to reply DNS responses in one TCP packet and not to close the connection from its
6419     // side.
6420     tls.setDelayQueries(2);
6421     tls.setDelayQueriesTimeout(500);
6422     tls.setPassiveClose(true);
6423 
6424     // Start sending DNS requests at the same time.
6425     std::array<std::thread, 2> threads;
6426     threads[0] = std::thread(queryAndCheck, hostname1, records);
6427     threads[1] = std::thread(queryAndCheck, hostname2, records);
6428 
6429     threads[0].join();
6430     threads[1].join();
6431 
6432     // Also check no additional queries due to DoT reconnection.
6433     EXPECT_TRUE(tls.waitForQueries(2));
6434 }
6435 
TEST_F(ResolverTest,MdnsGetHostByName)6436 TEST_F(ResolverTest, MdnsGetHostByName) {
6437     constexpr char v6addr[] = "::127.0.0.3";
6438     constexpr char v4addr[] = "127.0.0.3";
6439     constexpr char host_name[] = "hello.local.";
6440     constexpr char nonexistent_host_name[] = "nonexistent.local.";
6441 
6442     test::DNSResponder mdnsv4("127.0.0.3", test::kDefaultMdnsListenService);
6443     mdnsv4.addMapping(host_name, ns_type::ns_t_a, v4addr);
6444     test::DNSResponder mdnsv6("::1", test::kDefaultMdnsListenService);
6445     mdnsv6.addMapping(host_name, ns_type::ns_t_aaaa, v6addr);
6446 
6447     ASSERT_TRUE(mdnsv4.startServer());
6448     ASSERT_TRUE(mdnsv6.startServer());
6449     mdnsv4.clearQueries();
6450     mdnsv6.clearQueries();
6451 
6452     std::vector<bool> keep_listening_udp_enable = {false, true};
6453     for (int value : keep_listening_udp_enable) {
6454         if (value == true) {
6455             // Set keep_listening_udp enable
6456             ScopedSystemProperties sp(kKeepListeningUdpFlag, "1");
6457             // Re-setup test network to make experiment flag take effect.
6458             resetNetwork();
6459         }
6460         ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
6461 
6462         static const struct TestConfig {
6463             int ai_family;
6464             const std::string expected_addr;
6465         } testConfigs[]{
6466                 {AF_INET, v4addr},
6467                 {AF_INET6, v6addr},
6468         };
6469 
6470         for (const auto& config : testConfigs) {
6471             SCOPED_TRACE(fmt::format("family: {}", config.ai_family));
6472             const hostent* result = nullptr;
6473 
6474             // No response for "nonexistent.local".
6475             result = gethostbyname2("nonexistent.local", config.ai_family);
6476             ASSERT_TRUE(result == nullptr);
6477             test::DNSResponder& mdns = config.ai_family == AF_INET ? mdnsv4 : mdnsv6;
6478             EXPECT_EQ(1U, GetNumQueries(mdns, nonexistent_host_name));
6479             mdns.clearQueries();
6480             EXPECT_EQ(HOST_NOT_FOUND, h_errno);
6481 
6482             // Normal mDns query
6483             result = gethostbyname2("hello.local", config.ai_family);
6484             ASSERT_FALSE(result == nullptr);
6485             EXPECT_EQ(1U, GetNumQueries(mdns, host_name));
6486             int length = config.ai_family == AF_INET ? 4 : 16;
6487             ASSERT_EQ(length, result->h_length);
6488             ASSERT_FALSE(result->h_addr_list[0] == nullptr);
6489             EXPECT_EQ(config.expected_addr, ToString(result));
6490             EXPECT_TRUE(result->h_addr_list[1] == nullptr);
6491             mdns.clearQueries();
6492 
6493             // Ensure the query result is still cached.
6494             result = gethostbyname2("hello.local", config.ai_family);
6495             EXPECT_EQ(0U, GetNumQueries(mdnsv4, "hello.local."));
6496             ASSERT_FALSE(result == nullptr);
6497             EXPECT_EQ(config.expected_addr, ToString(result));
6498             ASSERT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
6499         }
6500     }
6501 }
6502 
6503 namespace {
6504 
6505 static const struct TransportTypeConfig {
6506     const std::vector<int32_t>& transportTypes;
6507     bool useMdns;
6508 } transportTypeConfig[]{
6509         // clang-format off
6510         {{}, true},
6511         {{IDnsResolver::TRANSPORT_CELLULAR}, false},
6512         {{IDnsResolver::TRANSPORT_WIFI}, true},
6513         {{IDnsResolver::TRANSPORT_BLUETOOTH}, true},
6514         {{IDnsResolver::TRANSPORT_ETHERNET}, true},
6515         {{IDnsResolver::TRANSPORT_VPN}, false},
6516         {{IDnsResolver::TRANSPORT_WIFI_AWARE}, true},
6517         {{IDnsResolver::TRANSPORT_LOWPAN}, true},
6518         {{IDnsResolver::TRANSPORT_TEST}, true},
6519         {{IDnsResolver::TRANSPORT_USB}, true},
6520         {{IDnsResolver::TRANSPORT_CELLULAR, IDnsResolver::TRANSPORT_VPN}, false},
6521         {{IDnsResolver::TRANSPORT_WIFI, IDnsResolver::TRANSPORT_VPN}, false},
6522         {{IDnsResolver::TRANSPORT_BLUETOOTH, IDnsResolver::TRANSPORT_VPN}, false},
6523         {{IDnsResolver::TRANSPORT_ETHERNET, IDnsResolver::TRANSPORT_VPN}, false},
6524         {{IDnsResolver::TRANSPORT_CELLULAR, IDnsResolver::TRANSPORT_WIFI,
6525           IDnsResolver::TRANSPORT_VPN}, false},
6526         {{IDnsResolver::TRANSPORT_WIFI_AWARE, IDnsResolver::TRANSPORT_VPN}, false},
6527         {{IDnsResolver::TRANSPORT_LOWPAN, IDnsResolver::TRANSPORT_VPN}, false},
6528         {{IDnsResolver::TRANSPORT_TEST, IDnsResolver::TRANSPORT_VPN}, false},
6529         {{IDnsResolver::TRANSPORT_USB, IDnsResolver::TRANSPORT_VPN}, false},
6530         // clang-format on
6531 };
6532 
6533 }  // namespace
6534 
TEST_F(ResolverTest,MdnsGetHostByName_transportTypes)6535 TEST_F(ResolverTest, MdnsGetHostByName_transportTypes) {
6536     constexpr char v6addr[] = "::127.0.0.3";
6537     constexpr char v4addr[] = "127.0.0.3";
6538     constexpr char host_name[] = "hello.local.";
6539 
6540     test::DNSResponder mdnsv4("127.0.0.3", test::kDefaultMdnsListenService);
6541     test::DNSResponder mdnsv6("::1", test::kDefaultMdnsListenService);
6542     mdnsv4.addMapping(host_name, ns_type::ns_t_a, v4addr);
6543     mdnsv6.addMapping(host_name, ns_type::ns_t_aaaa, v6addr);
6544     ASSERT_TRUE(mdnsv4.startServer());
6545     ASSERT_TRUE(mdnsv6.startServer());
6546 
6547     const std::vector<DnsRecord> records = {
6548             {host_name, ns_type::ns_t_a, v4addr},
6549             {host_name, ns_type::ns_t_aaaa, v6addr},
6550     };
6551     test::DNSResponder dns(v4addr);
6552     StartDns(dns, records);
6553 
6554     for (const auto& tpConfig : transportTypeConfig) {
6555         SCOPED_TRACE(fmt::format("transportTypes: [{}], useMdns: {}",
6556                                  fmt::join(tpConfig.transportTypes, ","), tpConfig.useMdns));
6557         ResolverParamsParcel setupParams = DnsResponderClient::GetDefaultResolverParamsParcel();
6558         setupParams.transportTypes = tpConfig.transportTypes;
6559         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(setupParams));
6560 
6561         static const struct TestConfig {
6562             int ai_family;
6563             const std::string expected_addr;
6564         } testConfigs[]{
6565                 {AF_INET, v4addr},
6566                 {AF_INET6, v6addr},
6567         };
6568 
6569         for (const auto& config : testConfigs) {
6570             SCOPED_TRACE(fmt::format("family: {}", config.ai_family));
6571             const hostent* result = nullptr;
6572             test::DNSResponder& mdns = config.ai_family == AF_INET ? mdnsv4 : mdnsv6;
6573 
6574             result = gethostbyname2("hello.local", config.ai_family);
6575             ASSERT_FALSE(result == nullptr);
6576             if (tpConfig.useMdns) {
6577                 EXPECT_EQ(1U, GetNumQueries(mdns, host_name));
6578                 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
6579             } else {
6580                 EXPECT_EQ(0U, GetNumQueries(mdns, host_name));
6581                 EXPECT_EQ(1U, GetNumQueries(dns, host_name));
6582             }
6583             int length = config.ai_family == AF_INET ? 4 : 16;
6584             ASSERT_EQ(length, result->h_length);
6585             ASSERT_FALSE(result->h_addr_list[0] == nullptr);
6586             EXPECT_EQ(config.expected_addr, ToString(result));
6587             EXPECT_TRUE(result->h_addr_list[1] == nullptr);
6588 
6589             mdns.clearQueries();
6590             dns.clearQueries();
6591             ASSERT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
6592         }
6593     }
6594 }
6595 
TEST_F(ResolverTest,MdnsGetHostByName_cnames)6596 TEST_F(ResolverTest, MdnsGetHostByName_cnames) {
6597     constexpr char v6addr[] = "::127.0.0.3";
6598     constexpr char v4addr[] = "127.0.0.3";
6599     constexpr char host_name[] = "hello.local.";
6600     const std::vector<DnsRecord> records = {
6601             {"hi.local.", ns_type::ns_t_cname, "a.local."},
6602             {"a.local.", ns_type::ns_t_cname, "b.local."},
6603             {"b.local.", ns_type::ns_t_cname, "c.local."},
6604             {"c.local.", ns_type::ns_t_cname, "d.local."},
6605             {"d.local.", ns_type::ns_t_cname, "e.local."},
6606             {"e.local.", ns_type::ns_t_cname, host_name},
6607             {host_name, ns_type::ns_t_a, v4addr},
6608             {host_name, ns_type::ns_t_aaaa, v6addr},
6609     };
6610     test::DNSResponder mdnsv4("127.0.0.3", test::kDefaultMdnsListenService);
6611     for (const auto& r : records) {
6612         mdnsv4.addMapping(r.host_name, r.type, r.addr);
6613     }
6614     test::DNSResponder mdnsv6("::1", test::kDefaultMdnsListenService);
6615     for (const auto& r : records) {
6616         mdnsv6.addMapping(r.host_name, r.type, r.addr);
6617     }
6618     ASSERT_TRUE(mdnsv4.startServer());
6619     ASSERT_TRUE(mdnsv6.startServer());
6620     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
6621     mdnsv4.clearQueries();
6622     mdnsv6.clearQueries();
6623 
6624     static const struct TestConfig {
6625         int ai_family;
6626         const std::string expected_addr;
6627     } testConfigs[]{
6628             {AF_INET, v4addr},
6629             {AF_INET6, v6addr},
6630     };
6631 
6632     for (const auto& config : testConfigs) {
6633         size_t cnamecount = 0;
6634         // using gethostbyname2() to resolve ipv4 hello.local. to 127.0.0.3
6635         // or ipv6 hello.local. to ::127.0.0.3.
6636         // Ensure the v4 address and cnames are correct
6637         const hostent* result;
6638         result = gethostbyname2("hi.local", config.ai_family);
6639         ASSERT_FALSE(result == nullptr);
6640 
6641         for (int i = 0; result != nullptr && result->h_aliases[i] != nullptr; i++) {
6642             std::string domain_name =
6643                     records[i].host_name.substr(0, records[i].host_name.size() - 1);
6644             EXPECT_EQ(result->h_aliases[i], domain_name);
6645             cnamecount++;
6646         }
6647         // The size of "Non-cname type" record in DNS records is 2
6648         ASSERT_EQ(cnamecount, records.size() - 2);
6649         test::DNSResponder& mdns = config.ai_family == AF_INET ? mdnsv4 : mdnsv6;
6650         EXPECT_EQ(1U, mdnsv4.queries().size()) << mdns.dumpQueries();
6651         int length = config.ai_family == AF_INET ? 4 : 16;
6652         ASSERT_EQ(length, result->h_length);
6653 
6654         ASSERT_FALSE(result->h_addr_list[0] == nullptr);
6655         EXPECT_EQ(config.expected_addr, ToString(result));
6656         EXPECT_TRUE(result->h_addr_list[1] == nullptr);
6657     }
6658 }
6659 
TEST_F(ResolverTest,MdnsGetHostByName_cnamesInfiniteLoop)6660 TEST_F(ResolverTest, MdnsGetHostByName_cnamesInfiniteLoop) {
6661     constexpr char host_name1[] = "hello.local.";
6662     constexpr char host_name2[] = "hi.local.";
6663     const std::vector<DnsRecord> records = {
6664             {host_name1, ns_type::ns_t_cname, host_name2},
6665             {host_name2, ns_type::ns_t_cname, host_name1},
6666     };
6667 
6668     test::DNSResponder mdnsv4("127.0.0.3", test::kDefaultMdnsListenService);
6669     test::DNSResponder mdnsv6("::1", test::kDefaultMdnsListenService);
6670     for (const auto& r : records) {
6671         mdnsv4.addMapping(r.host_name, r.type, r.addr);
6672     }
6673     for (const auto& r : records) {
6674         mdnsv6.addMapping(r.host_name, r.type, r.addr);
6675     }
6676     ASSERT_TRUE(mdnsv4.startServer());
6677     ASSERT_TRUE(mdnsv6.startServer());
6678     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
6679     mdnsv4.clearQueries();
6680     mdnsv6.clearQueries();
6681 
6682     const hostent* result;
6683     result = gethostbyname2("hello.local", AF_INET);
6684     ASSERT_TRUE(result == nullptr);
6685 
6686     result = gethostbyname2("hello.local", AF_INET6);
6687     ASSERT_TRUE(result == nullptr);
6688 }
6689 
TEST_F(ResolverTest,MdnsGetAddrInfo)6690 TEST_F(ResolverTest, MdnsGetAddrInfo) {
6691     constexpr char v6addr[] = "::127.0.0.3";
6692     constexpr char v4addr[] = "127.0.0.3";
6693     constexpr char host_name[] = "hello.local.";
6694     test::DNSResponder mdnsv4("127.0.0.3", test::kDefaultMdnsListenService);
6695     test::DNSResponder mdnsv6("::1", test::kDefaultMdnsListenService);
6696     mdnsv4.addMapping(host_name, ns_type::ns_t_a, v4addr);
6697     mdnsv6.addMapping(host_name, ns_type::ns_t_aaaa, v6addr);
6698     ASSERT_TRUE(mdnsv4.startServer());
6699     ASSERT_TRUE(mdnsv6.startServer());
6700 
6701     std::vector<bool> keep_listening_udp_enable = {false, true};
6702     for (int value : keep_listening_udp_enable) {
6703         if (value == true) {
6704             // Set keep_listening_udp enable
6705             ScopedSystemProperties sp(kKeepListeningUdpFlag, "1");
6706             // Re-setup test network to make experiment flag take effect.
6707             resetNetwork();
6708         }
6709 
6710         ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
6711         static const struct TestConfig {
6712             int ai_family;
6713             const std::vector<std::string> expected_addr;
6714         } testConfigs[]{
6715                 {AF_INET, {v4addr}},
6716                 {AF_INET6, {v6addr}},
6717                 {AF_UNSPEC, {v4addr, v6addr}},
6718         };
6719 
6720         for (const auto& config : testConfigs) {
6721             mdnsv4.clearQueries();
6722             mdnsv6.clearQueries();
6723             addrinfo hints = {.ai_family = config.ai_family, .ai_socktype = SOCK_DGRAM};
6724             ScopedAddrinfo result = safe_getaddrinfo("hello.local", nullptr, &hints);
6725 
6726             EXPECT_TRUE(result != nullptr);
6727             if (config.ai_family == AF_INET) {
6728                 EXPECT_EQ(1U, GetNumQueries(mdnsv4, host_name));
6729                 mdnsv4.clearQueries();
6730             } else if (config.ai_family == AF_INET6) {
6731                 EXPECT_EQ(1U, GetNumQueries(mdnsv6, host_name));
6732                 mdnsv6.clearQueries();
6733             } else if (config.ai_family == AF_UNSPEC) {
6734                 EXPECT_EQ(1U, GetNumQueries(mdnsv4, host_name));
6735                 EXPECT_EQ(1U, GetNumQueries(mdnsv6, host_name));
6736                 mdnsv4.clearQueries();
6737                 mdnsv6.clearQueries();
6738             }
6739             std::string result_str = ToString(result);
6740             EXPECT_THAT(ToStrings(result),
6741                         testing::UnorderedElementsAreArray(config.expected_addr));
6742 
6743             // Ensure the query results are still cached.
6744             result = safe_getaddrinfo("hello.local", nullptr, &hints);
6745             EXPECT_TRUE(result != nullptr);
6746             if (config.ai_family == AF_INET)
6747                 EXPECT_EQ(0U, GetNumQueries(mdnsv4, host_name));
6748             else if (config.ai_family == AF_INET6)
6749                 EXPECT_EQ(0U, GetNumQueries(mdnsv6, host_name));
6750             else if (config.ai_family == AF_UNSPEC) {
6751                 EXPECT_EQ(0U, GetNumQueries(mdnsv4, host_name));
6752                 EXPECT_EQ(0U, GetNumQueries(mdnsv6, host_name));
6753             }
6754             result_str = ToString(result);
6755             EXPECT_THAT(ToStrings(result),
6756                         testing::UnorderedElementsAreArray(config.expected_addr));
6757             ASSERT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
6758         }
6759     }
6760 }
6761 
TEST_F(ResolverTest,MdnsGetAddrInfo_transportTypes)6762 TEST_F(ResolverTest, MdnsGetAddrInfo_transportTypes) {
6763     constexpr char v6addr[] = "::127.0.0.3";
6764     constexpr char v4addr[] = "127.0.0.3";
6765     constexpr char host_name[] = "hello.local.";
6766     test::DNSResponder mdnsv4("127.0.0.3", test::kDefaultMdnsListenService);
6767     test::DNSResponder mdnsv6("::1", test::kDefaultMdnsListenService);
6768     mdnsv4.addMapping(host_name, ns_type::ns_t_a, v4addr);
6769     mdnsv6.addMapping(host_name, ns_type::ns_t_aaaa, v6addr);
6770     ASSERT_TRUE(mdnsv4.startServer());
6771     ASSERT_TRUE(mdnsv6.startServer());
6772 
6773     const std::vector<DnsRecord> records = {
6774             {host_name, ns_type::ns_t_a, v4addr},
6775             {host_name, ns_type::ns_t_aaaa, v6addr},
6776     };
6777     test::DNSResponder dns(v4addr);
6778     StartDns(dns, records);
6779 
6780     for (const auto& tpConfig : transportTypeConfig) {
6781         SCOPED_TRACE(fmt::format("transportTypes: [{}], useMdns: {}",
6782                                  fmt::join(tpConfig.transportTypes, ","), tpConfig.useMdns));
6783         ResolverParamsParcel setupParams = DnsResponderClient::GetDefaultResolverParamsParcel();
6784         setupParams.transportTypes = tpConfig.transportTypes;
6785         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(setupParams));
6786 
6787         static const struct TestConfig {
6788             int ai_family;
6789             const std::vector<std::string> expected_addr;
6790         } testConfigs[]{
6791                 {AF_INET, {v4addr}},
6792                 {AF_INET6, {v6addr}},
6793                 {AF_UNSPEC, {v4addr, v6addr}},
6794         };
6795 
6796         for (const auto& config : testConfigs) {
6797             addrinfo hints = {.ai_family = config.ai_family, .ai_socktype = SOCK_DGRAM};
6798             ScopedAddrinfo result = safe_getaddrinfo("hello.local", nullptr, &hints);
6799 
6800             EXPECT_TRUE(result != nullptr);
6801             if (tpConfig.useMdns) {
6802                 if (config.ai_family == AF_INET) {
6803                     EXPECT_EQ(1U, GetNumQueries(mdnsv4, host_name));
6804                     EXPECT_EQ(0U, GetNumQueries(mdnsv6, host_name));
6805                 } else if (config.ai_family == AF_INET6) {
6806                     EXPECT_EQ(0U, GetNumQueries(mdnsv4, host_name));
6807                     EXPECT_EQ(1U, GetNumQueries(mdnsv6, host_name));
6808                 } else {
6809                     EXPECT_EQ(1U, GetNumQueries(mdnsv4, host_name));
6810                     EXPECT_EQ(1U, GetNumQueries(mdnsv6, host_name));
6811                 }
6812                 EXPECT_EQ(0U, GetNumQueries(dns, host_name));
6813             } else {
6814                 EXPECT_EQ(0U, GetNumQueries(mdnsv4, host_name));
6815                 EXPECT_EQ(0U, GetNumQueries(mdnsv6, host_name));
6816                 if (config.ai_family == AF_INET || config.ai_family == AF_INET6) {
6817                     EXPECT_EQ(1U, GetNumQueries(dns, host_name));
6818                 } else {
6819                     EXPECT_EQ(2U, GetNumQueries(dns, host_name));
6820                 }
6821             }
6822             std::string result_str = ToString(result);
6823             EXPECT_THAT(ToStrings(result),
6824                         testing::UnorderedElementsAreArray(config.expected_addr));
6825 
6826             mdnsv4.clearQueries();
6827             mdnsv6.clearQueries();
6828             dns.clearQueries();
6829             ASSERT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
6830         }
6831     }
6832 }
6833 
TEST_F(ResolverTest,MdnsGetAddrInfo_InvalidSocketType)6834 TEST_F(ResolverTest, MdnsGetAddrInfo_InvalidSocketType) {
6835     constexpr char v6addr[] = "::127.0.0.3";
6836     constexpr char host_name[] = "hello.local.";
6837 
6838     test::DNSResponder mdnsv6("::1", test::kDefaultMdnsListenService);
6839     mdnsv6.addMapping(host_name, ns_type::ns_t_aaaa, v6addr);
6840     ASSERT_TRUE(mdnsv6.startServer());
6841     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
6842 
6843     // TODO: Test other invalid socket types.
6844     const addrinfo hints = {
6845             .ai_family = AF_UNSPEC,
6846             .ai_socktype = SOCK_PACKET,
6847     };
6848     addrinfo* result = nullptr;
6849     // This is a valid hint, but the query won't be sent because the socket type is
6850     // not supported.
6851     EXPECT_EQ(EAI_NODATA, getaddrinfo("howdy.local", nullptr, &hints, &result));
6852     ScopedAddrinfo result_cleanup(result);
6853     EXPECT_EQ(nullptr, result);
6854 }
6855 
TEST_F(ResolverTest,MdnsGetAddrInfo_cnames)6856 TEST_F(ResolverTest, MdnsGetAddrInfo_cnames) {
6857     constexpr char v6addr[] = "::127.0.0.3";
6858     constexpr char v4addr[] = "127.0.0.3";
6859     constexpr char host_name[] = "hello.local.";
6860     test::DNSResponder mdnsv4("127.0.0.3", test::kDefaultMdnsListenService);
6861     test::DNSResponder mdnsv6("::1", test::kDefaultMdnsListenService);
6862     const std::vector<DnsRecord> records = {
6863             {"hi.local.", ns_type::ns_t_cname, "a.local."},
6864             {"a.local.", ns_type::ns_t_cname, "b.local."},
6865             {"b.local.", ns_type::ns_t_cname, "c.local."},
6866             {"c.local.", ns_type::ns_t_cname, "d.local."},
6867             {"d.local.", ns_type::ns_t_cname, "e.local."},
6868             {"e.local.", ns_type::ns_t_cname, host_name},
6869             {host_name, ns_type::ns_t_a, v4addr},
6870             {host_name, ns_type::ns_t_aaaa, v6addr},
6871     };
6872     for (const auto& r : records) {
6873         mdnsv4.addMapping(r.host_name, r.type, r.addr);
6874     }
6875     for (const auto& r : records) {
6876         mdnsv6.addMapping(r.host_name, r.type, r.addr);
6877     }
6878     ASSERT_TRUE(mdnsv4.startServer());
6879     ASSERT_TRUE(mdnsv6.startServer());
6880     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
6881 
6882     static const struct TestConfig {
6883         int ai_family;
6884         const std::vector<std::string> expected_addr;
6885     } testConfigs[]{
6886             {AF_INET, {v4addr}},
6887             {AF_INET6, {v6addr}},
6888             {AF_UNSPEC, {v4addr, v6addr}},
6889     };
6890     for (const auto& config : testConfigs) {
6891         mdnsv4.clearQueries();
6892         mdnsv6.clearQueries();
6893         addrinfo hints = {.ai_family = config.ai_family, .ai_socktype = SOCK_DGRAM};
6894         ScopedAddrinfo result = safe_getaddrinfo("hi.local", nullptr, &hints);
6895         EXPECT_TRUE(result != nullptr);
6896         EXPECT_THAT(ToStrings(result), testing::UnorderedElementsAreArray(config.expected_addr));
6897     }
6898 }
6899 
TEST_F(ResolverTest,MdnsGetAddrInfo_cnamesNoIpAddress)6900 TEST_F(ResolverTest, MdnsGetAddrInfo_cnamesNoIpAddress) {
6901     constexpr char host_name[] = "hello.local.";
6902     test::DNSResponder mdnsv4("127.0.0.3", test::kDefaultMdnsListenService);
6903     test::DNSResponder mdnsv6("::1", test::kDefaultMdnsListenService);
6904     mdnsv4.addMapping(host_name, ns_type::ns_t_cname, "a.local.");
6905     mdnsv6.addMapping(host_name, ns_type::ns_t_cname, "a.local.");
6906     ASSERT_TRUE(mdnsv4.startServer());
6907     ASSERT_TRUE(mdnsv6.startServer());
6908     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
6909 
6910     addrinfo hints = {.ai_family = AF_INET};
6911     ScopedAddrinfo result = safe_getaddrinfo("hello.local", nullptr, &hints);
6912     EXPECT_TRUE(result == nullptr);
6913 
6914     mdnsv4.clearQueries();
6915     hints = {.ai_family = AF_INET6};
6916     result = safe_getaddrinfo("hello.local", nullptr, &hints);
6917     EXPECT_TRUE(result == nullptr);
6918 
6919     mdnsv6.clearQueries();
6920     hints = {.ai_family = AF_UNSPEC};
6921     result = safe_getaddrinfo("hello.local", nullptr, &hints);
6922     EXPECT_TRUE(result == nullptr);
6923 }
6924 
TEST_F(ResolverTest,MdnsGetAddrInfo_cnamesIllegalRdata)6925 TEST_F(ResolverTest, MdnsGetAddrInfo_cnamesIllegalRdata) {
6926     constexpr char host_name[] = "hello.local.";
6927     test::DNSResponder mdnsv4("127.0.0.3", test::kDefaultMdnsListenService);
6928     test::DNSResponder mdnsv6("::1", test::kDefaultMdnsListenService);
6929     mdnsv4.addMapping(host_name, ns_type::ns_t_cname, ".!#?");
6930     mdnsv6.addMapping(host_name, ns_type::ns_t_cname, ".!#?");
6931     ASSERT_TRUE(mdnsv4.startServer());
6932     ASSERT_TRUE(mdnsv6.startServer());
6933     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
6934 
6935     addrinfo hints = {.ai_family = AF_INET};
6936     ScopedAddrinfo result = safe_getaddrinfo("hello.local", nullptr, &hints);
6937     EXPECT_TRUE(result == nullptr);
6938 
6939     mdnsv4.clearQueries();
6940     hints = {.ai_family = AF_INET6};
6941     result = safe_getaddrinfo("hello.local", nullptr, &hints);
6942     EXPECT_TRUE(result == nullptr);
6943 
6944     mdnsv6.clearQueries();
6945     hints = {.ai_family = AF_UNSPEC};
6946     result = safe_getaddrinfo("hello.local", nullptr, &hints);
6947     EXPECT_TRUE(result == nullptr);
6948 }
6949 
6950 // Test if .local resolution will try unicast when multicast is failed.
TEST_F(ResolverTest,MdnsGetAddrInfo_fallback)6951 TEST_F(ResolverTest, MdnsGetAddrInfo_fallback) {
6952     constexpr char v6addr[] = "::1.2.3.4";
6953     constexpr char v4addr[] = "1.2.3.4";
6954     constexpr char host_name[] = "hello.local.";
6955     test::DNSResponder mdnsv4("127.0.0.3", test::kDefaultMdnsListenService,
6956                               static_cast<ns_rcode>(-1));
6957     test::DNSResponder mdnsv6("::1", test::kDefaultMdnsListenService, static_cast<ns_rcode>(-1));
6958     // Set unresponsive on multicast.
6959     mdnsv4.setResponseProbability(0.0);
6960     mdnsv6.setResponseProbability(0.0);
6961     ASSERT_TRUE(mdnsv4.startServer());
6962     ASSERT_TRUE(mdnsv6.startServer());
6963 
6964     const std::vector<DnsRecord> records = {
6965             {host_name, ns_type::ns_t_a, v4addr},
6966             {host_name, ns_type::ns_t_aaaa, v6addr},
6967     };
6968     test::DNSResponder dns("127.0.0.3");
6969     StartDns(dns, records);
6970     ASSERT_TRUE(mDnsClient.SetResolversForNetwork());
6971 
6972     static const struct TestConfig {
6973         int ai_family;
6974         const std::vector<std::string> expected_addr;
6975     } testConfigs[]{
6976             {AF_INET, {v4addr}},
6977             {AF_INET6, {v6addr}},
6978             {AF_UNSPEC, {v4addr, v6addr}},
6979     };
6980 
6981     for (const auto& config : testConfigs) {
6982         SCOPED_TRACE(fmt::format("family: {}", config.ai_family));
6983         addrinfo hints = {.ai_family = config.ai_family, .ai_socktype = SOCK_DGRAM};
6984         ScopedAddrinfo result = safe_getaddrinfo("hello.local", nullptr, &hints);
6985         EXPECT_TRUE(result != nullptr);
6986         if (config.ai_family == AF_INET) {
6987             EXPECT_EQ(1U, GetNumQueries(mdnsv4, host_name));
6988             EXPECT_EQ(0U, GetNumQueries(mdnsv6, host_name));
6989             EXPECT_EQ(1U, GetNumQueries(dns, host_name));
6990         } else if (config.ai_family == AF_INET6) {
6991             EXPECT_EQ(0U, GetNumQueries(mdnsv4, host_name));
6992             EXPECT_EQ(1U, GetNumQueries(mdnsv6, host_name));
6993             EXPECT_EQ(1U, GetNumQueries(dns, host_name));
6994         } else {
6995             EXPECT_EQ(1U, GetNumQueries(mdnsv4, host_name));
6996             EXPECT_EQ(1U, GetNumQueries(mdnsv6, host_name));
6997             EXPECT_EQ(2U, GetNumQueries(dns, host_name));
6998         }
6999         EXPECT_THAT(ToStrings(result), testing::UnorderedElementsAreArray(config.expected_addr));
7000 
7001         mdnsv4.clearQueries();
7002         mdnsv6.clearQueries();
7003         dns.clearQueries();
7004         ASSERT_TRUE(mDnsClient.resolvService()->flushNetworkCache(TEST_NETID).isOk());
7005     }
7006 }
7007 
7008 // ResolverMultinetworkTest is used to verify multinetwork functionality. Here's how it works:
7009 // The resolver sends queries to address A, and then there will be a TunForwarder helping forward
7010 // the packets to address B, which is the address on which the testing server is listening. The
7011 // answer packets responded from the testing server go through the reverse path back to the
7012 // resolver.
7013 //
7014 // To achieve the that, it needs to set up a interface with routing rules. Tests are not
7015 // supposed to initiate DNS servers on their own; instead, some utilities are added to the class to
7016 // help the setup.
7017 //
7018 // An example of how to use it:
7019 // TEST_F() {
7020 //     ScopedPhysicalNetwork network = CreateScopedPhysicalNetwork(V4);
7021 //     network.init();
7022 //
7023 //     auto dns = network.addIpv4Dns();
7024 //     StartDns(dns.dnsServer, {});
7025 //
7026 //     network.setDnsConfiguration();
7027 //     network.startTunForwarder();
7028 //
7029 //     // Send queries here
7030 // }
7031 
7032 class ResolverMultinetworkTest : public ResolverTest {
7033   protected:
7034     enum class ConnectivityType { V4, V6, V4V6 };
7035     static constexpr int TEST_NETID_BASE = 10000;
7036 
7037     struct DnsServerPair {
DnsServerPairResolverMultinetworkTest::DnsServerPair7038         DnsServerPair(std::shared_ptr<test::DNSResponder> server, std::string addr)
7039             : dnsServer(server), dnsAddr(addr) {}
7040         std::shared_ptr<test::DNSResponder> dnsServer;
7041         std::string dnsAddr;  // The DNS server address used for setResolverConfiguration().
7042         // TODO: Add test::DnsTlsFrontend* and std::string for DoT.
7043     };
7044 
7045     class ScopedNetwork {
7046       public:
ScopedNetwork(unsigned netId,ConnectivityType type,INetd * netdSrv,IDnsResolver * dnsResolvSrv,const char * networkName)7047         ScopedNetwork(unsigned netId, ConnectivityType type, INetd* netdSrv,
7048                       IDnsResolver* dnsResolvSrv, const char* networkName)
7049             : mNetId(netId),
7050               mConnectivityType(type),
7051               mNetdSrv(netdSrv),
7052               mDnsResolvSrv(dnsResolvSrv),
7053               mNetworkName(networkName) {
7054             mIfname = fmt::format("testtun{}", netId);
7055         }
~ScopedNetwork()7056         virtual ~ScopedNetwork() {
7057             if (mNetdSrv != nullptr) mNetdSrv->networkDestroy(mNetId);
7058             if (mDnsResolvSrv != nullptr) mDnsResolvSrv->destroyNetworkCache(mNetId);
7059         }
7060 
7061         Result<void> init();
addIpv4Dns()7062         Result<DnsServerPair> addIpv4Dns() { return addDns(ConnectivityType::V4); }
addIpv6Dns()7063         Result<DnsServerPair> addIpv6Dns() { return addDns(ConnectivityType::V6); }
startTunForwarder()7064         bool startTunForwarder() { return mTunForwarder->startForwarding(); }
7065         bool setDnsConfiguration() const;
7066         bool clearDnsConfiguration() const;
netId() const7067         unsigned netId() const { return mNetId; }
name() const7068         std::string name() const { return mNetworkName; }
addUser(uid_t uid) const7069         Result<void> addUser(uid_t uid) const { return addUidRange(uid, uid); }
addUidRange(uid_t from,uid_t to) const7070         Result<void> addUidRange(uid_t from, uid_t to) const {
7071             if (auto r = mNetdSrv->networkAddUidRanges(mNetId, {makeUidRangeParcel(from, to)});
7072                 !r.isOk()) {
7073                 return Error() << r.getMessage();
7074             }
7075             return {};
7076         }
7077 
addUserFromParcel(uid_t uid,int32_t subPriority) const7078         Result<void> addUserFromParcel(uid_t uid, int32_t subPriority) const {
7079             return addUidRangeFromParcel(uid, uid, subPriority);
7080         }
7081 
addUidRangeFromParcel(uid_t from,uid_t to,int32_t subPriority) const7082         Result<void> addUidRangeFromParcel(uid_t from, uid_t to, int32_t subPriority) const {
7083             NativeUidRangeConfig cfg =
7084                     makeNativeUidRangeConfig(mNetId, {makeUidRangeParcel(from, to)}, subPriority);
7085             if (auto r = mNetdSrv->networkAddUidRangesParcel(cfg); !r.isOk()) {
7086                 return Error() << r.getMessage();
7087             }
7088             return {};
7089         }
7090 
ifname()7091         const std::string& ifname() { return mIfname; }
7092         // Assuming mNetId is unique during ResolverMultinetworkTest, make the
7093         // address based on it to avoid conflicts.
makeIpv4AddrString(uint8_t n) const7094         std::string makeIpv4AddrString(uint8_t n) const {
7095             return fmt::format("192.168.{}.{}", (mNetId - TEST_NETID_BASE), n);
7096         }
makeIpv6AddrString(uint8_t n) const7097         std::string makeIpv6AddrString(uint8_t n) const {
7098             return fmt::format("2001:db8:{}::{}", (mNetId - TEST_NETID_BASE), n);
7099         }
7100 
7101       protected:
7102         // Subclasses should implement it to decide which network should be create.
7103         virtual Result<void> createNetwork() const = 0;
7104 
7105         const unsigned mNetId;
7106         const ConnectivityType mConnectivityType;
7107         INetd* mNetdSrv;
7108         IDnsResolver* mDnsResolvSrv;
7109         const std::string mNetworkName;
7110         std::string mIfname;
7111         std::unique_ptr<TunForwarder> mTunForwarder;
7112         std::vector<DnsServerPair> mDnsServerPairs;
7113 
7114       private:
7115         Result<DnsServerPair> addDns(ConnectivityType connectivity);
7116     };
7117 
7118     class ScopedPhysicalNetwork : public ScopedNetwork {
7119       public:
ScopedPhysicalNetwork(unsigned netId,const char * networkName)7120         ScopedPhysicalNetwork(unsigned netId, const char* networkName)
7121             : ScopedNetwork(netId, ConnectivityType::V4V6, nullptr, nullptr, networkName) {}
ScopedPhysicalNetwork(unsigned netId,ConnectivityType type,INetd * netdSrv,IDnsResolver * dnsResolvSrv,const char * name="Physical")7122         ScopedPhysicalNetwork(unsigned netId, ConnectivityType type, INetd* netdSrv,
7123                               IDnsResolver* dnsResolvSrv, const char* name = "Physical")
7124             : ScopedNetwork(netId, type, netdSrv, dnsResolvSrv, name) {}
7125 
7126       protected:
createNetwork() const7127         Result<void> createNetwork() const override {
7128             ::ndk::ScopedAStatus r;
7129             if (DnsResponderClient::isRemoteVersionSupported(mNetdSrv, 6)) {
7130                 const auto& config = DnsResponderClient::makeNativeNetworkConfig(
7131                         mNetId, NativeNetworkType::PHYSICAL, INetd::PERMISSION_NONE,
7132                         /*secure=*/false);
7133                 r = mNetdSrv->networkCreate(config);
7134             } else {
7135 #pragma clang diagnostic push
7136 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
7137                 r = mNetdSrv->networkCreatePhysical(mNetId, INetd::PERMISSION_NONE);
7138 #pragma clang diagnostic pop
7139             }
7140 
7141             if (!r.isOk()) {
7142                 return Error() << r.getMessage();
7143             }
7144             return {};
7145         }
7146     };
7147 
7148     class ScopedVirtualNetwork : public ScopedNetwork {
7149       public:
ScopedVirtualNetwork(unsigned netId,ConnectivityType type,INetd * netdSrv,IDnsResolver * dnsResolvSrv,const char * name,bool isSecure)7150         ScopedVirtualNetwork(unsigned netId, ConnectivityType type, INetd* netdSrv,
7151                              IDnsResolver* dnsResolvSrv, const char* name, bool isSecure)
7152             : ScopedNetwork(netId, type, netdSrv, dnsResolvSrv, name), mIsSecure(isSecure) {
7153             if (android::modules::sdklevel::IsAtLeastT()) {
7154                 mFw = Firewall::getInstance();
7155             }
7156         }
~ScopedVirtualNetwork()7157         ~ScopedVirtualNetwork() {
7158             if (!mVpnIsolationUids.empty()) {
7159                 const std::vector<int> tmpUids(mVpnIsolationUids.begin(), mVpnIsolationUids.end());
7160                 mNetdSrv->firewallRemoveUidInterfaceRules(tmpUids);
7161             }
7162         }
7163         // Enable VPN isolation. Ensures that uid can only receive packets on mIfname.
enableVpnIsolation(int uid)7164         Result<void> enableVpnIsolation(int uid) {
7165             if (android::modules::sdklevel::IsAtLeastT()) {
7166                 if (auto r = mFw->addUidInterfaceRules(mIfname, {uid}); !r.ok()) {
7167                     return r;
7168                 }
7169             } else if (auto r = mNetdSrv->firewallAddUidInterfaceRules(mIfname, {uid}); !r.isOk()) {
7170                 return Error() << r.getMessage();
7171             }
7172             mVpnIsolationUids.insert(uid);
7173             return {};
7174         }
disableVpnIsolation(int uid)7175         Result<void> disableVpnIsolation(int uid) {
7176             if (android::modules::sdklevel::IsAtLeastT()) {
7177                 if (auto r = mFw->removeUidInterfaceRules({uid}); !r.ok()) {
7178                     return r;
7179                 }
7180             } else if (auto r = mNetdSrv->firewallRemoveUidInterfaceRules({uid}); !r.isOk()) {
7181                 return Error() << r.getMessage();
7182             }
7183             mVpnIsolationUids.erase(uid);
7184             return {};
7185         }
7186 
7187       protected:
createNetwork() const7188         Result<void> createNetwork() const override {
7189             ::ndk::ScopedAStatus r;
7190             if (DnsResponderClient::isRemoteVersionSupported(mNetdSrv, 6)) {
7191                 const auto& config = DnsResponderClient::makeNativeNetworkConfig(
7192                         mNetId, NativeNetworkType::VIRTUAL, INetd::PERMISSION_NONE, mIsSecure);
7193                 r = mNetdSrv->networkCreate(config);
7194             } else {
7195 #pragma clang diagnostic push
7196 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
7197                 r = mNetdSrv->networkCreateVpn(mNetId, mIsSecure);
7198 #pragma clang diagnostic pop
7199             }
7200 
7201             if (!r.isOk()) {
7202                 return Error() << r.getMessage();
7203             }
7204             return {};
7205         }
7206 
7207         bool mIsSecure = false;
7208         std::unordered_set<int> mVpnIsolationUids;
7209         Firewall* mFw;
7210     };
7211 
SetUp()7212     void SetUp() override {
7213         ResolverTest::SetUp();
7214         ASSERT_NE(mDnsClient.netdService(), nullptr);
7215         ASSERT_NE(mDnsClient.resolvService(), nullptr);
7216     }
7217 
TearDown()7218     void TearDown() override {
7219         ResolverTest::TearDown();
7220         // Restore default network
7221         if (mStoredDefaultNetwork >= 0) {
7222             mDnsClient.netdService()->networkSetDefault(mStoredDefaultNetwork);
7223         }
7224     }
7225 
CreateScopedPhysicalNetwork(ConnectivityType type,const char * name="Physical")7226     ScopedPhysicalNetwork CreateScopedPhysicalNetwork(ConnectivityType type,
7227                                                       const char* name = "Physical") {
7228         return {getFreeNetId(), type, mDnsClient.netdService(), mDnsClient.resolvService(), name};
7229     }
CreateScopedVirtualNetwork(ConnectivityType type,bool isSecure,const char * name="Virtual")7230     ScopedVirtualNetwork CreateScopedVirtualNetwork(ConnectivityType type, bool isSecure,
7231                                                     const char* name = "Virtual") {
7232         return {getFreeNetId(), type,    mDnsClient.netdService(), mDnsClient.resolvService(),
7233                 name,           isSecure};
7234     }
7235     void StartDns(test::DNSResponder& dns, const std::vector<DnsRecord>& records);
setDefaultNetwork(int netId)7236     void setDefaultNetwork(int netId) {
7237         // Save current default network at the first call.
7238         std::call_once(defaultNetworkFlag, [&]() {
7239             ASSERT_TRUE(mDnsClient.netdService()->networkGetDefault(&mStoredDefaultNetwork).isOk());
7240         });
7241         ASSERT_TRUE(mDnsClient.netdService()->networkSetDefault(netId).isOk());
7242     }
getFreeNetId()7243     unsigned getFreeNetId() {
7244         if (mNextNetId == TEST_NETID_BASE + 256) mNextNetId = TEST_NETID_BASE;
7245         return mNextNetId++;
7246     }
7247     Result<std::shared_ptr<test::DNSResponder>> setupDns(ConnectivityType type, ScopedNetwork* nw,
7248                                                          const char* host_name,
7249                                                          const char* ipv4_addr,
7250                                                          const char* ipv6_addr);
7251 
expectDnsQueryCountsFn(std::shared_ptr<test::DNSResponder> dnsServer,const char * host_name,size_t count,unsigned expectedDnsNetId)7252     void expectDnsQueryCountsFn(std::shared_ptr<test::DNSResponder> dnsServer,
7253                                 const char* host_name, size_t count, unsigned expectedDnsNetId) {
7254         EXPECT_EQ(GetNumQueries(*dnsServer, host_name), count);
7255         EXPECT_TRUE(mDnsClient.resolvService()->flushNetworkCache(expectedDnsNetId).isOk());
7256         dnsServer->clearQueries();
7257     }
7258 
makeNativeUidRangeConfig(unsigned netId,std::vector<UidRangeParcel> uidRanges,int32_t subPriority)7259     static NativeUidRangeConfig makeNativeUidRangeConfig(unsigned netId,
7260                                                          std::vector<UidRangeParcel> uidRanges,
7261                                                          int32_t subPriority) {
7262         NativeUidRangeConfig res;
7263         res.netId = netId;
7264         res.uidRanges = std::move(uidRanges);
7265         res.subPriority = subPriority;
7266 
7267         return res;
7268     }
7269 
7270   private:
7271     // Use a different netId because this class inherits from the class ResolverTest which
7272     // always creates TEST_NETID in setup. It's incremented when CreateScoped{Physical,
7273     // Virtual}Network() is called.
7274     // Note: 255 is the maximum number of (mNextNetId - TEST_NETID_BASE) here as mNextNetId
7275     // is used to create address.
7276     unsigned mNextNetId = TEST_NETID_BASE;
7277     // Use -1 to represent that default network was not modified because
7278     // real netId must be an unsigned value.
7279     int mStoredDefaultNetwork = -1;
7280     std::once_flag defaultNetworkFlag;
7281 };
7282 
init()7283 Result<void> ResolverMultinetworkTest::ScopedNetwork::init() {
7284     if (mNetdSrv == nullptr || mDnsResolvSrv == nullptr) return Error() << "srv not available";
7285     unique_fd ufd = TunForwarder::createTun(mIfname);
7286     if (!ufd.ok()) {
7287         return Errorf("createTun for {} failed", mIfname);
7288     }
7289     mTunForwarder = std::make_unique<TunForwarder>(std::move(ufd));
7290 
7291     if (auto r = createNetwork(); !r.ok()) {
7292         return r;
7293     }
7294     if (auto r = mDnsResolvSrv->createNetworkCache(mNetId); !r.isOk()) {
7295         return Error() << r.getMessage();
7296     }
7297     if (auto r = mNetdSrv->networkAddInterface(mNetId, mIfname); !r.isOk()) {
7298         return Error() << r.getMessage();
7299     }
7300 
7301     if (mConnectivityType == ConnectivityType::V4 || mConnectivityType == ConnectivityType::V4V6) {
7302         const std::string v4Addr = makeIpv4AddrString(1);
7303         if (auto r = mNetdSrv->interfaceAddAddress(mIfname, v4Addr, 32); !r.isOk()) {
7304             return Error() << r.getMessage();
7305         }
7306         if (auto r = mNetdSrv->networkAddRoute(mNetId, mIfname, "0.0.0.0/0", ""); !r.isOk()) {
7307             return Error() << r.getMessage();
7308         }
7309     }
7310     if (mConnectivityType == ConnectivityType::V6 || mConnectivityType == ConnectivityType::V4V6) {
7311         const std::string v6Addr = makeIpv6AddrString(1);
7312         if (auto r = mNetdSrv->interfaceAddAddress(mIfname, v6Addr, 128); !r.isOk()) {
7313             return Error() << r.getMessage();
7314         }
7315         if (auto r = mNetdSrv->networkAddRoute(mNetId, mIfname, "::/0", ""); !r.isOk()) {
7316             return Error() << r.getMessage();
7317         }
7318     }
7319 
7320     return {};
7321 }
7322 
StartDns(test::DNSResponder & dns,const std::vector<DnsRecord> & records)7323 void ResolverMultinetworkTest::StartDns(test::DNSResponder& dns,
7324                                         const std::vector<DnsRecord>& records) {
7325     ResolverTest::StartDns(dns, records);
7326 
7327     // Bind the DNSResponder's sockets to the network if specified.
7328     if (std::optional<unsigned> netId = dns.getNetwork(); netId.has_value()) {
7329         setNetworkForSocket(netId.value(), dns.getUdpSocket());
7330         setNetworkForSocket(netId.value(), dns.getTcpSocket());
7331     }
7332 }
7333 
setupDns(ConnectivityType type,ScopedNetwork * nw,const char * host_name,const char * ipv4_addr,const char * ipv6_addr)7334 Result<std::shared_ptr<test::DNSResponder>> ResolverMultinetworkTest::setupDns(
7335         ConnectivityType type, ScopedNetwork* nw, const char* host_name, const char* ipv4_addr,
7336         const char* ipv6_addr) {
7337     // Add a testing DNS server to networks.
7338     const Result<DnsServerPair> dnsSvPair =
7339             (type == ConnectivityType::V4) ? nw->addIpv4Dns() : nw->addIpv6Dns();
7340     if (!dnsSvPair.ok()) return Error() << dnsSvPair.error();
7341 
7342     StartDns(*dnsSvPair->dnsServer,
7343              {{host_name, ns_type::ns_t_a, ipv4_addr}, {host_name, ns_type::ns_t_aaaa, ipv6_addr}});
7344     if (!nw->setDnsConfiguration()) return Error() << "setDnsConfiguration() failed";
7345     if (!nw->startTunForwarder()) return Error() << "startTunForwarder() failed";
7346     return dnsSvPair->dnsServer;
7347 }
7348 
addDns(ConnectivityType type)7349 Result<ResolverMultinetworkTest::DnsServerPair> ResolverMultinetworkTest::ScopedNetwork::addDns(
7350         ConnectivityType type) {
7351     const int index = mDnsServerPairs.size();
7352     const int prefixLen = (type == ConnectivityType::V4) ? 32 : 128;
7353 
7354     const std::function<std::string(unsigned)> makeIpString =
7355             std::bind((type == ConnectivityType::V4) ? &ScopedNetwork::makeIpv4AddrString
7356                                                      : &ScopedNetwork::makeIpv6AddrString,
7357                       this, std::placeholders::_1);
7358 
7359     std::string src1 = makeIpString(1);            // The address from which the resolver will send.
7360     std::string dst1 = makeIpString(
7361             index + 100 +
7362             (mNetId - TEST_NETID_BASE));           // The address to which the resolver will send.
7363     std::string src2 = dst1;                       // The address translated from src1.
7364     std::string dst2 = makeIpString(
7365             index + 200 + (mNetId - TEST_NETID_BASE));  // The address translated from dst2.
7366 
7367     if (!mTunForwarder->addForwardingRule({src1, dst1}, {src2, dst2}) ||
7368         !mTunForwarder->addForwardingRule({dst2, src2}, {dst1, src1})) {
7369         return Errorf("Failed to add the rules ({}, {}, {}, {})", src1, dst1, src2, dst2);
7370     }
7371 
7372     if (!mNetdSrv->interfaceAddAddress(mIfname, dst2, prefixLen).isOk()) {
7373         return Errorf("interfaceAddAddress({}, {}, {}) failed", mIfname, dst2, prefixLen);
7374     }
7375 
7376     return mDnsServerPairs.emplace_back(std::make_shared<test::DNSResponder>(mNetId, dst2), dst1);
7377 }
7378 
setDnsConfiguration() const7379 bool ResolverMultinetworkTest::ScopedNetwork::setDnsConfiguration() const {
7380     if (mDnsResolvSrv == nullptr) return false;
7381     ResolverParamsParcel parcel = DnsResponderClient::GetDefaultResolverParamsParcel();
7382     parcel.tlsServers.clear();
7383     parcel.netId = mNetId;
7384     parcel.servers.clear();
7385     parcel.interfaceNames.push_back(mIfname);
7386     for (const auto& pair : mDnsServerPairs) {
7387         parcel.servers.push_back(pair.dnsAddr);
7388     }
7389     return mDnsResolvSrv->setResolverConfiguration(parcel).isOk();
7390 }
7391 
clearDnsConfiguration() const7392 bool ResolverMultinetworkTest::ScopedNetwork::clearDnsConfiguration() const {
7393     if (mDnsResolvSrv == nullptr) return false;
7394     return mDnsResolvSrv->destroyNetworkCache(mNetId).isOk() &&
7395            mDnsResolvSrv->createNetworkCache(mNetId).isOk();
7396 }
7397 
7398 namespace {
7399 
7400 // Convenient wrapper for making getaddrinfo call like framework.
android_getaddrinfofornet_wrapper(const char * name,int netId)7401 Result<ScopedAddrinfo> android_getaddrinfofornet_wrapper(const char* name, int netId) {
7402     // Use the same parameter as libcore/ojluni/src/main/java/java/net/Inet6AddressImpl.java.
7403     static const addrinfo hints = {
7404             .ai_flags = AI_ADDRCONFIG,
7405             .ai_family = AF_UNSPEC,
7406             .ai_socktype = SOCK_STREAM,
7407     };
7408     addrinfo* result = nullptr;
7409     if (int r = android_getaddrinfofornet(name, nullptr, &hints, netId, MARK_UNSET, &result)) {
7410         return Error() << r;
7411     }
7412     return ScopedAddrinfo(result);
7413 }
7414 
expectDnsWorksForUid(const char * name,unsigned netId,uid_t uid,const std::vector<std::string> & expectedResult)7415 void expectDnsWorksForUid(const char* name, unsigned netId, uid_t uid,
7416                           const std::vector<std::string>& expectedResult) {
7417     ScopedChangeUID scopedChangeUID(uid);
7418     auto result = android_getaddrinfofornet_wrapper(name, netId);
7419     ASSERT_RESULT_OK(result);
7420     ScopedAddrinfo ai_result(std::move(result.value()));
7421     std::vector<std::string> result_strs = ToStrings(ai_result);
7422     EXPECT_THAT(result_strs, testing::UnorderedElementsAreArray(expectedResult));
7423 }
7424 
expectDnsFailedForUid(const char * name,unsigned netId,uid_t uid)7425 void expectDnsFailedForUid(const char* name, unsigned netId, uid_t uid) {
7426     ScopedChangeUID scopedChangeUID(uid);
7427     ASSERT_FALSE(android_getaddrinfofornet_wrapper(name, netId).ok());
7428 }
7429 
7430 }  // namespace
7431 
TEST_F(ResolverMultinetworkTest,GetAddrInfo_AI_ADDRCONFIG)7432 TEST_F(ResolverMultinetworkTest, GetAddrInfo_AI_ADDRCONFIG) {
7433     constexpr char host_name[] = "ohayou.example.com.";
7434 
7435     const std::array<ConnectivityType, 3> allTypes = {
7436             ConnectivityType::V4,
7437             ConnectivityType::V6,
7438             ConnectivityType::V4V6,
7439     };
7440     for (const auto& type : allTypes) {
7441         SCOPED_TRACE(fmt::format("ConnectivityType: {}", static_cast<int>(type)));
7442 
7443         // Create a network.
7444         ScopedPhysicalNetwork network = CreateScopedPhysicalNetwork(type);
7445         ASSERT_RESULT_OK(network.init());
7446 
7447         // Add a testing DNS server.
7448         const Result<DnsServerPair> dnsPair =
7449                 (type == ConnectivityType::V4) ? network.addIpv4Dns() : network.addIpv6Dns();
7450         ASSERT_RESULT_OK(dnsPair);
7451         StartDns(*dnsPair->dnsServer, {{host_name, ns_type::ns_t_a, "192.0.2.0"},
7452                                        {host_name, ns_type::ns_t_aaaa, "2001:db8:cafe:d00d::31"}});
7453 
7454         // Set up resolver and start forwarding.
7455         ASSERT_TRUE(network.setDnsConfiguration());
7456         ASSERT_TRUE(network.startTunForwarder());
7457 
7458         auto result = android_getaddrinfofornet_wrapper(host_name, network.netId());
7459         ASSERT_RESULT_OK(result);
7460         ScopedAddrinfo ai_result(std::move(result.value()));
7461         std::vector<std::string> result_strs = ToStrings(ai_result);
7462         std::vector<std::string> expectedResult;
7463         size_t expectedQueries = 0;
7464 
7465         if (type == ConnectivityType::V6 || type == ConnectivityType::V4V6) {
7466             expectedResult.emplace_back("2001:db8:cafe:d00d::31");
7467             expectedQueries++;
7468         }
7469         if (type == ConnectivityType::V4 || type == ConnectivityType::V4V6) {
7470             expectedResult.emplace_back("192.0.2.0");
7471             expectedQueries++;
7472         }
7473         EXPECT_THAT(result_strs, testing::UnorderedElementsAreArray(expectedResult));
7474         EXPECT_EQ(GetNumQueries(*dnsPair->dnsServer, host_name), expectedQueries);
7475     }
7476 }
7477 
TEST_F(ResolverMultinetworkTest,NetworkDestroyedDuringQueryInFlight)7478 TEST_F(ResolverMultinetworkTest, NetworkDestroyedDuringQueryInFlight) {
7479     constexpr char host_name[] = "ohayou.example.com.";
7480 
7481     // Create a network and add an ipv4 DNS server.
7482     auto network = std::make_unique<ScopedPhysicalNetwork>(getFreeNetId(), ConnectivityType::V4V6,
7483                                                            mDnsClient.netdService(),
7484                                                            mDnsClient.resolvService());
7485     ASSERT_RESULT_OK(network->init());
7486     const Result<DnsServerPair> dnsPair = network->addIpv4Dns();
7487     ASSERT_RESULT_OK(dnsPair);
7488 
7489     // Set the DNS server unresponsive.
7490     dnsPair->dnsServer->setResponseProbability(0.0);
7491     dnsPair->dnsServer->setErrorRcode(static_cast<ns_rcode>(-1));
7492     StartDns(*dnsPair->dnsServer, {});
7493 
7494     // Set up resolver and start forwarding.
7495     ASSERT_TRUE(network->setDnsConfiguration());
7496     ASSERT_TRUE(network->startTunForwarder());
7497 
7498     // Expect the things happening in order:
7499     // 1. The thread sends the query to the dns server which is unresponsive.
7500     // 2. The network is destroyed while the thread is waiting for the response from the dns server.
7501     // 3. After the dns server timeout, the thread retries but fails to connect.
7502     std::thread lookup([&]() {
7503         int fd = resNetworkQuery(network->netId(), host_name, ns_c_in, ns_t_a, 0);
7504         EXPECT_TRUE(fd != -1);
7505         expectAnswersNotValid(fd, -ETIMEDOUT);
7506     });
7507 
7508     // Tear down the network as soon as the dns server receives the query.
7509     const auto condition = [&]() { return GetNumQueries(*dnsPair->dnsServer, host_name) == 1U; };
7510     EXPECT_TRUE(PollForCondition(condition));
7511     network.reset();
7512 
7513     lookup.join();
7514 }
7515 
TEST_F(ResolverMultinetworkTest,OneCachePerNetwork)7516 TEST_F(ResolverMultinetworkTest, OneCachePerNetwork) {
7517     SKIP_IF_REMOTE_VERSION_LESS_THAN(mDnsClient.resolvService(), 4);
7518     constexpr char host_name[] = "ohayou.example.com.";
7519 
7520     ScopedPhysicalNetwork network1 = CreateScopedPhysicalNetwork(ConnectivityType::V4V6);
7521     ScopedPhysicalNetwork network2 = CreateScopedPhysicalNetwork(ConnectivityType::V4V6);
7522     ASSERT_RESULT_OK(network1.init());
7523     ASSERT_RESULT_OK(network2.init());
7524 
7525     const Result<DnsServerPair> dnsPair1 = network1.addIpv4Dns();
7526     const Result<DnsServerPair> dnsPair2 = network2.addIpv4Dns();
7527     ASSERT_RESULT_OK(dnsPair1);
7528     ASSERT_RESULT_OK(dnsPair2);
7529     StartDns(*dnsPair1->dnsServer, {{host_name, ns_type::ns_t_a, "192.0.2.0"}});
7530     StartDns(*dnsPair2->dnsServer, {{host_name, ns_type::ns_t_a, "192.0.2.1"}});
7531 
7532     // Set up resolver for network 1 and start forwarding.
7533     ASSERT_TRUE(network1.setDnsConfiguration());
7534     ASSERT_TRUE(network1.startTunForwarder());
7535 
7536     // Set up resolver for network 2 and start forwarding.
7537     ASSERT_TRUE(network2.setDnsConfiguration());
7538     ASSERT_TRUE(network2.startTunForwarder());
7539 
7540     // Send the same queries to both networks.
7541     int fd1 = resNetworkQuery(network1.netId(), host_name, ns_c_in, ns_t_a, 0);
7542     int fd2 = resNetworkQuery(network2.netId(), host_name, ns_c_in, ns_t_a, 0);
7543 
7544     expectAnswersValid(fd1, AF_INET, "192.0.2.0");
7545     expectAnswersValid(fd2, AF_INET, "192.0.2.1");
7546     EXPECT_EQ(GetNumQueries(*dnsPair1->dnsServer, host_name), 1U);
7547     EXPECT_EQ(GetNumQueries(*dnsPair2->dnsServer, host_name), 1U);
7548 
7549     // Flush the cache of network 1, and send the queries again.
7550     EXPECT_TRUE(mDnsClient.resolvService()->flushNetworkCache(network1.netId()).isOk());
7551     fd1 = resNetworkQuery(network1.netId(), host_name, ns_c_in, ns_t_a, 0);
7552     fd2 = resNetworkQuery(network2.netId(), host_name, ns_c_in, ns_t_a, 0);
7553 
7554     expectAnswersValid(fd1, AF_INET, "192.0.2.0");
7555     expectAnswersValid(fd2, AF_INET, "192.0.2.1");
7556     EXPECT_EQ(GetNumQueries(*dnsPair1->dnsServer, host_name), 2U);
7557     EXPECT_EQ(GetNumQueries(*dnsPair2->dnsServer, host_name), 1U);
7558 }
7559 
TEST_F(ResolverMultinetworkTest,DnsWithVpn)7560 TEST_F(ResolverMultinetworkTest, DnsWithVpn) {
7561     SKIP_IF_BPF_NOT_SUPPORTED;
7562     SKIP_IF_REMOTE_VERSION_LESS_THAN(mDnsClient.resolvService(), 4);
7563     constexpr char host_name[] = "ohayou.example.com.";
7564     constexpr char ipv4_addr[] = "192.0.2.0";
7565     constexpr char ipv6_addr[] = "2001:db8:cafe:d00d::31";
7566 
7567     const std::pair<ConnectivityType, std::vector<std::string>> testPairs[] = {
7568             {ConnectivityType::V4, {ipv4_addr}},
7569             {ConnectivityType::V6, {ipv6_addr}},
7570             {ConnectivityType::V4V6, {ipv6_addr, ipv4_addr}},
7571     };
7572     for (const auto& [type, result] : testPairs) {
7573         SCOPED_TRACE(fmt::format("ConnectivityType: {}", static_cast<int>(type)));
7574 
7575         // Create a network.
7576         ScopedPhysicalNetwork underlyingNetwork = CreateScopedPhysicalNetwork(type, "Underlying");
7577         ScopedVirtualNetwork bypassableVpnNetwork =
7578                 CreateScopedVirtualNetwork(type, false, "BypassableVpn");
7579         ScopedVirtualNetwork secureVpnNetwork = CreateScopedVirtualNetwork(type, true, "SecureVpn");
7580 
7581         ASSERT_RESULT_OK(underlyingNetwork.init());
7582         ASSERT_RESULT_OK(bypassableVpnNetwork.init());
7583         ASSERT_RESULT_OK(secureVpnNetwork.init());
7584         ASSERT_RESULT_OK(bypassableVpnNetwork.addUser(TEST_UID));
7585         ASSERT_RESULT_OK(secureVpnNetwork.addUser(TEST_UID2));
7586 
7587         // Set up resolver and start forwarding for networks.
7588         auto underlyingNwDnsSv =
7589                 setupDns(type, &underlyingNetwork, host_name, ipv4_addr, ipv6_addr);
7590         ASSERT_RESULT_OK(underlyingNwDnsSv);
7591         auto bypassableVpnDnsSv =
7592                 setupDns(type, &bypassableVpnNetwork, host_name, ipv4_addr, ipv6_addr);
7593         ASSERT_RESULT_OK(bypassableVpnDnsSv);
7594         auto secureVpnDnsSv = setupDns(type, &secureVpnNetwork, host_name, ipv4_addr, ipv6_addr);
7595         ASSERT_RESULT_OK(secureVpnDnsSv);
7596 
7597         setDefaultNetwork(underlyingNetwork.netId());
7598         const unsigned underlyingNetId = underlyingNetwork.netId();
7599         const unsigned bypassableVpnNetId = bypassableVpnNetwork.netId();
7600         const unsigned secureVpnNetId = secureVpnNetwork.netId();
7601         // We've called setNetworkForProcess in SetupOemNetwork, so reset to default first.
7602         ScopedSetNetworkForProcess scopedSetNetworkForProcess(NETID_UNSET);
7603 
7604         // Create a object to represent default network, do not init it.
7605         ScopedPhysicalNetwork defaultNetwork{NETID_UNSET, "Default"};
7606 
7607         // Test VPN with DNS server under 4 different network selection scenarios.
7608         // See the test config for the expectation.
7609         const struct TestConfig {
7610             ScopedNetwork* selectedNetwork;
7611             unsigned expectedDnsNetId;
7612             std::shared_ptr<test::DNSResponder> expectedDnsServer;
7613         } vpnWithDnsServerConfigs[]{
7614                 // clang-format off
7615                 // Queries use the bypassable VPN by default.
7616                 {&defaultNetwork,       bypassableVpnNetId, *bypassableVpnDnsSv},
7617                 // Choosing the underlying network works because the VPN is bypassable.
7618                 {&underlyingNetwork,    underlyingNetId,    *underlyingNwDnsSv},
7619                 // Selecting the VPN sends the query on the VPN.
7620                 {&bypassableVpnNetwork, bypassableVpnNetId, *bypassableVpnDnsSv},
7621                 // TEST_UID does not have access to the secure VPN.
7622                 {&secureVpnNetwork,     bypassableVpnNetId, *bypassableVpnDnsSv},
7623                 // clang-format on
7624         };
7625         for (const auto& config : vpnWithDnsServerConfigs) {
7626             SCOPED_TRACE(fmt::format("Bypassble VPN with DnsServer, selectedNetwork = {}",
7627                                      config.selectedNetwork->name()));
7628             expectDnsWorksForUid(host_name, config.selectedNetwork->netId(), TEST_UID, result);
7629             expectDnsQueryCountsFn(config.expectedDnsServer, host_name, result.size(),
7630                                    config.expectedDnsNetId);
7631         }
7632 
7633         std::vector<ScopedNetwork*> nwVec{&defaultNetwork, &underlyingNetwork,
7634                                           &bypassableVpnNetwork, &secureVpnNetwork};
7635         // Test the VPN without DNS server with the same combination as before.
7636         ASSERT_TRUE(bypassableVpnNetwork.clearDnsConfiguration());
7637         // Test bypassable VPN, TEST_UID
7638         for (const auto* selectedNetwork : nwVec) {
7639             SCOPED_TRACE(fmt::format("Bypassble VPN without DnsServer, selectedNetwork = {}",
7640                                      selectedNetwork->name()));
7641             expectDnsWorksForUid(host_name, selectedNetwork->netId(), TEST_UID, result);
7642             expectDnsQueryCountsFn(*underlyingNwDnsSv, host_name, result.size(), underlyingNetId);
7643         }
7644 
7645         // The same test scenario as before plus enableVpnIsolation for secure VPN, TEST_UID2.
7646         for (bool enableVpnIsolation : {false, true}) {
7647             SCOPED_TRACE(fmt::format("enableVpnIsolation = {}", enableVpnIsolation));
7648             if (enableVpnIsolation) {
7649                 EXPECT_RESULT_OK(secureVpnNetwork.enableVpnIsolation(TEST_UID2));
7650             }
7651 
7652             // Test secure VPN without DNS server.
7653             ASSERT_TRUE(secureVpnNetwork.clearDnsConfiguration());
7654             for (const auto* selectedNetwork : nwVec) {
7655                 SCOPED_TRACE(fmt::format("Secure VPN without DnsServer, selectedNetwork = {}",
7656                                          selectedNetwork->name()));
7657                 expectDnsWorksForUid(host_name, selectedNetwork->netId(), TEST_UID2, result);
7658                 expectDnsQueryCountsFn(*underlyingNwDnsSv, host_name, result.size(),
7659                                        underlyingNetId);
7660             }
7661 
7662             // Test secure VPN with DNS server.
7663             ASSERT_TRUE(secureVpnNetwork.setDnsConfiguration());
7664             for (const auto* selectedNetwork : nwVec) {
7665                 SCOPED_TRACE(fmt::format("Secure VPN with DnsServer, selectedNetwork = {}",
7666                                          selectedNetwork->name()));
7667                 expectDnsWorksForUid(host_name, selectedNetwork->netId(), TEST_UID2, result);
7668                 expectDnsQueryCountsFn(*secureVpnDnsSv, host_name, result.size(), secureVpnNetId);
7669             }
7670 
7671             if (enableVpnIsolation) {
7672                 EXPECT_RESULT_OK(secureVpnNetwork.disableVpnIsolation(TEST_UID2));
7673             }
7674         }
7675     }
7676 }
7677 
7678 // verify per-application default network selection on DNS.
TEST_F(ResolverMultinetworkTest,PerAppDefaultNetwork)7679 TEST_F(ResolverMultinetworkTest, PerAppDefaultNetwork) {
7680     // Netd supports uid ranges on physical network from v6.
7681     SKIP_IF_REMOTE_VERSION_LESS_THAN(mDnsClient.netdService(), 6);
7682 
7683     constexpr char host_name[] = "ohayou.example.com.";
7684     constexpr char ipv4_addr[] = "192.0.2.0";
7685     constexpr char ipv6_addr[] = "2001:db8:cafe:d00d::31";
7686 
7687     const std::pair<ConnectivityType, std::vector<std::string>> testPairs[] = {
7688             {ConnectivityType::V4, {ipv4_addr}},
7689             {ConnectivityType::V6, {ipv6_addr}},
7690             {ConnectivityType::V4V6, {ipv6_addr, ipv4_addr}},
7691     };
7692     for (const auto& [ipVersion, expectedDnsReply] : testPairs) {
7693         SCOPED_TRACE(fmt::format("ConnectivityType: {}", static_cast<int>(ipVersion)));
7694 
7695         // Create networks.
7696         ScopedPhysicalNetwork sysDefaultNetwork =
7697                 CreateScopedPhysicalNetwork(ipVersion, "SysDefault");
7698         ScopedPhysicalNetwork appDefaultNetwork =
7699                 CreateScopedPhysicalNetwork(ipVersion, "AppDefault");
7700         ScopedVirtualNetwork vpn = CreateScopedVirtualNetwork(ipVersion, false, "Vpn");
7701 
7702         ASSERT_RESULT_OK(sysDefaultNetwork.init());
7703         ASSERT_RESULT_OK(appDefaultNetwork.init());
7704         ASSERT_RESULT_OK(vpn.init());
7705 
7706         // Set up resolver and start forwarding for networks.
7707         auto sysDefaultNwDnsSv =
7708                 setupDns(ipVersion, &sysDefaultNetwork, host_name, ipv4_addr, ipv6_addr);
7709         ASSERT_RESULT_OK(sysDefaultNwDnsSv);
7710         auto appDefaultNwDnsSv =
7711                 setupDns(ipVersion, &appDefaultNetwork, host_name, ipv4_addr, ipv6_addr);
7712         ASSERT_RESULT_OK(appDefaultNwDnsSv);
7713         auto vpnDnsSv = setupDns(ipVersion, &vpn, host_name, ipv4_addr, ipv6_addr);
7714         ASSERT_RESULT_OK(vpnDnsSv);
7715 
7716         const unsigned systemDefaultNetId = sysDefaultNetwork.netId();
7717         const unsigned appDefaultNetId = appDefaultNetwork.netId();
7718         const unsigned vpnNetId = vpn.netId();
7719 
7720         setDefaultNetwork(systemDefaultNetId);
7721         EXPECT_TRUE(
7722                 mDnsClient.netdService()
7723                         ->networkSetPermissionForNetwork(appDefaultNetId, INetd::PERMISSION_SYSTEM)
7724                         .isOk());
7725 
7726         // We've called setNetworkForProcess in SetupOemNetwork, reset to default first.
7727         ScopedSetNetworkForProcess scopedSetNetworkForProcess(NETID_UNSET);
7728 
7729         // Test DNS query without selecting a network. --> use system default network.
7730         expectDnsWorksForUid(host_name, NETID_UNSET, TEST_UID, expectedDnsReply);
7731         expectDnsQueryCountsFn(*sysDefaultNwDnsSv, host_name, expectedDnsReply.size(),
7732                                systemDefaultNetId);
7733         // Add user to app default network. --> use app default network.
7734         ASSERT_RESULT_OK(appDefaultNetwork.addUser(TEST_UID));
7735         expectDnsWorksForUid(host_name, NETID_UNSET, TEST_UID, expectedDnsReply);
7736         expectDnsQueryCountsFn(*appDefaultNwDnsSv, host_name, expectedDnsReply.size(),
7737                                appDefaultNetId);
7738 
7739         // Test DNS query with a selected network.
7740         // App default network applies to uid, vpn does not applies to uid.
7741         const struct TestConfig {
7742             ScopedNetwork* selectedNetwork;
7743             unsigned expectedDnsNetId;
7744             std::shared_ptr<test::DNSResponder> expectedDnsServer;
7745         } vpnWithDnsServerConfigs[]{
7746                 // clang-format off
7747                 // App can select the system default network without any permission.
7748                 {&sysDefaultNetwork, systemDefaultNetId, *sysDefaultNwDnsSv},
7749                 // App can select the restricted network, since its uid was assigned to the network.
7750                 {&appDefaultNetwork, appDefaultNetId, *appDefaultNwDnsSv},
7751                 // App does not have access to the VPN. --> fallback to app default network.
7752                 {&vpn, appDefaultNetId, *appDefaultNwDnsSv},
7753                 // clang-format on
7754         };
7755         for (const auto& config : vpnWithDnsServerConfigs) {
7756             SCOPED_TRACE(fmt::format("Dns over app default network, selectedNetwork = {}",
7757                                      config.selectedNetwork->name()));
7758             expectDnsWorksForUid(host_name, config.selectedNetwork->netId(), TEST_UID,
7759                                  expectedDnsReply);
7760             expectDnsQueryCountsFn(config.expectedDnsServer, host_name, expectedDnsReply.size(),
7761                                    config.expectedDnsNetId);
7762         }
7763 
7764         // App default network applies to uid, vpn applies to uid. --> use vpn.
7765         ASSERT_RESULT_OK(vpn.addUser(TEST_UID));
7766         expectDnsWorksForUid(host_name, vpn.netId(), TEST_UID, expectedDnsReply);
7767         expectDnsQueryCountsFn(*vpnDnsSv, host_name, expectedDnsReply.size(), vpnNetId);
7768 
7769         // vpn without server. --> fallback to app default network.
7770         ASSERT_TRUE(vpn.clearDnsConfiguration());
7771         expectDnsWorksForUid(host_name, vpn.netId(), TEST_UID, expectedDnsReply);
7772         expectDnsQueryCountsFn(*appDefaultNwDnsSv, host_name, expectedDnsReply.size(),
7773                                appDefaultNetId);
7774     }
7775 }
7776 
7777 // Do not send AAAA query when IPv6 address is link-local with a default route.
TEST_F(ResolverMultinetworkTest,IPv6LinkLocalWithDefaultRoute)7778 TEST_F(ResolverMultinetworkTest, IPv6LinkLocalWithDefaultRoute) {
7779     constexpr char host_name[] = "ohayou.example.com.";
7780     ScopedPhysicalNetwork network = CreateScopedPhysicalNetwork(ConnectivityType::V4);
7781     ASSERT_RESULT_OK(network.init());
7782 
7783     // Add IPv6 default route
7784     ASSERT_TRUE(mDnsClient.netdService()
7785                         ->networkAddRoute(network.netId(), network.ifname(), "::/0", "")
7786                         .isOk());
7787 
7788     const Result<DnsServerPair> dnsPair = network.addIpv4Dns();
7789     ASSERT_RESULT_OK(dnsPair);
7790     StartDns(*dnsPair->dnsServer, {{host_name, ns_type::ns_t_a, "192.0.2.0"},
7791                                    {host_name, ns_type::ns_t_aaaa, "2001:db8:cafe:d00d::31"}});
7792 
7793     ASSERT_TRUE(network.setDnsConfiguration());
7794     ASSERT_TRUE(network.startTunForwarder());
7795 
7796     auto result = android_getaddrinfofornet_wrapper(host_name, network.netId());
7797     ASSERT_RESULT_OK(result);
7798     ScopedAddrinfo ai_result(std::move(result.value()));
7799     EXPECT_EQ(ToString(ai_result), "192.0.2.0");
7800     EXPECT_EQ(GetNumQueriesForType(*dnsPair->dnsServer, ns_type::ns_t_a, host_name), 1U);
7801     EXPECT_EQ(GetNumQueriesForType(*dnsPair->dnsServer, ns_type::ns_t_aaaa, host_name), 0U);
7802 
7803     EXPECT_TRUE(mDnsClient.resolvService()->flushNetworkCache(network.netId()).isOk());
7804     dnsPair->dnsServer->clearQueries();
7805 
7806     // Add an IPv6 global address. Resolver starts issuing AAAA queries as well as A queries.
7807     const std::string v6Addr = network.makeIpv6AddrString(1);
7808     EXPECT_TRUE(
7809             mDnsClient.netdService()->interfaceAddAddress(network.ifname(), v6Addr, 128).isOk());
7810     // Ensuring that address is applied. This is required for mainline test (b/249225311).
7811     usleep(1000 * 1000);
7812 
7813     result = android_getaddrinfofornet_wrapper(host_name, network.netId());
7814     ASSERT_RESULT_OK(result);
7815     ScopedAddrinfo ai_results(std::move(result.value()));
7816     std::vector<std::string> result_strs = ToStrings(ai_results);
7817     EXPECT_THAT(result_strs,
7818                 testing::UnorderedElementsAreArray({"192.0.2.0", "2001:db8:cafe:d00d::31"}));
7819     EXPECT_EQ(GetNumQueriesForType(*dnsPair->dnsServer, ns_type::ns_t_a, host_name), 1U);
7820     EXPECT_EQ(GetNumQueriesForType(*dnsPair->dnsServer, ns_type::ns_t_aaaa, host_name), 1U);
7821 }
7822 
7823 // v6 mdns is expected to be sent when the IPv6 address is a link-local with a default route.
TEST_F(ResolverMultinetworkTest,MdnsIPv6LinkLocalWithDefaultRoute)7824 TEST_F(ResolverMultinetworkTest, MdnsIPv6LinkLocalWithDefaultRoute) {
7825     // Kernel 4.4 does not provide an IPv6 link-local address when an interface is added to a
7826     // network. Skip it because v6 link-local address is a prerequisite for this test.
7827     SKIP_IF_KERNEL_VERSION_LOWER_THAN(4, 9, 0);
7828 
7829     constexpr char v6addr[] = "::127.0.0.3";
7830     constexpr char v4addr[] = "127.0.0.3";
7831     constexpr char host_name[] = "hello.local.";
7832     ScopedPhysicalNetwork network = CreateScopedPhysicalNetwork(ConnectivityType::V4);
7833     ASSERT_RESULT_OK(network.init());
7834 
7835     // Add IPv6 default route
7836     ASSERT_TRUE(mDnsClient.netdService()
7837                         ->networkAddRoute(network.netId(), network.ifname(), "::/0", "")
7838                         .isOk());
7839     // Ensuring that routing is applied. This is required for mainline test (b/247693272).
7840     usleep(1000 * 1000);
7841 
7842     const Result<DnsServerPair> dnsPair = network.addIpv4Dns();
7843     ASSERT_RESULT_OK(dnsPair);
7844     StartDns(*dnsPair->dnsServer, {});
7845 
7846     ASSERT_TRUE(network.setDnsConfiguration());
7847     ASSERT_TRUE(network.startTunForwarder());
7848 
7849     test::DNSResponder mdnsv4("127.0.0.3", test::kDefaultMdnsListenService);
7850     test::DNSResponder mdnsv6("::1", test::kDefaultMdnsListenService);
7851     mdnsv4.setNetwork(network.netId());
7852     mdnsv6.setNetwork(network.netId());
7853     StartDns(mdnsv4, {{host_name, ns_type::ns_t_a, v4addr}});
7854     StartDns(mdnsv6, {{host_name, ns_type::ns_t_aaaa, v6addr}});
7855 
7856     auto result = android_getaddrinfofornet_wrapper("hello.local", network.netId());
7857     ASSERT_RESULT_OK(result);
7858     ScopedAddrinfo ai_result(std::move(result.value()));
7859     EXPECT_THAT(ToStrings(ai_result), testing::UnorderedElementsAreArray({v4addr, v6addr}));
7860 
7861     // make sure queries were sent & received via mdns.
7862     EXPECT_EQ(GetNumQueries(mdnsv4, host_name), 1U);
7863     EXPECT_EQ(GetNumQueries(mdnsv6, host_name), 1U);
7864     EXPECT_EQ(GetNumQueriesForType(*dnsPair->dnsServer, ns_type::ns_t_a, host_name), 0U);
7865     EXPECT_EQ(GetNumQueriesForType(*dnsPair->dnsServer, ns_type::ns_t_aaaa, host_name), 0U);
7866 }
7867 
TEST_F(ResolverTest,NegativeValueInExperimentFlag)7868 TEST_F(ResolverTest, NegativeValueInExperimentFlag) {
7869     // Test setting up different retry count and BASE_TIMEOUT_MSEC in DNS server.
7870     const struct TestConfig {
7871         int retryCount;
7872         int baseTimeoutMsec;
7873         int expectedRetryCount;
7874         int expectedBaseTimeoutMsec;
7875     } TestConfigs[]{{2, 1000, 2, 1000}, {0, 0, RES_DFLRETRY, RES_TIMEOUT}};
7876 
7877     for (const auto& config : TestConfigs) {
7878         SCOPED_TRACE(fmt::format("Setting up retryCount = {}, baseTimeoutMsec = {}",
7879                                  config.retryCount, config.baseTimeoutMsec));
7880         // Initiate negative values in experiment flags.
7881         ScopedSystemProperties sp1(kRetryCountFlag, "-2");
7882         ScopedSystemProperties sp2(kRetransIntervalFlag, "-3000");
7883         resetNetwork();
7884 
7885         ResolverParamsParcel setupParams = DnsResponderClient::GetDefaultResolverParamsParcel();
7886         setupParams.retryCount = config.retryCount;
7887         setupParams.baseTimeoutMsec = config.baseTimeoutMsec;
7888         ASSERT_TRUE(mDnsClient.SetResolversFromParcel(setupParams));
7889 
7890         const auto resolvInfo = mDnsClient.getResolverInfo();
7891         ASSERT_RESULT_OK(resolvInfo);
7892         EXPECT_EQ(config.expectedRetryCount, resolvInfo.value().params.retry_count);
7893         EXPECT_EQ(config.expectedBaseTimeoutMsec, resolvInfo.value().params.base_timeout_msec);
7894     }
7895 }
7896 
7897 // Verify that DNS queries can be made for hostnames that exist in etc/hosts when the default
7898 // network is not set and the application does not specify a network. (See
7899 // NetworkController::isUidAllowed for implementation details.)
TEST_F(ResolverTest,NetworkUnspecified_localhost)7900 TEST_F(ResolverTest, NetworkUnspecified_localhost) {
7901     ScopedDefaultNetwork scopedDefaultNetwork(mDnsClient.netdService(), NETID_UNSET);
7902     ScopedSetNetworkForProcess scopedSetNetworkForProcess(NETID_UNSET);
7903 
7904     ScopedAddrinfo result = safe_getaddrinfo(kLocalHost, nullptr, nullptr);
7905     EXPECT_TRUE(result != nullptr);
7906     EXPECT_EQ(kLocalHostAddr, ToString(result));
7907 
7908     result = safe_getaddrinfo(kIp6LocalHost, nullptr, nullptr);
7909     EXPECT_TRUE(result != nullptr);
7910     EXPECT_EQ(kIp6LocalHostAddr, ToString(result));
7911 }
7912 
7913 // Verify uid-based network permission on DNS, which is controlled by INetd::setNetworkAllowlist().
7914 //
7915 // Scenario:
7916 // 1. There are three neworks at the same time:
7917 //  - system default network
7918 //  - enterprise network #1
7919 //  - enterprise network #2
7920 //
7921 // 2. Simulate ConnectivityService calling INetd::setNetworkAllowlist so that
7922 //  - TEST_UID can select only enterprise network #1 and #2. Can not select system default network.
7923 //  - TEST_UID2 is unrestricted on all networks.
TEST_F(ResolverMultinetworkTest,UidAllowedNetworks)7924 TEST_F(ResolverMultinetworkTest, UidAllowedNetworks) {
7925     // Netd supports it from v13.
7926     SKIP_IF_REMOTE_VERSION_LESS_THAN(mDnsClient.netdService(), 13);
7927 
7928     constexpr char host_name[] = "ohayou.example.com.";
7929     constexpr char ipv4_addr[] = "192.0.2.0";
7930     constexpr char ipv6_addr[] = "2001:db8:cafe:d00d::31";
7931 
7932     const std::pair<ConnectivityType, std::vector<std::string>> testPairs[] = {
7933             {ConnectivityType::V4, {ipv4_addr}},
7934             {ConnectivityType::V6, {ipv6_addr}},
7935             {ConnectivityType::V4V6, {ipv6_addr, ipv4_addr}},
7936     };
7937     for (const auto& [ipVersion, expectedDnsReply] : testPairs) {
7938         SCOPED_TRACE(fmt::format("ConnectivityType: {}", static_cast<int>(ipVersion)));
7939 
7940         // Create networks.
7941         ScopedPhysicalNetwork sysDefaultNetwork =
7942                 CreateScopedPhysicalNetwork(ipVersion, "SysDefault");
7943         ScopedPhysicalNetwork enterpriseNetwork_1 =
7944                 CreateScopedPhysicalNetwork(ipVersion, "enterprise_1");
7945         ScopedPhysicalNetwork enterpriseNetwork_2 =
7946                 CreateScopedPhysicalNetwork(ipVersion, "enterprise_2");
7947         ASSERT_RESULT_OK(sysDefaultNetwork.init());
7948         ASSERT_RESULT_OK(enterpriseNetwork_1.init());
7949         ASSERT_RESULT_OK(enterpriseNetwork_2.init());
7950 
7951         // Set up resolver and start forwarding for networks.
7952         auto sysDefaultNwDnsSv =
7953                 setupDns(ipVersion, &sysDefaultNetwork, host_name, ipv4_addr, ipv6_addr);
7954         ASSERT_RESULT_OK(sysDefaultNwDnsSv);
7955         auto enterpriseNw1DnsSv =
7956                 setupDns(ipVersion, &enterpriseNetwork_1, host_name, ipv4_addr, ipv6_addr);
7957         ASSERT_RESULT_OK(enterpriseNw1DnsSv);
7958         auto enterpriseNw2DnsSv =
7959                 setupDns(ipVersion, &enterpriseNetwork_2, host_name, ipv4_addr, ipv6_addr);
7960         ASSERT_RESULT_OK(enterpriseNw2DnsSv);
7961 
7962         const unsigned systemDefaultNetId = sysDefaultNetwork.netId();
7963         const unsigned enterprise1NetId = enterpriseNetwork_1.netId();
7964         const unsigned enterprise2NetId = enterpriseNetwork_2.netId();
7965 
7966         setDefaultNetwork(systemDefaultNetId);
7967 
7968         // We've called setNetworkForProcess in SetupOemNetwork, reset to default first.
7969         ScopedSetNetworkForProcess scopedSetNetworkForProcess(NETID_UNSET);
7970 
7971         // Add profile app default network for UID. DNS should be sent on it.
7972         // Note: subPriority 20 = PREFERENCE_ORDER_PROFILE, which is defined
7973         // in ConnectivityService.java. The value here doesn't really matter.
7974         ASSERT_RESULT_OK(enterpriseNetwork_1.addUserFromParcel(TEST_UID, /*subPriority*/ 20));
7975         expectDnsWorksForUid(host_name, NETID_UNSET, TEST_UID, expectedDnsReply);
7976         expectDnsQueryCountsFn(*enterpriseNw1DnsSv, host_name, expectedDnsReply.size(),
7977                                enterprise1NetId);
7978 
7979         // Set allowed networks for UIDs. To simplify test, assumes overall UID range is
7980         // {0, 1, 2, ..., TEST_UID2, TEST_UID}.
7981         // TEST_UID can't select the system default network. 0 - TEST_UID2 are allowed.
7982         NativeUidRangeConfig nwDefaultUserConfig = makeNativeUidRangeConfig(
7983                 systemDefaultNetId, {makeUidRangeParcel(0, TEST_UID2)}, /*unused*/ 0);
7984         // All UIDs can select the enterprise network #1. 0 - TEST_UID are allowed.
7985         NativeUidRangeConfig nw1UserConfig = makeNativeUidRangeConfig(
7986                 enterprise1NetId, {makeUidRangeParcel(0, TEST_UID)}, /*unused*/ 0);
7987         // All UIDs can select the enterprise network #2. 0 - TEST_UID are allowed.
7988         NativeUidRangeConfig nw2UserConfig = makeNativeUidRangeConfig(
7989                 enterprise2NetId, {makeUidRangeParcel(0, TEST_UID)}, /*unused*/ 0);
7990         EXPECT_TRUE(
7991                 mDnsClient.netdService()
7992                         ->setNetworkAllowlist({nwDefaultUserConfig, nw1UserConfig, nw2UserConfig})
7993                         .isOk());
7994 
7995         // Verify that DNS is behaving as the setting.
7996         struct TestConfig {
7997             int uid;
7998             const ScopedNetwork& selectedNetwork;
7999             bool expectedSuccess;
8000         } configs[]{
8001                 // clang-format off
8002                 {TEST_UID, sysDefaultNetwork, false},
8003                 {TEST_UID, enterpriseNetwork_1, true},
8004                 {TEST_UID, enterpriseNetwork_2, true},
8005                 {TEST_UID2, sysDefaultNetwork, true},
8006                 {TEST_UID2, enterpriseNetwork_1, true},
8007                 {TEST_UID2, enterpriseNetwork_2, true},
8008                 // clang-format on
8009         };
8010         for (const auto& cfg : configs) {
8011             SCOPED_TRACE(fmt::format("Dns over UID {}, selectedNetwork {}", cfg.uid,
8012                                      cfg.selectedNetwork.name()));
8013             if (cfg.expectedSuccess) {
8014                 expectDnsWorksForUid(host_name, cfg.selectedNetwork.netId(), cfg.uid,
8015                                      expectedDnsReply);
8016             } else {
8017                 expectDnsFailedForUid(host_name, cfg.selectedNetwork.netId(), cfg.uid);
8018             }
8019         }
8020 
8021         // Clear network restrictions.
8022         EXPECT_TRUE(mDnsClient.netdService()->setNetworkAllowlist({}).isOk());
8023         // TEST_UID and TEST_UID2 can both select all networks.
8024         for (const auto& cfg : configs) {
8025             SCOPED_TRACE(fmt::format("Dns over UID {}, selectedNetwork {}", cfg.uid,
8026                                      cfg.selectedNetwork.name()));
8027             expectDnsWorksForUid(host_name, cfg.selectedNetwork.netId(), cfg.uid, expectedDnsReply);
8028         }
8029     }
8030 }
8031