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