• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*	$NetBSD: getaddrinfo.c,v 1.82 2006/03/25 12:09:40 rpaulo Exp $	*/
2 /*	$KAME: getaddrinfo.c,v 1.29 2000/08/31 17:26:57 itojun Exp $	*/
3 
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #define LOG_TAG "resolv"
34 
35 #include "getaddrinfo.h"
36 
37 #include <arpa/inet.h>
38 #include <arpa/nameser.h>
39 #include <assert.h>
40 #include <ctype.h>
41 #include <fcntl.h>
42 #include <net/if.h>
43 #include <netdb.h>
44 #include <netinet/in.h>
45 #include <stdbool.h>
46 #include <stddef.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <sys/param.h>
50 #include <sys/socket.h>
51 #include <sys/stat.h>
52 #include <sys/un.h>
53 #include <unistd.h>
54 
55 #include <chrono>
56 #include <future>
57 
58 #include <android-base/logging.h>
59 #include <android-base/parseint.h>
60 
61 #include "Experiments.h"
62 #include "netd_resolv/resolv.h"
63 #include "res_comp.h"
64 #include "res_debug.h"
65 #include "resolv_cache.h"
66 #include "resolv_private.h"
67 
68 #define ANY 0
69 
70 using android::net::Experiments;
71 using android::net::NetworkDnsEventReported;
72 
73 const char in_addrany[] = {0, 0, 0, 0};
74 const char in_loopback[] = {127, 0, 0, 1};
75 const char in6_addrany[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
76 const char in6_loopback[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
77 
78 const struct afd {
79     int a_af;
80     int a_addrlen;
81     int a_socklen;
82     int a_off;
83     const char* a_addrany;
84     const char* a_loopback;
85     int a_scoped;
86 } afdl[] = {
87         {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6),
88          offsetof(struct sockaddr_in6, sin6_addr), in6_addrany, in6_loopback, 1},
89         {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in),
90          offsetof(struct sockaddr_in, sin_addr), in_addrany, in_loopback, 0},
91         {0, 0, 0, 0, NULL, NULL, 0},
92 };
93 
94 struct Explore {
95     int e_af;
96     int e_socktype;
97     int e_protocol;
98     int e_wild;
99 #define WILD_AF(ex) ((ex).e_wild & 0x01)
100 #define WILD_SOCKTYPE(ex) ((ex).e_wild & 0x02)
101 #define WILD_PROTOCOL(ex) ((ex).e_wild & 0x04)
102 };
103 
104 const Explore explore_options[] = {
105         {PF_INET6, SOCK_DGRAM, IPPROTO_UDP, 0x07},
106         {PF_INET6, SOCK_STREAM, IPPROTO_TCP, 0x07},
107         {PF_INET6, SOCK_RAW, ANY, 0x05},
108         {PF_INET, SOCK_DGRAM, IPPROTO_UDP, 0x07},
109         {PF_INET, SOCK_STREAM, IPPROTO_TCP, 0x07},
110         {PF_INET, SOCK_RAW, ANY, 0x05},
111         {PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, 0x07},
112         {PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, 0x07},
113         {PF_UNSPEC, SOCK_RAW, ANY, 0x05},
114 };
115 
116 #define PTON_MAX 16
117 
118 struct res_target {
119     const char* name;                                                  // domain name
120     int qclass, qtype;                                                 // class and type of query
121     std::vector<uint8_t> answer = std::vector<uint8_t>(MAXPACKET, 0);  // buffer to put answer
122     int n = 0;                                                         // result length
123     // ResState this query should be run within
124     ResState* res_state;
125 };
126 
127 static int explore_fqdn(const struct addrinfo*, const char*, const char*, struct addrinfo**,
128                         const struct android_net_context*, std::optional<int> app_socket,
129                         NetworkDnsEventReported* event);
130 static int explore_null(const struct addrinfo*, const char*, struct addrinfo**);
131 static int explore_numeric(const struct addrinfo*, const char*, const char*, struct addrinfo**,
132                            const char*);
133 static int explore_numeric_scope(const struct addrinfo*, const char*, const char*,
134                                  struct addrinfo**);
135 static int get_canonname(const struct addrinfo*, struct addrinfo*, const char*);
136 static struct addrinfo* get_ai(const struct addrinfo*, const struct afd*, const char*);
137 static int get_portmatch(const struct addrinfo*, const char*);
138 static int get_port(const struct addrinfo*, const char*, int);
139 static const struct afd* find_afd(int);
140 static int ip6_str2scopeid(const char*, struct sockaddr_in6*, uint32_t*);
141 
142 static struct addrinfo* getanswer(const std::vector<uint8_t>&, int, const char*, int,
143                                   const struct addrinfo*, int* herrno);
144 static int dns_getaddrinfo(const char* name, const addrinfo* pai,
145                            const android_net_context* netcontext, std::optional<int> app_socket,
146                            addrinfo** rv, NetworkDnsEventReported* event);
147 static void _sethtent(FILE**);
148 static void _endhtent(FILE**);
149 static struct addrinfo* _gethtent(FILE**, const char*, const struct addrinfo*);
150 static struct addrinfo* getCustomHosts(const size_t netid, const char*, const struct addrinfo*);
151 static bool files_getaddrinfo(const size_t netid, const char* name, const addrinfo* pai,
152                               addrinfo** res);
153 static int _find_src_addr(const struct sockaddr*, struct sockaddr*, unsigned, uid_t,
154                           bool allow_v6_linklocal);
155 
156 static int res_searchN(const char* name, std::span<res_target> queries,
157                        std::span<std::string> search_domains, bool is_mdns,
158                        android::net::NetworkDnsEventReported* event, int* herrno);
159 static int res_querydomainN(const char* name, const char* domain, std::span<res_target> queries,
160                             android::net::NetworkDnsEventReported* event, int* herrno);
161 
162 const char* const ai_errlist[] = {
163         "Success",
164         "Address family for hostname not supported",    /* EAI_ADDRFAMILY */
165         "Temporary failure in name resolution",         /* EAI_AGAIN      */
166         "Invalid value for ai_flags",                   /* EAI_BADFLAGS   */
167         "Non-recoverable failure in name resolution",   /* EAI_FAIL       */
168         "ai_family not supported",                      /* EAI_FAMILY     */
169         "Memory allocation failure",                    /* EAI_MEMORY     */
170         "No address associated with hostname",          /* EAI_NODATA     */
171         "hostname nor servname provided, or not known", /* EAI_NONAME     */
172         "servname not supported for ai_socktype",       /* EAI_SERVICE    */
173         "ai_socktype not supported",                    /* EAI_SOCKTYPE   */
174         "System error returned in errno",               /* EAI_SYSTEM     */
175         "Invalid value for hints",                      /* EAI_BADHINTS	  */
176         "Resolved protocol is unknown",                 /* EAI_PROTOCOL   */
177         "Argument buffer overflow",                     /* EAI_OVERFLOW   */
178         "Unknown error",                                /* EAI_MAX        */
179 };
180 
181 /* XXX macros that make external reference is BAD. */
182 
183 #define GET_AI(ai, afd, addr)                                \
184     do {                                                     \
185         /* external reference: pai, error, and label free */ \
186         (ai) = get_ai(pai, (afd), (addr));                   \
187         if ((ai) == NULL) {                                  \
188             error = EAI_MEMORY;                              \
189             goto free;                                       \
190         }                                                    \
191     } while (0)
192 
193 #define GET_PORT(ai, serv)                             \
194     do {                                               \
195         /* external reference: error and label free */ \
196         error = get_port((ai), (serv), 0);             \
197         if (error != 0) goto free;                     \
198     } while (0)
199 
200 #define MATCH_FAMILY(x, y, w) \
201     ((x) == (y) || ((w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
202 #define MATCH(x, y, w) ((x) == (y) || ((w) && ((x) == ANY || (y) == ANY)))
203 
gai_strerror(int ecode)204 const char* gai_strerror(int ecode) {
205     if (ecode < 0 || ecode > EAI_MAX) ecode = EAI_MAX;
206     return ai_errlist[ecode];
207 }
208 
freeaddrinfo(struct addrinfo * ai)209 void freeaddrinfo(struct addrinfo* ai) {
210     while (ai) {
211         struct addrinfo* next = ai->ai_next;
212         if (ai->ai_canonname) free(ai->ai_canonname);
213         // Also frees ai->ai_addr which points to extra space beyond addrinfo
214         free(ai);
215         ai = next;
216     }
217 }
218 
have_global_ipv6_connectivity(unsigned mark,uid_t uid)219 static bool have_global_ipv6_connectivity(unsigned mark, uid_t uid) {
220     static const struct sockaddr_in6 sin6_test = {
221             .sin6_family = AF_INET6,
222             .sin6_addr.s6_addr = {// 2000::
223                                   0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}};
224     sockaddr_union addr = {.sin6 = sin6_test};
225     sockaddr_storage sa;
226     return _find_src_addr(&addr.sa, (struct sockaddr*)&sa, mark, uid,
227                           /*allow_v6_linklocal=*/false) == 1;
228 }
229 
have_local_ipv6_connectivity(unsigned mark,uid_t uid,int netid)230 static bool have_local_ipv6_connectivity(unsigned mark, uid_t uid, int netid) {
231     // IPv6 link-local addresses require a scope identifier to be correctly defined. This forces us
232     // to loop through all interfaces included within |netid|.
233     std::vector<std::string> interface_names = resolv_get_interface_names(netid);
234     for (const auto& interface_name : interface_names) {
235         const struct sockaddr_in6 sin6_test = {
236                 .sin6_family = AF_INET6,
237                 .sin6_addr.s6_addr =
238                         {// fe80::
239                          0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
240                 .sin6_scope_id = if_nametoindex(interface_name.c_str())};
241         sockaddr_union addr = {.sin6 = sin6_test};
242         sockaddr_storage sa;
243         if (_find_src_addr(&addr.sa, (struct sockaddr*)&sa, mark, uid,
244                            /*allow_v6_linklocal=*/true) == 1) {
245             return true;
246         }
247     }
248     return false;
249 }
250 
have_ipv4_connectivity(unsigned mark,uid_t uid)251 static bool have_ipv4_connectivity(unsigned mark, uid_t uid) {
252     static const struct sockaddr_in sin_test = {
253             .sin_family = AF_INET,
254             .sin_addr.s_addr = __constant_htonl(0x08080808L)  // 8.8.8.8
255     };
256     sockaddr_union addr = {.sin = sin_test};
257     sockaddr_storage sa;
258     return _find_src_addr(&addr.sa, (struct sockaddr*)&sa, mark, uid,
259                           /*(don't care) allow_v6_linklocal=*/false) == 1;
260 }
261 
262 // Internal version of getaddrinfo(), but limited to AI_NUMERICHOST.
263 // NOTE: also called by resolv_set_nameservers().
getaddrinfo_numeric(const char * hostname,const char * servname,addrinfo hints,addrinfo ** result)264 int getaddrinfo_numeric(const char* hostname, const char* servname, addrinfo hints,
265                         addrinfo** result) {
266     hints.ai_flags = AI_NUMERICHOST;
267     const android_net_context netcontext = {
268             .app_netid = NETID_UNSET,
269             .app_mark = MARK_UNSET,
270             .dns_netid = NETID_UNSET,
271             .dns_mark = MARK_UNSET,
272             .uid = NET_CONTEXT_INVALID_UID,
273             .pid = NET_CONTEXT_INVALID_PID,
274     };
275     NetworkDnsEventReported event;
276     return android_getaddrinfofornetcontext(hostname, servname, &hints, &netcontext, result,
277                                             &event);
278 }
279 
280 namespace {
281 
validateHints(const addrinfo * _Nonnull hints)282 int validateHints(const addrinfo* _Nonnull hints) {
283     if (!hints) return EAI_BADHINTS;
284 
285     // error check for hints
286     if (hints->ai_addrlen || hints->ai_canonname || hints->ai_addr || hints->ai_next) {
287         return EAI_BADHINTS;
288     }
289     if (hints->ai_flags & ~AI_MASK) {
290         return EAI_BADFLAGS;
291     }
292     if (!(hints->ai_family == PF_UNSPEC || hints->ai_family == PF_INET ||
293           hints->ai_family == PF_INET6)) {
294         return EAI_FAMILY;
295     }
296 
297     // Socket types which are not in explore_options.
298     switch (hints->ai_socktype) {
299         case SOCK_RAW:
300         case SOCK_DGRAM:
301         case SOCK_STREAM:
302         case ANY:
303             break;
304         default:
305             return EAI_SOCKTYPE;
306     }
307 
308     if (hints->ai_socktype == ANY || hints->ai_protocol == ANY) return 0;
309 
310     // if both socktype/protocol are specified, check if they are meaningful combination.
311     for (const Explore& ex : explore_options) {
312         if (hints->ai_family != ex.e_af) continue;
313         if (ex.e_socktype == ANY) continue;
314         if (ex.e_protocol == ANY) continue;
315         if (hints->ai_socktype == ex.e_socktype && hints->ai_protocol != ex.e_protocol) {
316             return EAI_BADHINTS;
317         }
318     }
319 
320     return 0;
321 }
322 
fill_sin6_scope_id_if_needed(const res_target & query,addrinfo * addr_info)323 void fill_sin6_scope_id_if_needed(const res_target& query, addrinfo* addr_info) {
324     if (addr_info->ai_family != AF_INET6) {
325         return;
326     }
327 
328     sockaddr_in6* sin6 = reinterpret_cast<sockaddr_in6*>(addr_info->ai_addr);
329     if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
330         sin6->sin6_scope_id = query.res_state->target_interface_index_for_mdns;
331     }
332 }
333 
334 }  // namespace
335 
android_getaddrinfofornetcontext(const char * hostname,const char * servname,const addrinfo * hints,const android_net_context * netcontext,addrinfo ** res,NetworkDnsEventReported * event)336 int android_getaddrinfofornetcontext(const char* hostname, const char* servname,
337                                      const addrinfo* hints, const android_net_context* netcontext,
338                                      addrinfo** res, NetworkDnsEventReported* event) {
339     // hostname is allowed to be nullptr
340     // servname is allowed to be nullptr
341     // hints is allowed to be nullptr
342     assert(res != nullptr);
343     assert(netcontext != nullptr);
344     assert(event != nullptr);
345 
346     addrinfo sentinel = {};
347     addrinfo* cur = &sentinel;
348     int error = 0;
349 
350     do {
351         if (hostname == nullptr && servname == nullptr) {
352             error = EAI_NONAME;
353             break;
354         }
355 
356         if (hints && (error = validateHints(hints))) break;
357         addrinfo ai = hints ? *hints : addrinfo{};
358 
359         // Check for special cases:
360         // (1) numeric servname is disallowed if socktype/protocol are left unspecified.
361         // (2) servname is disallowed for raw and other inet{,6} sockets.
362         if (MATCH_FAMILY(ai.ai_family, PF_INET, 1) || MATCH_FAMILY(ai.ai_family, PF_INET6, 1)) {
363             addrinfo tmp = ai;
364             if (tmp.ai_family == PF_UNSPEC) {
365                 tmp.ai_family = PF_INET6;
366             }
367             error = get_portmatch(&tmp, servname);
368             if (error) break;
369         }
370 
371         // NULL hostname, or numeric hostname
372         for (const Explore& ex : explore_options) {
373             /* PF_UNSPEC entries are prepared for DNS queries only */
374             if (ex.e_af == PF_UNSPEC) continue;
375 
376             if (!MATCH_FAMILY(ai.ai_family, ex.e_af, WILD_AF(ex))) continue;
377             if (!MATCH(ai.ai_socktype, ex.e_socktype, WILD_SOCKTYPE(ex))) continue;
378             if (!MATCH(ai.ai_protocol, ex.e_protocol, WILD_PROTOCOL(ex))) continue;
379 
380             addrinfo tmp = ai;
381             if (tmp.ai_family == PF_UNSPEC) tmp.ai_family = ex.e_af;
382             if (tmp.ai_socktype == ANY && ex.e_socktype != ANY) tmp.ai_socktype = ex.e_socktype;
383             if (tmp.ai_protocol == ANY && ex.e_protocol != ANY) tmp.ai_protocol = ex.e_protocol;
384 
385             LOG(DEBUG) << __func__ << ": explore_numeric: ai_family=" << tmp.ai_family
386                        << " ai_socktype=" << tmp.ai_socktype << " ai_protocol=" << tmp.ai_protocol;
387             if (hostname == nullptr)
388                 error = explore_null(&tmp, servname, &cur->ai_next);
389             else
390                 error = explore_numeric_scope(&tmp, hostname, servname, &cur->ai_next);
391 
392             if (error) break;
393 
394             while (cur->ai_next) cur = cur->ai_next;
395         }
396         if (error) break;
397 
398         // If numeric representation of AF1 can be interpreted as FQDN
399         // representation of AF2, we need to think again about the code below.
400         if (sentinel.ai_next) break;
401 
402         if (hostname == nullptr) {
403             error = EAI_NODATA;
404             break;
405         }
406         if (ai.ai_flags & AI_NUMERICHOST) {
407             error = EAI_NONAME;
408             break;
409         }
410 
411         return resolv_getaddrinfo(hostname, servname, hints, netcontext, APP_SOCKET_NONE, res,
412                                   event);
413     } while (0);
414 
415     if (error) {
416         freeaddrinfo(sentinel.ai_next);
417         *res = nullptr;
418     } else {
419         *res = sentinel.ai_next;
420     }
421     return error;
422 }
423 
resolv_getaddrinfo(const char * _Nonnull hostname,const char * servname,const addrinfo * hints,const android_net_context * _Nonnull netcontext,std::optional<int> app_socket,addrinfo ** _Nonnull res,NetworkDnsEventReported * _Nonnull event)424 int resolv_getaddrinfo(const char* _Nonnull hostname, const char* servname, const addrinfo* hints,
425                        const android_net_context* _Nonnull netcontext,
426                        std::optional<int> app_socket, addrinfo** _Nonnull res,
427                        NetworkDnsEventReported* _Nonnull event) {
428     if (hostname == nullptr && servname == nullptr) return EAI_NONAME;
429     if (hostname == nullptr) return EAI_NODATA;
430 
431     // servname is allowed to be nullptr
432     // hints is allowed to be nullptr
433     assert(res != nullptr);
434     assert(netcontext != nullptr);
435     assert(event != nullptr);
436 
437     int error = EAI_FAIL;
438     if (hints && (error = validateHints(hints))) {
439         *res = nullptr;
440         return error;
441     }
442 
443     addrinfo ai = hints ? *hints : addrinfo{};
444     addrinfo sentinel = {};
445     addrinfo* cur = &sentinel;
446     // hostname as alphanumeric name.
447     // We would like to prefer AF_INET6 over AF_INET, so we'll make a outer loop by AFs.
448     for (const Explore& ex : explore_options) {
449         // Require exact match for family field
450         if (ai.ai_family != ex.e_af) continue;
451 
452         if (!MATCH(ai.ai_socktype, ex.e_socktype, WILD_SOCKTYPE(ex))) continue;
453 
454         if (!MATCH(ai.ai_protocol, ex.e_protocol, WILD_PROTOCOL(ex))) continue;
455 
456         addrinfo tmp = ai;
457         if (tmp.ai_socktype == ANY && ex.e_socktype != ANY) tmp.ai_socktype = ex.e_socktype;
458         if (tmp.ai_protocol == ANY && ex.e_protocol != ANY) tmp.ai_protocol = ex.e_protocol;
459 
460         LOG(DEBUG) << __func__ << ": explore_fqdn(): ai_family=" << tmp.ai_family
461                    << " ai_socktype=" << tmp.ai_socktype << " ai_protocol=" << tmp.ai_protocol;
462         error = explore_fqdn(&tmp, hostname, servname, &cur->ai_next, netcontext, app_socket,
463                              event);
464 
465         while (cur->ai_next) cur = cur->ai_next;
466     }
467 
468     // Propagate the last error from explore_fqdn(), but only when *all* attempts failed.
469     if ((*res = sentinel.ai_next)) return 0;
470 
471     // TODO: consider removing freeaddrinfo.
472     freeaddrinfo(sentinel.ai_next);
473     *res = nullptr;
474     return (error == 0) ? EAI_FAIL : error;
475 }
476 
477 // FQDN hostname, DNS lookup
explore_fqdn(const addrinfo * pai,const char * hostname,const char * servname,addrinfo ** res,const android_net_context * netcontext,std::optional<int> app_socket,NetworkDnsEventReported * event)478 static int explore_fqdn(const addrinfo* pai, const char* hostname, const char* servname,
479                         addrinfo** res, const android_net_context* netcontext,
480                         std::optional<int> app_socket, NetworkDnsEventReported* event) {
481     assert(pai != nullptr);
482     // hostname may be nullptr
483     // servname may be nullptr
484     assert(res != nullptr);
485 
486     addrinfo* result = nullptr;
487     int error = 0;
488 
489     // If the servname does not match socktype/protocol, return error code.
490     if ((error = get_portmatch(pai, servname))) return error;
491 
492     if (!files_getaddrinfo(netcontext->dns_netid, hostname, pai, &result)) {
493         error = dns_getaddrinfo(hostname, pai, netcontext, app_socket, &result, event);
494     }
495     if (error) {
496         freeaddrinfo(result);
497         return error;
498     }
499 
500     for (addrinfo* cur = result; cur; cur = cur->ai_next) {
501         // canonname should be filled already
502         if ((error = get_port(cur, servname, 0))) {
503             freeaddrinfo(result);
504             return error;
505         }
506     }
507     *res = result;
508     return 0;
509 }
510 
511 /*
512  * hostname == NULL.
513  * passive socket -> anyaddr (0.0.0.0 or ::)
514  * non-passive socket -> localhost (127.0.0.1 or ::1)
515  */
explore_null(const struct addrinfo * pai,const char * servname,struct addrinfo ** res)516 static int explore_null(const struct addrinfo* pai, const char* servname, struct addrinfo** res) {
517     int s;
518     const struct afd* afd;
519     struct addrinfo* cur;
520     struct addrinfo sentinel;
521     int error;
522 
523     LOG(DEBUG) << __func__;
524 
525     assert(pai != NULL);
526     /* servname may be NULL */
527     assert(res != NULL);
528 
529     *res = NULL;
530     sentinel.ai_next = NULL;
531     cur = &sentinel;
532 
533     /*
534      * filter out AFs that are not supported by the kernel
535      * XXX errno?
536      */
537     s = socket(pai->ai_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
538     if (s < 0) {
539         if (errno != EMFILE) return 0;
540     } else
541         close(s);
542 
543     /*
544      * if the servname does not match socktype/protocol, ignore it.
545      */
546     if (get_portmatch(pai, servname) != 0) return 0;
547 
548     afd = find_afd(pai->ai_family);
549     if (afd == NULL) return 0;
550 
551     if (pai->ai_flags & AI_PASSIVE) {
552         GET_AI(cur->ai_next, afd, afd->a_addrany);
553         GET_PORT(cur->ai_next, servname);
554     } else {
555         GET_AI(cur->ai_next, afd, afd->a_loopback);
556         GET_PORT(cur->ai_next, servname);
557     }
558     cur = cur->ai_next;
559 
560     *res = sentinel.ai_next;
561     return 0;
562 
563 free:
564     freeaddrinfo(sentinel.ai_next);
565     return error;
566 }
567 
568 /*
569  * numeric hostname
570  */
explore_numeric(const struct addrinfo * pai,const char * hostname,const char * servname,struct addrinfo ** res,const char * canonname)571 static int explore_numeric(const struct addrinfo* pai, const char* hostname, const char* servname,
572                            struct addrinfo** res, const char* canonname) {
573     const struct afd* afd;
574     struct addrinfo* cur;
575     struct addrinfo sentinel;
576     int error;
577     char pton[PTON_MAX];
578 
579     assert(pai != NULL);
580     /* hostname may be NULL */
581     /* servname may be NULL */
582     assert(res != NULL);
583 
584     *res = NULL;
585     sentinel.ai_next = NULL;
586     cur = &sentinel;
587 
588     /*
589      * if the servname does not match socktype/protocol, ignore it.
590      */
591     if (get_portmatch(pai, servname) != 0) return 0;
592 
593     afd = find_afd(pai->ai_family);
594     if (afd == NULL) return 0;
595 
596     if (inet_pton(afd->a_af, hostname, pton) == 1) {
597         if (pai->ai_family == afd->a_af || pai->ai_family == PF_UNSPEC /*?*/) {
598             GET_AI(cur->ai_next, afd, pton);
599             GET_PORT(cur->ai_next, servname);
600             if ((pai->ai_flags & AI_CANONNAME)) {
601                 /*
602                  * Set the numeric address itself as
603                  * the canonical name, based on a
604                  * clarification in rfc2553bis-03.
605                  */
606                 error = get_canonname(pai, cur->ai_next, canonname);
607                 if (error != 0) {
608                     freeaddrinfo(sentinel.ai_next);
609                     return error;
610                 }
611             }
612             while (cur->ai_next) cur = cur->ai_next;
613         } else
614             return EAI_FAMILY;
615     }
616 
617     *res = sentinel.ai_next;
618     return 0;
619 
620 free:
621     freeaddrinfo(sentinel.ai_next);
622     return error;
623 }
624 
625 /*
626  * numeric hostname with scope
627  */
explore_numeric_scope(const struct addrinfo * pai,const char * hostname,const char * servname,struct addrinfo ** res)628 static int explore_numeric_scope(const struct addrinfo* pai, const char* hostname,
629                                  const char* servname, struct addrinfo** res) {
630     const struct afd* afd;
631     struct addrinfo* cur;
632     int error;
633     const char *cp, *scope, *addr;
634     struct sockaddr_in6* sin6;
635 
636     LOG(DEBUG) << __func__;
637 
638     assert(pai != NULL);
639     /* hostname may be NULL */
640     /* servname may be NULL */
641     assert(res != NULL);
642 
643     /*
644      * if the servname does not match socktype/protocol, ignore it.
645      */
646     if (get_portmatch(pai, servname) != 0) return 0;
647 
648     afd = find_afd(pai->ai_family);
649     if (afd == NULL) return 0;
650 
651     if (!afd->a_scoped) return explore_numeric(pai, hostname, servname, res, hostname);
652 
653     cp = strchr(hostname, SCOPE_DELIMITER);
654     if (cp == NULL) return explore_numeric(pai, hostname, servname, res, hostname);
655 
656     /*
657      * Handle special case of <scoped_address><delimiter><scope id>
658      */
659     char* hostname2 = strdup(hostname);
660     if (hostname2 == NULL) return EAI_MEMORY;
661     /* terminate at the delimiter */
662     hostname2[cp - hostname] = '\0';
663     addr = hostname2;
664     scope = cp + 1;
665 
666     error = explore_numeric(pai, addr, servname, res, hostname);
667     if (error == 0) {
668         uint32_t scopeid;
669 
670         for (cur = *res; cur; cur = cur->ai_next) {
671             if (cur->ai_family != AF_INET6) continue;
672             sin6 = (struct sockaddr_in6*) (void*) cur->ai_addr;
673             if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
674                 free(hostname2);
675                 return (EAI_NODATA); /* XXX: is return OK? */
676             }
677             sin6->sin6_scope_id = scopeid;
678         }
679     }
680 
681     free(hostname2);
682 
683     return error;
684 }
685 
get_canonname(const struct addrinfo * pai,struct addrinfo * ai,const char * str)686 static int get_canonname(const struct addrinfo* pai, struct addrinfo* ai, const char* str) {
687     assert(pai != NULL);
688     assert(ai != NULL);
689     assert(str != NULL);
690 
691     if ((pai->ai_flags & AI_CANONNAME) != 0) {
692         ai->ai_canonname = strdup(str);
693         if (ai->ai_canonname == NULL) return EAI_MEMORY;
694     }
695     return 0;
696 }
697 
get_ai(const struct addrinfo * pai,const struct afd * afd,const char * addr)698 static struct addrinfo* get_ai(const struct addrinfo* pai, const struct afd* afd,
699                                const char* addr) {
700     char* p;
701     struct addrinfo* ai;
702 
703     assert(pai != NULL);
704     assert(afd != NULL);
705     assert(addr != NULL);
706 
707     ai = (struct addrinfo*) calloc(1, sizeof(struct addrinfo) + sizeof(sockaddr_union));
708     if (ai == NULL) return NULL;
709 
710     memcpy(ai, pai, sizeof(struct addrinfo));
711     ai->ai_addr = (struct sockaddr*) (void*) (ai + 1);
712     ai->ai_addrlen = afd->a_socklen;
713     ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
714     p = (char*) (void*) (ai->ai_addr);
715     memcpy(p + afd->a_off, addr, (size_t) afd->a_addrlen);
716     return ai;
717 }
718 
get_portmatch(const struct addrinfo * ai,const char * servname)719 static int get_portmatch(const struct addrinfo* ai, const char* servname) {
720     assert(ai != NULL);
721     /* servname may be NULL */
722 
723     return get_port(ai, servname, 1);
724 }
725 
get_port(const struct addrinfo * ai,const char * servname,int matchonly)726 static int get_port(const struct addrinfo* ai, const char* servname, int matchonly) {
727     const char* proto;
728     struct servent* sp;
729     uint port;
730     int allownumeric;
731 
732     assert(ai != NULL);
733     /* servname may be NULL */
734 
735     if (servname == NULL) return 0;
736     switch (ai->ai_family) {
737         case AF_INET:
738         case AF_INET6:
739             break;
740         default:
741             return 0;
742     }
743 
744     switch (ai->ai_socktype) {
745         case SOCK_RAW:
746             return EAI_SERVICE;
747         case SOCK_DGRAM:
748         case SOCK_STREAM:
749         case ANY:
750             allownumeric = 1;
751             break;
752         default:
753             return EAI_SOCKTYPE;
754     }
755 
756     if (android::base::ParseUint(servname, &port)) {
757         if (!allownumeric) return EAI_SERVICE;
758         if (port > 65535) return EAI_SERVICE;
759         port = htons(port);
760     } else {
761         if (ai->ai_flags & AI_NUMERICSERV) return EAI_NONAME;
762 
763         switch (ai->ai_socktype) {
764             case SOCK_DGRAM:
765                 proto = "udp";
766                 break;
767             case SOCK_STREAM:
768                 proto = "tcp";
769                 break;
770             default:
771                 proto = NULL;
772                 break;
773         }
774 
775         if ((sp = getservbyname(servname, proto)) == NULL) return EAI_SERVICE;
776         port = sp->s_port;
777     }
778 
779     if (!matchonly) {
780         switch (ai->ai_family) {
781             case AF_INET:
782                 ((struct sockaddr_in*) (void*) ai->ai_addr)->sin_port = port;
783                 break;
784             case AF_INET6:
785                 ((struct sockaddr_in6*) (void*) ai->ai_addr)->sin6_port = port;
786                 break;
787         }
788     }
789 
790     return 0;
791 }
792 
find_afd(int af)793 static const struct afd* find_afd(int af) {
794     const struct afd* afd;
795 
796     if (af == PF_UNSPEC) return NULL;
797     for (afd = afdl; afd->a_af; afd++) {
798         if (afd->a_af == af) return afd;
799     }
800     return NULL;
801 }
802 
803 // Convert a string to a scope identifier.
ip6_str2scopeid(const char * scope,struct sockaddr_in6 * sin6,uint32_t * scopeid)804 static int ip6_str2scopeid(const char* scope, struct sockaddr_in6* sin6, uint32_t* scopeid) {
805     struct in6_addr* a6;
806 
807     assert(scope != NULL);
808     assert(sin6 != NULL);
809     assert(scopeid != NULL);
810 
811     a6 = &sin6->sin6_addr;
812 
813     /* empty scopeid portion is invalid */
814     if (*scope == '\0') return -1;
815 
816     if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
817         /*
818          * We currently assume a one-to-one mapping between links
819          * and interfaces, so we simply use interface indices for
820          * like-local scopes.
821          */
822         *scopeid = if_nametoindex(scope);
823         if (*scopeid != 0) return 0;
824     }
825 
826     /* try to convert to a numeric id as a last resort*/
827     if (!android::base::ParseUint(scope, scopeid)) return -1;
828 
829     return 0;
830 }
831 
832 /* code duplicate with gethnamaddr.c */
833 
834 #define BOUNDED_INCR(x)      \
835     do {                     \
836         BOUNDS_CHECK(cp, x); \
837         cp += (x);           \
838     } while (0)
839 
840 #define BOUNDS_CHECK(ptr, count)     \
841     do {                             \
842         if (eom - (ptr) < (count)) { \
843             *herrno = NO_RECOVERY;   \
844             return NULL;             \
845         }                            \
846     } while (0)
847 
getanswer(const std::vector<uint8_t> & answer,int anslen,const char * qname,int qtype,const struct addrinfo * pai,int * herrno)848 static struct addrinfo* getanswer(const std::vector<uint8_t>& answer, int anslen, const char* qname,
849                                   int qtype, const struct addrinfo* pai, int* herrno) {
850     struct addrinfo sentinel = {};
851     struct addrinfo *cur;
852     struct addrinfo ai;
853     const struct afd* afd;
854     char* canonname;
855     const HEADER* hp;
856     const uint8_t* cp;
857     int n;
858     const uint8_t* eom;
859     char *bp, *ep;
860     int type, ancount, qdcount;
861     int haveanswer, had_error;
862     char tbuf[MAXDNAME];
863     char hostbuf[8 * 1024];
864 
865     assert(qname != NULL);
866     assert(pai != NULL);
867 
868     cur = &sentinel;
869 
870     canonname = NULL;
871     eom = answer.data() + anslen;
872 
873     bool (*name_ok)(const char* dn);
874     switch (qtype) {
875         case T_A:
876         case T_AAAA:
877         case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
878             name_ok = res_hnok;
879             break;
880         default:
881             return NULL; /* XXX should be abort(); */
882     }
883     /*
884      * find first satisfactory answer
885      */
886     hp = reinterpret_cast<const HEADER*>(answer.data());
887     ancount = ntohs(hp->ancount);
888     qdcount = ntohs(hp->qdcount);
889     bp = hostbuf;
890     ep = hostbuf + sizeof hostbuf;
891     cp = answer.data();
892     BOUNDED_INCR(HFIXEDSZ);
893     if (qdcount != 1) {
894         *herrno = NO_RECOVERY;
895         return (NULL);
896     }
897     n = dn_expand(answer.data(), eom, cp, bp, ep - bp);
898     if ((n < 0) || !(*name_ok)(bp)) {
899         *herrno = NO_RECOVERY;
900         return (NULL);
901     }
902     BOUNDED_INCR(n + QFIXEDSZ);
903     if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
904         /* res_send() has already verified that the query name is the
905          * same as the one we sent; this just gets the expanded name
906          * (i.e., with the succeeding search-domain tacked on).
907          */
908         n = strlen(bp) + 1; /* for the \0 */
909         if (n >= MAXHOSTNAMELEN) {
910             *herrno = NO_RECOVERY;
911             return (NULL);
912         }
913         canonname = bp;
914         bp += n;
915         /* The qname can be abbreviated, but h_name is now absolute. */
916         qname = canonname;
917     }
918     haveanswer = 0;
919     had_error = 0;
920     while (ancount-- > 0 && cp < eom && !had_error) {
921         n = dn_expand(answer.data(), eom, cp, bp, ep - bp);
922         if ((n < 0) || !(*name_ok)(bp)) {
923             had_error++;
924             continue;
925         }
926         cp += n; /* name */
927         BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
928         type = ntohs(*reinterpret_cast<const uint16_t*>(cp));
929         cp += INT16SZ; /* type */
930         int cl = ntohs(*reinterpret_cast<const uint16_t*>(cp));
931         cp += INT16SZ + INT32SZ; /* class, TTL */
932         n = ntohs(*reinterpret_cast<const uint16_t*>(cp));
933         cp += INT16SZ; /* len */
934         BOUNDS_CHECK(cp, n);
935         if (cl != C_IN) {
936             /* XXX - debug? syslog? */
937             cp += n;
938             continue; /* XXX - had_error++ ? */
939         }
940         if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) && type == T_CNAME) {
941             n = dn_expand(answer.data(), eom, cp, tbuf, sizeof tbuf);
942             if ((n < 0) || !(*name_ok)(tbuf)) {
943                 had_error++;
944                 continue;
945             }
946             cp += n;
947             /* Get canonical name. */
948             n = strlen(tbuf) + 1; /* for the \0 */
949             if (n > ep - bp || n >= MAXHOSTNAMELEN) {
950                 had_error++;
951                 continue;
952             }
953             strlcpy(bp, tbuf, (size_t)(ep - bp));
954             canonname = bp;
955             bp += n;
956             continue;
957         }
958         if (qtype == T_ANY) {
959             if (!(type == T_A || type == T_AAAA)) {
960                 cp += n;
961                 continue;
962             }
963         } else if (type != qtype) {
964             if (type != T_KEY && type != T_SIG)
965                 LOG(DEBUG) << __func__ << ": asked for \"" << qname << " " << p_class(C_IN) << " "
966                            << p_type(qtype) << "\", got type \"" << p_type(type) << "\"";
967             cp += n;
968             continue; /* XXX - had_error++ ? */
969         }
970         switch (type) {
971             case T_A:
972             case T_AAAA:
973                 if (strcasecmp(canonname, bp) != 0) {
974                     LOG(DEBUG) << __func__ << ": asked for \"" << canonname << "\", got \"" << bp
975                                << "\"";
976                     cp += n;
977                     continue; /* XXX - had_error++ ? */
978                 }
979                 if (type == T_A && n != INADDRSZ) {
980                     cp += n;
981                     continue;
982                 }
983                 if (type == T_AAAA && n != IN6ADDRSZ) {
984                     cp += n;
985                     continue;
986                 }
987                 if (type == T_AAAA) {
988                     struct in6_addr in6;
989                     memcpy(&in6, cp, IN6ADDRSZ);
990                     if (IN6_IS_ADDR_V4MAPPED(&in6)) {
991                         cp += n;
992                         continue;
993                     }
994                 }
995                 if (!haveanswer) {
996                     int nn;
997 
998                     canonname = bp;
999                     nn = strlen(bp) + 1; /* for the \0 */
1000                     bp += nn;
1001                 }
1002 
1003                 /* don't overwrite pai */
1004                 ai = *pai;
1005                 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1006                 afd = find_afd(ai.ai_family);
1007                 if (afd == NULL) {
1008                     cp += n;
1009                     continue;
1010                 }
1011                 cur->ai_next = get_ai(&ai, afd, (const char*) cp);
1012                 if (cur->ai_next == NULL) had_error++;
1013                 while (cur && cur->ai_next) cur = cur->ai_next;
1014                 cp += n;
1015                 break;
1016             default:
1017                 abort();
1018         }
1019         if (!had_error) haveanswer++;
1020     }
1021     if (haveanswer) {
1022         if (!canonname)
1023             (void) get_canonname(pai, sentinel.ai_next, qname);
1024         else
1025             (void) get_canonname(pai, sentinel.ai_next, canonname);
1026         *herrno = NETDB_SUCCESS;
1027         return sentinel.ai_next;
1028     }
1029 
1030     *herrno = NO_RECOVERY;
1031     return NULL;
1032 }
1033 
1034 struct addrinfo_sort_elem {
1035     struct addrinfo* ai;
1036     int has_src_addr;
1037     sockaddr_union src_addr;
1038     int original_order;
1039 };
1040 
_get_scope(const struct sockaddr * addr)1041 static int _get_scope(const struct sockaddr* addr) {
1042     if (addr->sa_family == AF_INET6) {
1043         const struct sockaddr_in6* addr6 = (const struct sockaddr_in6*) addr;
1044         if (IN6_IS_ADDR_MULTICAST(&addr6->sin6_addr)) {
1045             return IPV6_ADDR_MC_SCOPE(&addr6->sin6_addr);
1046         } else if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr) ||
1047                    IN6_IS_ADDR_LINKLOCAL(&addr6->sin6_addr)) {
1048             /*
1049              * RFC 4291 section 2.5.3 says loopback is to be treated as having
1050              * link-local scope.
1051              */
1052             return IPV6_ADDR_SCOPE_LINKLOCAL;
1053         } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1054             return IPV6_ADDR_SCOPE_SITELOCAL;
1055         } else {
1056             return IPV6_ADDR_SCOPE_GLOBAL;
1057         }
1058     } else if (addr->sa_family == AF_INET) {
1059         const struct sockaddr_in* addr4 = (const struct sockaddr_in*) addr;
1060         unsigned long int na = ntohl(addr4->sin_addr.s_addr);
1061 
1062         if (IN_LOOPBACK(na) ||                 /* 127.0.0.0/8 */
1063             (na & 0xffff0000) == 0xa9fe0000) { /* 169.254.0.0/16 */
1064             return IPV6_ADDR_SCOPE_LINKLOCAL;
1065         } else {
1066             /*
1067              * RFC 6724 section 3.2. Other IPv4 addresses, including private addresses
1068              * and shared addresses (100.64.0.0/10), are assigned global scope.
1069              */
1070             return IPV6_ADDR_SCOPE_GLOBAL;
1071         }
1072     } else {
1073         /*
1074          * This should never happen.
1075          * Return a scope with low priority as a last resort.
1076          */
1077         return IPV6_ADDR_SCOPE_NODELOCAL;
1078     }
1079 }
1080 
1081 /* These macros are modelled after the ones in <netinet/in6.h>. */
1082 
1083 /* RFC 4380, section 2.6 */
1084 #define IN6_IS_ADDR_TEREDO(a) \
1085     ((*(const uint32_t*) (const void*) (&(a)->s6_addr[0]) == ntohl(0x20010000)))
1086 
1087 /* RFC 3056, section 2. */
1088 #define IN6_IS_ADDR_6TO4(a) (((a)->s6_addr[0] == 0x20) && ((a)->s6_addr[1] == 0x02))
1089 
1090 /* 6bone testing address area (3ffe::/16), deprecated in RFC 3701. */
1091 #define IN6_IS_ADDR_6BONE(a) (((a)->s6_addr[0] == 0x3f) && ((a)->s6_addr[1] == 0xfe))
1092 
1093 /*
1094  * Get the label for a given IPv4/IPv6 address.
1095  * RFC 6724, section 2.1.
1096  */
1097 
_get_label(const struct sockaddr * addr)1098 static int _get_label(const struct sockaddr* addr) {
1099     if (addr->sa_family == AF_INET) {
1100         return 4;
1101     } else if (addr->sa_family == AF_INET6) {
1102         const struct sockaddr_in6* addr6 = (const struct sockaddr_in6*) addr;
1103         if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1104             return 0;
1105         } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
1106             return 4;
1107         } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1108             return 2;
1109         } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1110             return 5;
1111         } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1112             return 13;
1113         } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr)) {
1114             return 3;
1115         } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1116             return 11;
1117         } else if (IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1118             return 12;
1119         } else {
1120             /* All other IPv6 addresses, including global unicast addresses. */
1121             return 1;
1122         }
1123     } else {
1124         /*
1125          * This should never happen.
1126          * Return a semi-random label as a last resort.
1127          */
1128         return 1;
1129     }
1130 }
1131 
1132 /*
1133  * Get the precedence for a given IPv4/IPv6 address.
1134  * RFC 6724, section 2.1.
1135  */
1136 
_get_precedence(const struct sockaddr * addr)1137 static int _get_precedence(const struct sockaddr* addr) {
1138     if (addr->sa_family == AF_INET) {
1139         return 35;
1140     } else if (addr->sa_family == AF_INET6) {
1141         const struct sockaddr_in6* addr6 = (const struct sockaddr_in6*) addr;
1142         if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1143             return 50;
1144         } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
1145             return 35;
1146         } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1147             return 30;
1148         } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1149             return 5;
1150         } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1151             return 3;
1152         } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr) ||
1153                    IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr) ||
1154                    IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1155             return 1;
1156         } else {
1157             /* All other IPv6 addresses, including global unicast addresses. */
1158             return 40;
1159         }
1160     } else {
1161         return 1;
1162     }
1163 }
1164 
1165 /*
1166  * Find number of matching initial bits between the two addresses a1 and a2.
1167  */
1168 
_common_prefix_len(const struct in6_addr * a1,const struct in6_addr * a2)1169 static int _common_prefix_len(const struct in6_addr* a1, const struct in6_addr* a2) {
1170     const char* p1 = (const char*) a1;
1171     const char* p2 = (const char*) a2;
1172     unsigned i;
1173 
1174     for (i = 0; i < sizeof(*a1); ++i) {
1175         int x, j;
1176 
1177         if (p1[i] == p2[i]) {
1178             continue;
1179         }
1180         x = p1[i] ^ p2[i];
1181         for (j = 0; j < CHAR_BIT; ++j) {
1182             if (x & (1 << (CHAR_BIT - 1))) {
1183                 return i * CHAR_BIT + j;
1184             }
1185             x <<= 1;
1186         }
1187     }
1188     return sizeof(*a1) * CHAR_BIT;
1189 }
1190 
1191 /*
1192  * Compare two source/destination address pairs.
1193  * RFC 6724, section 6.
1194  */
1195 
_rfc6724_compare(const void * ptr1,const void * ptr2)1196 static int _rfc6724_compare(const void* ptr1, const void* ptr2) {
1197     const struct addrinfo_sort_elem* a1 = (const struct addrinfo_sort_elem*) ptr1;
1198     const struct addrinfo_sort_elem* a2 = (const struct addrinfo_sort_elem*) ptr2;
1199     int scope_src1, scope_dst1, scope_match1;
1200     int scope_src2, scope_dst2, scope_match2;
1201     int label_src1, label_dst1, label_match1;
1202     int label_src2, label_dst2, label_match2;
1203     int precedence1, precedence2;
1204     int prefixlen1, prefixlen2;
1205 
1206     /* Rule 1: Avoid unusable destinations. */
1207     if (a1->has_src_addr != a2->has_src_addr) {
1208         return a2->has_src_addr - a1->has_src_addr;
1209     }
1210 
1211     /* Rule 2: Prefer matching scope. */
1212     scope_src1 = _get_scope(&a1->src_addr.sa);
1213     scope_dst1 = _get_scope(a1->ai->ai_addr);
1214     scope_match1 = (scope_src1 == scope_dst1);
1215 
1216     scope_src2 = _get_scope(&a2->src_addr.sa);
1217     scope_dst2 = _get_scope(a2->ai->ai_addr);
1218     scope_match2 = (scope_src2 == scope_dst2);
1219 
1220     if (scope_match1 != scope_match2) {
1221         return scope_match2 - scope_match1;
1222     }
1223 
1224     /*
1225      * Rule 3: Avoid deprecated addresses.
1226      * TODO(sesse): We don't currently have a good way of finding this.
1227      */
1228 
1229     /*
1230      * Rule 4: Prefer home addresses.
1231      * TODO(sesse): We don't currently have a good way of finding this.
1232      */
1233 
1234     /* Rule 5: Prefer matching label. */
1235     label_src1 = _get_label(&a1->src_addr.sa);
1236     label_dst1 = _get_label(a1->ai->ai_addr);
1237     label_match1 = (label_src1 == label_dst1);
1238 
1239     label_src2 = _get_label(&a2->src_addr.sa);
1240     label_dst2 = _get_label(a2->ai->ai_addr);
1241     label_match2 = (label_src2 == label_dst2);
1242 
1243     if (label_match1 != label_match2) {
1244         return label_match2 - label_match1;
1245     }
1246 
1247     /* Rule 6: Prefer higher precedence. */
1248     precedence1 = _get_precedence(a1->ai->ai_addr);
1249     precedence2 = _get_precedence(a2->ai->ai_addr);
1250     if (precedence1 != precedence2) {
1251         return precedence2 - precedence1;
1252     }
1253 
1254     /*
1255      * Rule 7: Prefer native transport.
1256      * TODO(sesse): We don't currently have a good way of finding this.
1257      */
1258 
1259     /* Rule 8: Prefer smaller scope. */
1260     if (scope_dst1 != scope_dst2) {
1261         return scope_dst1 - scope_dst2;
1262     }
1263 
1264     /*
1265      * Rule 9: Use longest matching prefix.
1266      * We implement this for IPv6 only, as the rules in RFC 6724 don't seem
1267      * to work very well directly applied to IPv4. (glibc uses information from
1268      * the routing table for a custom IPv4 implementation here.)
1269      */
1270     if (a1->has_src_addr && a1->ai->ai_addr->sa_family == AF_INET6 && a2->has_src_addr &&
1271         a2->ai->ai_addr->sa_family == AF_INET6) {
1272         const struct sockaddr_in6* a1_src = &a1->src_addr.sin6;
1273         const struct sockaddr_in6* a1_dst = (const struct sockaddr_in6*) a1->ai->ai_addr;
1274         const struct sockaddr_in6* a2_src = &a2->src_addr.sin6;
1275         const struct sockaddr_in6* a2_dst = (const struct sockaddr_in6*) a2->ai->ai_addr;
1276         prefixlen1 = _common_prefix_len(&a1_src->sin6_addr, &a1_dst->sin6_addr);
1277         prefixlen2 = _common_prefix_len(&a2_src->sin6_addr, &a2_dst->sin6_addr);
1278         if (prefixlen1 != prefixlen2) {
1279             return prefixlen2 - prefixlen1;
1280         }
1281     }
1282 
1283     /*
1284      * Rule 10: Leave the order unchanged.
1285      * We need this since qsort() is not necessarily stable.
1286      */
1287     return a1->original_order - a2->original_order;
1288 }
1289 
1290 /*
1291  * Find the source address that will be used if trying to connect to the given
1292  * address. src_addr must be assigned and large enough to hold a struct sockaddr_in6.
1293  * allow_v6_linklocal controls whether to accept link-local source addresses.
1294  *
1295  * Returns 1 if a source address was found, 0 if the address is unreachable,
1296  * and -1 if a fatal error occurred. If 0 or -1, the contents of src_addr are
1297  * undefined.
1298  */
1299 
_find_src_addr(const struct sockaddr * addr,struct sockaddr * src_addr,unsigned mark,uid_t uid,bool allow_v6_linklocal)1300 static int _find_src_addr(const struct sockaddr* addr, struct sockaddr* src_addr, unsigned mark,
1301                           uid_t uid, bool allow_v6_linklocal) {
1302     if (src_addr == nullptr) return -1;
1303 
1304     int ret;
1305     socklen_t len;
1306 
1307     switch (addr->sa_family) {
1308         case AF_INET:
1309             len = sizeof(struct sockaddr_in);
1310             break;
1311         case AF_INET6:
1312             len = sizeof(struct sockaddr_in6);
1313             break;
1314         default:
1315             /* No known usable source address for non-INET families. */
1316             return 0;
1317     }
1318 
1319     android::base::unique_fd sock(socket(addr->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP));
1320     if (sock.get() == -1) {
1321         if (errno == EAFNOSUPPORT) {
1322             return 0;
1323         } else {
1324             return -1;
1325         }
1326     }
1327     if (mark != MARK_UNSET && setsockopt(sock, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) < 0) {
1328         return 0;
1329     }
1330     if (uid > 0 && uid != NET_CONTEXT_INVALID_UID && fchown(sock, uid, (gid_t) -1) < 0) {
1331         return 0;
1332     }
1333     do {
1334         ret = connect(sock, addr, len);
1335     } while (ret == -1 && errno == EINTR);
1336 
1337     if (ret == -1) {
1338         return 0;
1339     }
1340 
1341     if (getsockname(sock, src_addr, &len) == -1) {
1342         return -1;
1343     }
1344 
1345     if (src_addr->sa_family == AF_INET6) {
1346         sockaddr_in6* sin6 = reinterpret_cast<sockaddr_in6*>(src_addr);
1347         if (!allow_v6_linklocal && IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
1348             // There is no point in sending an AAAA query because the device does not have a global
1349             // IP address. The only thing that can be affected is the hostname "localhost". Devices
1350             // with this setting will not be able to get the localhost v6 IP address ::1 via DNS
1351             // lookups, which is accessible by host local. But it is expected that a DNS server that
1352             // replies to "localhost" in AAAA should also reply in A. So it shouldn't cause issues.
1353             // Also, the current behavior will not be changed because hostname “localhost” only gets
1354             // 127.0.0.1 per etc/hosts configs.
1355             return 0;
1356         }
1357     }
1358 
1359     return 1;
1360 }
1361 
1362 /*
1363  * Sort the linked list starting at sentinel->ai_next in RFC6724 order.
1364  * Will leave the list unchanged if an error occurs.
1365  */
1366 
resolv_rfc6724_sort(struct addrinfo * list_sentinel,unsigned mark,uid_t uid)1367 void resolv_rfc6724_sort(struct addrinfo* list_sentinel, unsigned mark, uid_t uid) {
1368     if (list_sentinel == nullptr) return;
1369 
1370     struct addrinfo* cur;
1371     int nelem = 0, i;
1372     struct addrinfo_sort_elem* elems;
1373 
1374     cur = list_sentinel->ai_next;
1375     while (cur) {
1376         ++nelem;
1377         cur = cur->ai_next;
1378     }
1379 
1380     elems = (struct addrinfo_sort_elem*) calloc(nelem, sizeof(struct addrinfo_sort_elem));
1381     if (elems == NULL) {
1382         goto error;
1383     }
1384 
1385     /*
1386      * Convert the linked list to an array that also contains the candidate
1387      * source address for each destination address.
1388      */
1389     for (i = 0, cur = list_sentinel->ai_next; i < nelem; ++i, cur = cur->ai_next) {
1390         int has_src_addr;
1391         assert(cur != NULL);
1392         elems[i].ai = cur;
1393         elems[i].original_order = i;
1394 
1395         has_src_addr = _find_src_addr(cur->ai_addr, &elems[i].src_addr.sa, mark, uid,
1396                                       /*allow_v6_linklocal=*/true);
1397         if (has_src_addr == -1) {
1398             goto error;
1399         }
1400         elems[i].has_src_addr = has_src_addr;
1401     }
1402 
1403     /* Sort the addresses, and rearrange the linked list so it matches the sorted order. */
1404     qsort((void*) elems, nelem, sizeof(struct addrinfo_sort_elem), _rfc6724_compare);
1405 
1406     list_sentinel->ai_next = elems[0].ai;
1407     for (i = 0; i < nelem - 1; ++i) {
1408         elems[i].ai->ai_next = elems[i + 1].ai;
1409     }
1410     elems[nelem - 1].ai->ai_next = NULL;
1411 
1412 error:
1413     free(elems);
1414 }
1415 
dns_getaddrinfo(const char * name,const addrinfo * pai,const android_net_context * netcontext,std::optional<int> app_socket,addrinfo ** rv,NetworkDnsEventReported * event)1416 static int dns_getaddrinfo(const char* name, const addrinfo* pai,
1417                            const android_net_context* netcontext, std::optional<int> app_socket,
1418                            addrinfo** rv, NetworkDnsEventReported* event) {
1419     std::vector<res_target> queries;
1420     ResState res(netcontext, app_socket, event);
1421 
1422     setMdnsFlag(name, res.netid, &(res.flags));
1423     bool is_mdns = isMdnsResolution(res.flags);
1424 
1425     bool query_ipv6 = false;
1426     bool query_ipv4 = false;
1427 
1428     if (pai->ai_family == AF_UNSPEC) {
1429         query_ipv6 = true;
1430         query_ipv4 = true;
1431         if (pai->ai_flags & AI_ADDRCONFIG) {
1432             // Strictly speaking, AI_ADDRCONFIG should not look at whether connectivity is
1433             // available, but whether addresses of the specified family are "configured on the local
1434             // system". However, bionic doesn't currently support getifaddrs, so checking for
1435             // connectivity is the next best thing.
1436             query_ipv6 = have_global_ipv6_connectivity(netcontext->app_mark, netcontext->uid) ||
1437                          (is_mdns && have_local_ipv6_connectivity(netcontext->app_mark,
1438                                                                   netcontext->uid, res.netid));
1439             query_ipv4 = have_ipv4_connectivity(netcontext->app_mark, netcontext->uid);
1440         }
1441     } else if (pai->ai_family == AF_INET) {
1442         query_ipv4 = true;
1443     } else if (pai->ai_family == AF_INET6) {
1444         query_ipv6 = true;
1445     } else {
1446         return EAI_FAMILY;
1447     }
1448 
1449     resolv_populate_res_for_net(&res);
1450 
1451     std::vector<ResState> res_states;
1452     if (is_mdns) {
1453         // resolv_get_interface_names is also called within have_local_ipv6_connectivity. This is
1454         // racy and the two could return different values. Having said that, the race condition is
1455         // benign for the following reasons:
1456         // 1. The first call is to figure out whether to send out an AAAA query.
1457         // 2. The second call is to figure out which interfaces to the queries to.
1458         // With the above in mind, if these value don't match only the following can happen:
1459         // 1. The second call returns interfaces that didn't exist before. In this scenario, we will
1460         //    send the query onto this additional interface. This is a good thing.
1461         // 2. The second call returns an interface that didn't exist before. In this scenario, we
1462         //    will not send the query onto this interface anymore. This is a good thing.
1463         // One could argue that whether we're sending out an AAAA query or not is also affected by
1464         // these network topology changes. But that is a race condition that cannot be avoided, as
1465         // it could also happen while this code is returning results to the caller.
1466         std::vector<std::string> interface_names = resolv_get_interface_names(res.netid);
1467         for (const auto& interface_name : interface_names) {
1468             res_states.emplace_back(res.clone(event)).target_interface_index_for_mdns =
1469                     if_nametoindex(interface_name.c_str());
1470         }
1471     } else {
1472         res_states.emplace_back(res.clone(event));
1473     }
1474 
1475     for (auto& res_state : res_states) {
1476         if (query_ipv6) {
1477             res_target ipv6_query;
1478             ipv6_query.name = name;
1479             ipv6_query.qclass = C_IN;
1480             ipv6_query.qtype = T_AAAA;
1481             ipv6_query.res_state = &res_state;
1482             queries.push_back(ipv6_query);
1483         }
1484         if (query_ipv4) {
1485             res_target ipv4_query;
1486             ipv4_query.name = name;
1487             ipv4_query.qclass = C_IN;
1488             ipv4_query.qtype = T_A;
1489             ipv4_query.res_state = &res_state;
1490             queries.push_back(ipv4_query);
1491         }
1492     }
1493     if (queries.empty()) {
1494         return EAI_NODATA;
1495     }
1496 
1497     int he;
1498     // TODO: Refactor search_domains and event out of ResState (they really should not be there).
1499     if (res_searchN(name, queries, res.search_domains, is_mdns, res.event, &he) < 0) {
1500         // Return h_errno (he) to catch more detailed errors rather than EAI_NODATA.
1501         // Note that res_searchN() doesn't set the pair NETDB_INTERNAL and errno.
1502         // See also herrnoToAiErrno().
1503         return herrnoToAiErrno(he);
1504     }
1505 
1506     addrinfo sentinel = {};
1507     addrinfo* cur = &sentinel;
1508     for (const auto& query : queries) {
1509         addrinfo* ai = getanswer(query.answer, query.n, query.name, query.qtype, pai, &he);
1510         if (ai) {
1511             cur->ai_next = ai;
1512             while (cur && cur->ai_next) {
1513                 cur = cur->ai_next;
1514                 fill_sin6_scope_id_if_needed(query, cur);
1515             }
1516         }
1517     }
1518 
1519     if (sentinel.ai_next == NULL) {
1520         // Note that getanswer() doesn't set the pair NETDB_INTERNAL and errno.
1521         // See also herrnoToAiErrno().
1522         return herrnoToAiErrno(he);
1523     }
1524 
1525     resolv_rfc6724_sort(&sentinel, netcontext->app_mark, netcontext->uid);
1526 
1527     *rv = sentinel.ai_next;
1528     return 0;
1529 }
1530 
_sethtent(FILE ** hostf)1531 static void _sethtent(FILE** hostf) {
1532     if (!*hostf)
1533         *hostf = fopen(_PATH_HOSTS, "re");
1534     else
1535         rewind(*hostf);
1536 }
1537 
_endhtent(FILE ** hostf)1538 static void _endhtent(FILE** hostf) {
1539     if (*hostf) {
1540         (void) fclose(*hostf);
1541         *hostf = NULL;
1542     }
1543 }
1544 
_gethtent(FILE ** hostf,const char * name,const struct addrinfo * pai)1545 static struct addrinfo* _gethtent(FILE** hostf, const char* name, const struct addrinfo* pai) {
1546     char* p;
1547     char *cp, *tname, *cname;
1548     struct addrinfo *res0, *res;
1549     int error;
1550     const char* addr;
1551     char hostbuf[8 * 1024];
1552 
1553     assert(name != NULL);
1554     assert(pai != NULL);
1555 
1556     if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "re"))) return (NULL);
1557 again:
1558     if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf))) return (NULL);
1559     if (*p == '#') goto again;
1560     if (!(cp = strpbrk(p, "#\n"))) goto again;
1561     *cp = '\0';
1562     if (!(cp = strpbrk(p, " \t"))) goto again;
1563     *cp++ = '\0';
1564     addr = p;
1565     /* if this is not something we're looking for, skip it. */
1566     cname = NULL;
1567     while (cp && *cp) {
1568         if (*cp == ' ' || *cp == '\t') {
1569             cp++;
1570             continue;
1571         }
1572         if (!cname) cname = cp;
1573         tname = cp;
1574         if ((cp = strpbrk(cp, " \t")) != NULL) *cp++ = '\0';
1575         if (strcasecmp(name, tname) == 0) goto found;
1576     }
1577     goto again;
1578 
1579 found:
1580     error = getaddrinfo_numeric(addr, nullptr, *pai, &res0);
1581     if (error) goto again;
1582     for (res = res0; res; res = res->ai_next) {
1583         /* cover it up */
1584         res->ai_flags = pai->ai_flags;
1585 
1586         if (pai->ai_flags & AI_CANONNAME) {
1587             if (get_canonname(pai, res, cname) != 0) {
1588                 freeaddrinfo(res0);
1589                 goto again;
1590             }
1591         }
1592     }
1593     return res0;
1594 }
1595 
getCustomHosts(const size_t netid,const char * _Nonnull name,const struct addrinfo * _Nonnull pai)1596 static struct addrinfo* getCustomHosts(const size_t netid, const char* _Nonnull name,
1597                                        const struct addrinfo* _Nonnull pai) {
1598     struct addrinfo sentinel = {};
1599     struct addrinfo *res0, *res;
1600     res = &sentinel;
1601     std::vector<std::string> hosts = getCustomizedTableByName(netid, name);
1602     for (const std::string& host : hosts) {
1603         int error = getaddrinfo_numeric(host.c_str(), nullptr, *pai, &res0);
1604         if (!error && res0 != nullptr) {
1605             res->ai_next = res0;
1606             res = res0;
1607             res0 = nullptr;
1608         }
1609     }
1610     return sentinel.ai_next;
1611 }
1612 
files_getaddrinfo(const size_t netid,const char * name,const addrinfo * pai,addrinfo ** res)1613 static bool files_getaddrinfo(const size_t netid, const char* name, const addrinfo* pai,
1614                               addrinfo** res) {
1615     struct addrinfo sentinel = {};
1616     struct addrinfo *p, *cur;
1617     FILE* hostf = nullptr;
1618 
1619     cur = &sentinel;
1620     _sethtent(&hostf);
1621     while ((p = _gethtent(&hostf, name, pai)) != nullptr) {
1622         cur->ai_next = p;
1623         while (cur && cur->ai_next) cur = cur->ai_next;
1624     }
1625     _endhtent(&hostf);
1626 
1627     if ((p = getCustomHosts(netid, name, pai)) != nullptr) {
1628         cur->ai_next = p;
1629     }
1630 
1631     *res = sentinel.ai_next;
1632     return sentinel.ai_next != nullptr;
1633 }
1634 
1635 /* resolver logic */
1636 
1637 namespace {
1638 
1639 constexpr int SLEEP_TIME_MS = 2;
1640 
getHerrnoFromRcode(int rcode)1641 int getHerrnoFromRcode(int rcode) {
1642     switch (rcode) {
1643         // Not defined in RFC.
1644         case RCODE_TIMEOUT:
1645             // DNS metrics monitors DNS query timeout.
1646             return NETD_RESOLV_H_ERRNO_EXT_TIMEOUT;  // extended h_errno.
1647         // Defined in RFC 1035 section 4.1.1.
1648         case NXDOMAIN:
1649             return HOST_NOT_FOUND;
1650         case SERVFAIL:
1651             return TRY_AGAIN;
1652         case NOERROR:
1653             return NO_DATA;
1654         case FORMERR:
1655         case NOTIMP:
1656         case REFUSED:
1657         default:
1658             return NO_RECOVERY;
1659     }
1660 }
1661 
1662 struct QueryResult {
1663     int ancount;
1664     int rcode;
1665     int herrno;
1666     int qerrno;
1667     NetworkDnsEventReported event;
1668 };
1669 
1670 // Formulate a normal query, send, and await answer.
1671 // Caller must parse answer and determine whether it answers the question.
doQuery(const char * name,res_target * t,ResState * res,std::chrono::milliseconds sleepTimeMs)1672 QueryResult doQuery(const char* name, res_target* t, ResState* res,
1673                     std::chrono::milliseconds sleepTimeMs) {
1674     HEADER* hp = (HEADER*)(void*)t->answer.data();
1675 
1676     hp->rcode = NOERROR;  // default
1677 
1678     const int cl = t->qclass;
1679     const int type = t->qtype;
1680     const int anslen = t->answer.size();
1681 
1682     LOG(DEBUG) << __func__ << ": (" << cl << ", " << type << ")";
1683 
1684     uint8_t buf[MAXPACKET];
1685     int n = res_nmkquery(QUERY, name, cl, type, {}, buf, res->netcontext_flags);
1686 
1687     if (n > 0 &&
1688         (res->netcontext_flags & (NET_CONTEXT_FLAG_USE_DNS_OVER_TLS | NET_CONTEXT_FLAG_USE_EDNS))) {
1689         n = res_nopt(res, n, buf, anslen);
1690     }
1691 
1692     NetworkDnsEventReported event;
1693     if (n <= 0) {
1694         LOG(ERROR) << __func__ << ": res_nmkquery failed";
1695         return {
1696                 .ancount = 0,
1697                 .rcode = -1,
1698                 .herrno = NO_RECOVERY,
1699                 .qerrno = errno,
1700                 .event = event,
1701         };
1702     }
1703 
1704     ResState res_temp = res->clone(&event);
1705 
1706     int rcode = NOERROR;
1707     n = res_nsend(&res_temp, std::span(buf, n), std::span(t->answer.data(), anslen), &rcode, 0,
1708                   sleepTimeMs);
1709     if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
1710         if (rcode != RCODE_TIMEOUT) rcode = hp->rcode;
1711         // if the query choked with EDNS0, retry without EDNS0
1712         if ((res_temp.netcontext_flags &
1713              (NET_CONTEXT_FLAG_USE_DNS_OVER_TLS | NET_CONTEXT_FLAG_USE_EDNS)) &&
1714             (res_temp.flags & RES_F_EDNS0ERR)) {
1715             LOG(INFO) << __func__ << ": retry without EDNS0";
1716             n = res_nmkquery(QUERY, name, cl, type, {}, buf, res_temp.netcontext_flags);
1717             n = res_nsend(&res_temp, std::span(buf, n), std::span(t->answer.data(), anslen), &rcode,
1718                           0);
1719         }
1720     }
1721 
1722     LOG(INFO) << __func__ << ": rcode=" << rcode << ", ancount=" << ntohs(hp->ancount)
1723               << ", return value=" << n;
1724 
1725     t->n = n;
1726     return {
1727             .ancount = ntohs(hp->ancount),
1728             .rcode = rcode,
1729             .qerrno = errno,
1730             .event = event,
1731     };
1732 }
1733 
1734 }  // namespace
1735 
1736 // This function runs doQuery() for each res_target in parallel.
res_queryN_parallel(const char * name,std::span<res_target> queries,android::net::NetworkDnsEventReported * event,int * herrno)1737 static int res_queryN_parallel(const char* name, std::span<res_target> queries,
1738                                android::net::NetworkDnsEventReported* event, int* herrno) {
1739     std::vector<std::future<QueryResult>> results;
1740     std::chrono::milliseconds sleepTimeMs{};
1741     bool is_first_iteration = true;
1742     for (auto& query : queries) {
1743         results.emplace_back(std::async(std::launch::async, doQuery, name, &query, query.res_state,
1744                                         sleepTimeMs));
1745         if (is_first_iteration) {
1746             // Avoiding gateways drop packets if queries are sent too close together
1747             // Only needed if we have multiple queries in a row.
1748             is_first_iteration = false;
1749             int sleepFlag = Experiments::getInstance()->getFlag("parallel_lookup_sleep_time",
1750                                                                 SLEEP_TIME_MS);
1751             if (sleepFlag > 1000) {
1752                 sleepFlag = 1000;
1753             }
1754             sleepTimeMs = std::chrono::milliseconds(sleepFlag);
1755         }
1756     }
1757 
1758     int ancount = 0;
1759     int rcode = 0;
1760 
1761     for (auto& f : results) {
1762         const QueryResult& r = f.get();
1763         if (r.herrno == NO_RECOVERY) {
1764             *herrno = r.herrno;
1765             return -1;
1766         }
1767         event->MergeFrom(r.event);
1768         ancount += r.ancount;
1769         rcode = r.rcode;
1770         errno = r.qerrno;
1771     }
1772 
1773     if (ancount == 0) {
1774         *herrno = getHerrnoFromRcode(rcode);
1775         return -1;
1776     }
1777 
1778     return ancount;
1779 }
1780 
1781 /*
1782  * Formulate a normal query, send, and retrieve answer in supplied buffer.
1783  * Return the size of the response on success, -1 on error.
1784  * If enabled, implement search rules until answer or unrecoverable failure
1785  * is detected.  Error code, if any, is left in *herrno.
1786  */
res_searchN(const char * name,std::span<res_target> queries,std::span<std::string> search_domains,bool is_mdns,android::net::NetworkDnsEventReported * event,int * herrno)1787 static int res_searchN(const char* name, std::span<res_target> queries,
1788                        std::span<std::string> search_domains, bool is_mdns,
1789                        android::net::NetworkDnsEventReported* event, int* herrno) {
1790     const char* cp;
1791     HEADER* hp;
1792     uint32_t dots;
1793     int ret, saved_herrno;
1794     int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
1795 
1796     assert(name != NULL);
1797     assert(!queries.empty());
1798 
1799     hp = (HEADER*)(void*)queries.front().answer.data();
1800 
1801     errno = 0;
1802     *herrno = HOST_NOT_FOUND; /* default, if we never query */
1803     dots = 0;
1804     for (cp = name; *cp; cp++) dots += (*cp == '.');
1805     const bool trailing_dot = (cp > name && *--cp == '.') ? true : false;
1806 
1807     // If there are dots in the name already, let's just give it a try 'as is'.
1808     saved_herrno = -1;
1809     if (dots >= NDOTS) {
1810         ret = res_querydomainN(name, NULL, queries, event, herrno);
1811         if (ret > 0) return (ret);
1812         saved_herrno = *herrno;
1813         tried_as_is++;
1814     }
1815 
1816     /*
1817      * We do at least one level of search if
1818      * - there is no dot, or
1819      * - there is at least one dot and there is no trailing dot.
1820      * - this is not a .local mDNS lookup.
1821      */
1822     if ((!dots || (dots && !trailing_dot)) && !is_mdns) {
1823         for (const auto& domain : search_domains) {
1824             ret = res_querydomainN(name, domain.c_str(), queries, event, herrno);
1825             if (ret > 0) return ret;
1826 
1827             /*
1828              * If no server present, give up.
1829              * If name isn't found in this domain,
1830              * keep trying higher domains in the search list
1831              * (if that's enabled).
1832              * On a NO_DATA error, keep trying, otherwise
1833              * a wildcard entry of another type could keep us
1834              * from finding this entry higher in the domain.
1835              * If we get some other error (negative answer or
1836              * server failure), then stop searching up,
1837              * but try the input name below in case it's
1838              * fully-qualified.
1839              */
1840             if (errno == ECONNREFUSED) {
1841                 *herrno = TRY_AGAIN;
1842                 return -1;
1843             }
1844 
1845             switch (*herrno) {
1846                 case NO_DATA:
1847                     got_nodata++;
1848                     [[fallthrough]];
1849                 case HOST_NOT_FOUND:
1850                     /* keep trying */
1851                     break;
1852                 case TRY_AGAIN:
1853                     if (hp->rcode == SERVFAIL) {
1854                         /* try next search element, if any */
1855                         got_servfail++;
1856                     }
1857                     break;
1858             }
1859         }
1860     }
1861 
1862     /*
1863      * if we have not already tried the name "as is", do that now.
1864      * note that we do this regardless of how many dots were in the
1865      * name or whether it ends with a dot.
1866      */
1867     if (!tried_as_is) {
1868         ret = res_querydomainN(name, NULL, queries, event, herrno);
1869         if (ret > 0) return ret;
1870     }
1871 
1872     /*
1873      * if we got here, we didn't satisfy the search.
1874      * if we did an initial full query, return that query's h_errno
1875      * (note that we wouldn't be here if that query had succeeded).
1876      * else if we ever got a nodata, send that back as the reason.
1877      * else send back meaningless h_errno, that being the one from
1878      * the last DNSRCH we did.
1879      */
1880     if (saved_herrno != -1)
1881         *herrno = saved_herrno;
1882     else if (got_nodata)
1883         *herrno = NO_DATA;
1884     else if (got_servfail)
1885         *herrno = TRY_AGAIN;
1886     return -1;
1887 }
1888 
1889 // Perform a call on res_query on the concatenation of name and domain,
1890 // removing a trailing dot from name if domain is NULL.
res_querydomainN(const char * name,const char * domain,std::span<res_target> queries,android::net::NetworkDnsEventReported * event,int * herrno)1891 static int res_querydomainN(const char* name, const char* domain, std::span<res_target> queries,
1892                             android::net::NetworkDnsEventReported* event, int* herrno) {
1893     char nbuf[MAXDNAME];
1894     const char* longname = nbuf;
1895     size_t n, d;
1896 
1897     assert(name != NULL);
1898 
1899     if (domain == NULL) {
1900         // Check for trailing '.'; copy without '.' if present.
1901         n = strlen(name);
1902         if (n + 1 > sizeof(nbuf)) {
1903             *herrno = NO_RECOVERY;
1904             return -1;
1905         }
1906         if (n > 0 && name[--n] == '.') {
1907             strncpy(nbuf, name, n);
1908             nbuf[n] = '\0';
1909         } else
1910             longname = name;
1911     } else {
1912         n = strlen(name);
1913         d = strlen(domain);
1914         if (n + 1 + d + 1 > sizeof(nbuf)) {
1915             *herrno = NO_RECOVERY;
1916             return -1;
1917         }
1918         snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
1919     }
1920     return res_queryN_parallel(longname, queries, event, herrno);
1921 }
1922