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*) calloc(1, 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     ai->ai_addrlen = afd->a_socklen;
681     ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
682     p = (char*) (void*) (ai->ai_addr);
683     memcpy(p + afd->a_off, addr, (size_t) afd->a_addrlen);
684     return ai;
685 }
686 
get_portmatch(const struct addrinfo * ai,const char * servname)687 static int get_portmatch(const struct addrinfo* ai, const char* servname) {
688     assert(ai != NULL);
689     /* servname may be NULL */
690 
691     return get_port(ai, servname, 1);
692 }
693 
get_port(const struct addrinfo * ai,const char * servname,int matchonly)694 static int get_port(const struct addrinfo* ai, const char* servname, int matchonly) {
695     const char* proto;
696     struct servent* sp;
697     uint port;
698     int allownumeric;
699 
700     assert(ai != NULL);
701     /* servname may be NULL */
702 
703     if (servname == NULL) return 0;
704     switch (ai->ai_family) {
705         case AF_INET:
706         case AF_INET6:
707             break;
708         default:
709             return 0;
710     }
711 
712     switch (ai->ai_socktype) {
713         case SOCK_RAW:
714             return EAI_SERVICE;
715         case SOCK_DGRAM:
716         case SOCK_STREAM:
717         case ANY:
718             allownumeric = 1;
719             break;
720         default:
721             return EAI_SOCKTYPE;
722     }
723 
724     if (android::base::ParseUint(servname, &port)) {
725         if (!allownumeric) return EAI_SERVICE;
726         if (port > 65535) return EAI_SERVICE;
727         port = htons(port);
728     } else {
729         if (ai->ai_flags & AI_NUMERICSERV) return EAI_NONAME;
730 
731         switch (ai->ai_socktype) {
732             case SOCK_DGRAM:
733                 proto = "udp";
734                 break;
735             case SOCK_STREAM:
736                 proto = "tcp";
737                 break;
738             default:
739                 proto = NULL;
740                 break;
741         }
742 
743         if ((sp = getservbyname(servname, proto)) == NULL) return EAI_SERVICE;
744         port = sp->s_port;
745     }
746 
747     if (!matchonly) {
748         switch (ai->ai_family) {
749             case AF_INET:
750                 ((struct sockaddr_in*) (void*) ai->ai_addr)->sin_port = port;
751                 break;
752             case AF_INET6:
753                 ((struct sockaddr_in6*) (void*) ai->ai_addr)->sin6_port = port;
754                 break;
755         }
756     }
757 
758     return 0;
759 }
760 
find_afd(int af)761 static const struct afd* find_afd(int af) {
762     const struct afd* afd;
763 
764     if (af == PF_UNSPEC) return NULL;
765     for (afd = afdl; afd->a_af; afd++) {
766         if (afd->a_af == af) return afd;
767     }
768     return NULL;
769 }
770 
771 // Convert a string to a scope identifier.
ip6_str2scopeid(const char * scope,struct sockaddr_in6 * sin6,uint32_t * scopeid)772 static int ip6_str2scopeid(const char* scope, struct sockaddr_in6* sin6, uint32_t* scopeid) {
773     struct in6_addr* a6;
774 
775     assert(scope != NULL);
776     assert(sin6 != NULL);
777     assert(scopeid != NULL);
778 
779     a6 = &sin6->sin6_addr;
780 
781     /* empty scopeid portion is invalid */
782     if (*scope == '\0') return -1;
783 
784     if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
785         /*
786          * We currently assume a one-to-one mapping between links
787          * and interfaces, so we simply use interface indices for
788          * like-local scopes.
789          */
790         *scopeid = if_nametoindex(scope);
791         if (*scopeid != 0) return 0;
792     }
793 
794     /* try to convert to a numeric id as a last resort*/
795     if (!android::base::ParseUint(scope, scopeid)) return -1;
796 
797     return 0;
798 }
799 
800 /* code duplicate with gethnamaddr.c */
801 
802 #define BOUNDED_INCR(x)      \
803     do {                     \
804         BOUNDS_CHECK(cp, x); \
805         cp += (x);           \
806     } while (0)
807 
808 #define BOUNDS_CHECK(ptr, count)     \
809     do {                             \
810         if (eom - (ptr) < (count)) { \
811             *herrno = NO_RECOVERY;   \
812             return NULL;             \
813         }                            \
814     } while (0)
815 
getanswer(const std::vector<uint8_t> & answer,int anslen,const char * qname,int qtype,const struct addrinfo * pai,int * herrno)816 static struct addrinfo* getanswer(const std::vector<uint8_t>& answer, int anslen, const char* qname,
817                                   int qtype, const struct addrinfo* pai, int* herrno) {
818     struct addrinfo sentinel = {};
819     struct addrinfo *cur;
820     struct addrinfo ai;
821     const struct afd* afd;
822     char* canonname;
823     const HEADER* hp;
824     const uint8_t* cp;
825     int n;
826     const uint8_t* eom;
827     char *bp, *ep;
828     int type, ancount, qdcount;
829     int haveanswer, had_error;
830     char tbuf[MAXDNAME];
831     char hostbuf[8 * 1024];
832 
833     assert(qname != NULL);
834     assert(pai != NULL);
835 
836     cur = &sentinel;
837 
838     canonname = NULL;
839     eom = answer.data() + anslen;
840 
841     bool (*name_ok)(const char* dn);
842     switch (qtype) {
843         case T_A:
844         case T_AAAA:
845         case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
846             name_ok = res_hnok;
847             break;
848         default:
849             return NULL; /* XXX should be abort(); */
850     }
851     /*
852      * find first satisfactory answer
853      */
854     hp = reinterpret_cast<const HEADER*>(answer.data());
855     ancount = ntohs(hp->ancount);
856     qdcount = ntohs(hp->qdcount);
857     bp = hostbuf;
858     ep = hostbuf + sizeof hostbuf;
859     cp = answer.data();
860     BOUNDED_INCR(HFIXEDSZ);
861     if (qdcount != 1) {
862         *herrno = NO_RECOVERY;
863         return (NULL);
864     }
865     n = dn_expand(answer.data(), eom, cp, bp, ep - bp);
866     if ((n < 0) || !(*name_ok)(bp)) {
867         *herrno = NO_RECOVERY;
868         return (NULL);
869     }
870     BOUNDED_INCR(n + QFIXEDSZ);
871     if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
872         /* res_send() has already verified that the query name is the
873          * same as the one we sent; this just gets the expanded name
874          * (i.e., with the succeeding search-domain tacked on).
875          */
876         n = strlen(bp) + 1; /* for the \0 */
877         if (n >= MAXHOSTNAMELEN) {
878             *herrno = NO_RECOVERY;
879             return (NULL);
880         }
881         canonname = bp;
882         bp += n;
883         /* The qname can be abbreviated, but h_name is now absolute. */
884         qname = canonname;
885     }
886     haveanswer = 0;
887     had_error = 0;
888     while (ancount-- > 0 && cp < eom && !had_error) {
889         n = dn_expand(answer.data(), eom, cp, bp, ep - bp);
890         if ((n < 0) || !(*name_ok)(bp)) {
891             had_error++;
892             continue;
893         }
894         cp += n; /* name */
895         BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
896         type = ntohs(*reinterpret_cast<const uint16_t*>(cp));
897         cp += INT16SZ; /* type */
898         int cl = ntohs(*reinterpret_cast<const uint16_t*>(cp));
899         cp += INT16SZ + INT32SZ; /* class, TTL */
900         n = ntohs(*reinterpret_cast<const uint16_t*>(cp));
901         cp += INT16SZ; /* len */
902         BOUNDS_CHECK(cp, n);
903         if (cl != C_IN) {
904             /* XXX - debug? syslog? */
905             cp += n;
906             continue; /* XXX - had_error++ ? */
907         }
908         if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) && type == T_CNAME) {
909             n = dn_expand(answer.data(), eom, cp, tbuf, sizeof tbuf);
910             if ((n < 0) || !(*name_ok)(tbuf)) {
911                 had_error++;
912                 continue;
913             }
914             cp += n;
915             /* Get canonical name. */
916             n = strlen(tbuf) + 1; /* for the \0 */
917             if (n > ep - bp || n >= MAXHOSTNAMELEN) {
918                 had_error++;
919                 continue;
920             }
921             strlcpy(bp, tbuf, (size_t)(ep - bp));
922             canonname = bp;
923             bp += n;
924             continue;
925         }
926         if (qtype == T_ANY) {
927             if (!(type == T_A || type == T_AAAA)) {
928                 cp += n;
929                 continue;
930             }
931         } else if (type != qtype) {
932             if (type != T_KEY && type != T_SIG)
933                 LOG(DEBUG) << __func__ << ": asked for \"" << qname << " " << p_class(C_IN) << " "
934                            << p_type(qtype) << "\", got type \"" << p_type(type) << "\"";
935             cp += n;
936             continue; /* XXX - had_error++ ? */
937         }
938         switch (type) {
939             case T_A:
940             case T_AAAA:
941                 if (strcasecmp(canonname, bp) != 0) {
942                     LOG(DEBUG) << __func__ << ": asked for \"" << canonname << "\", got \"" << bp
943                                << "\"";
944                     cp += n;
945                     continue; /* XXX - had_error++ ? */
946                 }
947                 if (type == T_A && n != INADDRSZ) {
948                     cp += n;
949                     continue;
950                 }
951                 if (type == T_AAAA && n != IN6ADDRSZ) {
952                     cp += n;
953                     continue;
954                 }
955                 if (type == T_AAAA) {
956                     struct in6_addr in6;
957                     memcpy(&in6, cp, IN6ADDRSZ);
958                     if (IN6_IS_ADDR_V4MAPPED(&in6)) {
959                         cp += n;
960                         continue;
961                     }
962                 }
963                 if (!haveanswer) {
964                     int nn;
965 
966                     canonname = bp;
967                     nn = strlen(bp) + 1; /* for the \0 */
968                     bp += nn;
969                 }
970 
971                 /* don't overwrite pai */
972                 ai = *pai;
973                 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
974                 afd = find_afd(ai.ai_family);
975                 if (afd == NULL) {
976                     cp += n;
977                     continue;
978                 }
979                 cur->ai_next = get_ai(&ai, afd, (const char*) cp);
980                 if (cur->ai_next == NULL) had_error++;
981                 while (cur && cur->ai_next) cur = cur->ai_next;
982                 cp += n;
983                 break;
984             default:
985                 abort();
986         }
987         if (!had_error) haveanswer++;
988     }
989     if (haveanswer) {
990         if (!canonname)
991             (void) get_canonname(pai, sentinel.ai_next, qname);
992         else
993             (void) get_canonname(pai, sentinel.ai_next, canonname);
994         *herrno = NETDB_SUCCESS;
995         return sentinel.ai_next;
996     }
997 
998     *herrno = NO_RECOVERY;
999     return NULL;
1000 }
1001 
1002 struct addrinfo_sort_elem {
1003     struct addrinfo* ai;
1004     int has_src_addr;
1005     sockaddr_union src_addr;
1006     int original_order;
1007 };
1008 
_get_scope(const struct sockaddr * addr)1009 static int _get_scope(const struct sockaddr* addr) {
1010     if (addr->sa_family == AF_INET6) {
1011         const struct sockaddr_in6* addr6 = (const struct sockaddr_in6*) addr;
1012         if (IN6_IS_ADDR_MULTICAST(&addr6->sin6_addr)) {
1013             return IPV6_ADDR_MC_SCOPE(&addr6->sin6_addr);
1014         } else if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr) ||
1015                    IN6_IS_ADDR_LINKLOCAL(&addr6->sin6_addr)) {
1016             /*
1017              * RFC 4291 section 2.5.3 says loopback is to be treated as having
1018              * link-local scope.
1019              */
1020             return IPV6_ADDR_SCOPE_LINKLOCAL;
1021         } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1022             return IPV6_ADDR_SCOPE_SITELOCAL;
1023         } else {
1024             return IPV6_ADDR_SCOPE_GLOBAL;
1025         }
1026     } else if (addr->sa_family == AF_INET) {
1027         const struct sockaddr_in* addr4 = (const struct sockaddr_in*) addr;
1028         unsigned long int na = ntohl(addr4->sin_addr.s_addr);
1029 
1030         if (IN_LOOPBACK(na) ||                 /* 127.0.0.0/8 */
1031             (na & 0xffff0000) == 0xa9fe0000) { /* 169.254.0.0/16 */
1032             return IPV6_ADDR_SCOPE_LINKLOCAL;
1033         } else {
1034             /*
1035              * RFC 6724 section 3.2. Other IPv4 addresses, including private addresses
1036              * and shared addresses (100.64.0.0/10), are assigned global scope.
1037              */
1038             return IPV6_ADDR_SCOPE_GLOBAL;
1039         }
1040     } else {
1041         /*
1042          * This should never happen.
1043          * Return a scope with low priority as a last resort.
1044          */
1045         return IPV6_ADDR_SCOPE_NODELOCAL;
1046     }
1047 }
1048 
1049 /* These macros are modelled after the ones in <netinet/in6.h>. */
1050 
1051 /* RFC 4380, section 2.6 */
1052 #define IN6_IS_ADDR_TEREDO(a) \
1053     ((*(const uint32_t*) (const void*) (&(a)->s6_addr[0]) == ntohl(0x20010000)))
1054 
1055 /* RFC 3056, section 2. */
1056 #define IN6_IS_ADDR_6TO4(a) (((a)->s6_addr[0] == 0x20) && ((a)->s6_addr[1] == 0x02))
1057 
1058 /* 6bone testing address area (3ffe::/16), deprecated in RFC 3701. */
1059 #define IN6_IS_ADDR_6BONE(a) (((a)->s6_addr[0] == 0x3f) && ((a)->s6_addr[1] == 0xfe))
1060 
1061 /*
1062  * Get the label for a given IPv4/IPv6 address.
1063  * RFC 6724, section 2.1.
1064  */
1065 
_get_label(const struct sockaddr * addr)1066 static int _get_label(const struct sockaddr* addr) {
1067     if (addr->sa_family == AF_INET) {
1068         return 4;
1069     } else if (addr->sa_family == AF_INET6) {
1070         const struct sockaddr_in6* addr6 = (const struct sockaddr_in6*) addr;
1071         if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1072             return 0;
1073         } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
1074             return 4;
1075         } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1076             return 2;
1077         } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1078             return 5;
1079         } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1080             return 13;
1081         } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr)) {
1082             return 3;
1083         } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1084             return 11;
1085         } else if (IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1086             return 12;
1087         } else {
1088             /* All other IPv6 addresses, including global unicast addresses. */
1089             return 1;
1090         }
1091     } else {
1092         /*
1093          * This should never happen.
1094          * Return a semi-random label as a last resort.
1095          */
1096         return 1;
1097     }
1098 }
1099 
1100 /*
1101  * Get the precedence for a given IPv4/IPv6 address.
1102  * RFC 6724, section 2.1.
1103  */
1104 
_get_precedence(const struct sockaddr * addr)1105 static int _get_precedence(const struct sockaddr* addr) {
1106     if (addr->sa_family == AF_INET) {
1107         return 35;
1108     } else if (addr->sa_family == AF_INET6) {
1109         const struct sockaddr_in6* addr6 = (const struct sockaddr_in6*) addr;
1110         if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1111             return 50;
1112         } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
1113             return 35;
1114         } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1115             return 30;
1116         } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1117             return 5;
1118         } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1119             return 3;
1120         } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr) ||
1121                    IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr) ||
1122                    IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1123             return 1;
1124         } else {
1125             /* All other IPv6 addresses, including global unicast addresses. */
1126             return 40;
1127         }
1128     } else {
1129         return 1;
1130     }
1131 }
1132 
1133 /*
1134  * Find number of matching initial bits between the two addresses a1 and a2.
1135  */
1136 
_common_prefix_len(const struct in6_addr * a1,const struct in6_addr * a2)1137 static int _common_prefix_len(const struct in6_addr* a1, const struct in6_addr* a2) {
1138     const char* p1 = (const char*) a1;
1139     const char* p2 = (const char*) a2;
1140     unsigned i;
1141 
1142     for (i = 0; i < sizeof(*a1); ++i) {
1143         int x, j;
1144 
1145         if (p1[i] == p2[i]) {
1146             continue;
1147         }
1148         x = p1[i] ^ p2[i];
1149         for (j = 0; j < CHAR_BIT; ++j) {
1150             if (x & (1 << (CHAR_BIT - 1))) {
1151                 return i * CHAR_BIT + j;
1152             }
1153             x <<= 1;
1154         }
1155     }
1156     return sizeof(*a1) * CHAR_BIT;
1157 }
1158 
1159 /*
1160  * Compare two source/destination address pairs.
1161  * RFC 6724, section 6.
1162  */
1163 
_rfc6724_compare(const void * ptr1,const void * ptr2)1164 static int _rfc6724_compare(const void* ptr1, const void* ptr2) {
1165     const struct addrinfo_sort_elem* a1 = (const struct addrinfo_sort_elem*) ptr1;
1166     const struct addrinfo_sort_elem* a2 = (const struct addrinfo_sort_elem*) ptr2;
1167     int scope_src1, scope_dst1, scope_match1;
1168     int scope_src2, scope_dst2, scope_match2;
1169     int label_src1, label_dst1, label_match1;
1170     int label_src2, label_dst2, label_match2;
1171     int precedence1, precedence2;
1172     int prefixlen1, prefixlen2;
1173 
1174     /* Rule 1: Avoid unusable destinations. */
1175     if (a1->has_src_addr != a2->has_src_addr) {
1176         return a2->has_src_addr - a1->has_src_addr;
1177     }
1178 
1179     /* Rule 2: Prefer matching scope. */
1180     scope_src1 = _get_scope(&a1->src_addr.sa);
1181     scope_dst1 = _get_scope(a1->ai->ai_addr);
1182     scope_match1 = (scope_src1 == scope_dst1);
1183 
1184     scope_src2 = _get_scope(&a2->src_addr.sa);
1185     scope_dst2 = _get_scope(a2->ai->ai_addr);
1186     scope_match2 = (scope_src2 == scope_dst2);
1187 
1188     if (scope_match1 != scope_match2) {
1189         return scope_match2 - scope_match1;
1190     }
1191 
1192     /*
1193      * Rule 3: Avoid deprecated addresses.
1194      * TODO(sesse): We don't currently have a good way of finding this.
1195      */
1196 
1197     /*
1198      * Rule 4: Prefer home addresses.
1199      * TODO(sesse): We don't currently have a good way of finding this.
1200      */
1201 
1202     /* Rule 5: Prefer matching label. */
1203     label_src1 = _get_label(&a1->src_addr.sa);
1204     label_dst1 = _get_label(a1->ai->ai_addr);
1205     label_match1 = (label_src1 == label_dst1);
1206 
1207     label_src2 = _get_label(&a2->src_addr.sa);
1208     label_dst2 = _get_label(a2->ai->ai_addr);
1209     label_match2 = (label_src2 == label_dst2);
1210 
1211     if (label_match1 != label_match2) {
1212         return label_match2 - label_match1;
1213     }
1214 
1215     /* Rule 6: Prefer higher precedence. */
1216     precedence1 = _get_precedence(a1->ai->ai_addr);
1217     precedence2 = _get_precedence(a2->ai->ai_addr);
1218     if (precedence1 != precedence2) {
1219         return precedence2 - precedence1;
1220     }
1221 
1222     /*
1223      * Rule 7: Prefer native transport.
1224      * TODO(sesse): We don't currently have a good way of finding this.
1225      */
1226 
1227     /* Rule 8: Prefer smaller scope. */
1228     if (scope_dst1 != scope_dst2) {
1229         return scope_dst1 - scope_dst2;
1230     }
1231 
1232     /*
1233      * Rule 9: Use longest matching prefix.
1234      * We implement this for IPv6 only, as the rules in RFC 6724 don't seem
1235      * to work very well directly applied to IPv4. (glibc uses information from
1236      * the routing table for a custom IPv4 implementation here.)
1237      */
1238     if (a1->has_src_addr && a1->ai->ai_addr->sa_family == AF_INET6 && a2->has_src_addr &&
1239         a2->ai->ai_addr->sa_family == AF_INET6) {
1240         const struct sockaddr_in6* a1_src = &a1->src_addr.sin6;
1241         const struct sockaddr_in6* a1_dst = (const struct sockaddr_in6*) a1->ai->ai_addr;
1242         const struct sockaddr_in6* a2_src = &a2->src_addr.sin6;
1243         const struct sockaddr_in6* a2_dst = (const struct sockaddr_in6*) a2->ai->ai_addr;
1244         prefixlen1 = _common_prefix_len(&a1_src->sin6_addr, &a1_dst->sin6_addr);
1245         prefixlen2 = _common_prefix_len(&a2_src->sin6_addr, &a2_dst->sin6_addr);
1246         if (prefixlen1 != prefixlen2) {
1247             return prefixlen2 - prefixlen1;
1248         }
1249     }
1250 
1251     /*
1252      * Rule 10: Leave the order unchanged.
1253      * We need this since qsort() is not necessarily stable.
1254      */
1255     return a1->original_order - a2->original_order;
1256 }
1257 
1258 /*
1259  * Find the source address that will be used if trying to connect to the given
1260  * address. src_addr must be assigned and large enough to hold a struct sockaddr_in6.
1261  * allow_v6_linklocal controls whether to accept link-local source addresses.
1262  *
1263  * Returns 1 if a source address was found, 0 if the address is unreachable,
1264  * and -1 if a fatal error occurred. If 0 or -1, the contents of src_addr are
1265  * undefined.
1266  */
1267 
_find_src_addr(const struct sockaddr * addr,struct sockaddr * src_addr,unsigned mark,uid_t uid,bool allow_v6_linklocal)1268 static int _find_src_addr(const struct sockaddr* addr, struct sockaddr* src_addr, unsigned mark,
1269                           uid_t uid, bool allow_v6_linklocal) {
1270     if (src_addr == nullptr) return -1;
1271 
1272     int ret;
1273     socklen_t len;
1274 
1275     switch (addr->sa_family) {
1276         case AF_INET:
1277             len = sizeof(struct sockaddr_in);
1278             break;
1279         case AF_INET6:
1280             len = sizeof(struct sockaddr_in6);
1281             break;
1282         default:
1283             /* No known usable source address for non-INET families. */
1284             return 0;
1285     }
1286 
1287     android::base::unique_fd sock(socket(addr->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP));
1288     if (sock.get() == -1) {
1289         if (errno == EAFNOSUPPORT) {
1290             return 0;
1291         } else {
1292             return -1;
1293         }
1294     }
1295     if (mark != MARK_UNSET && setsockopt(sock, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) < 0) {
1296         return 0;
1297     }
1298     if (uid > 0 && uid != NET_CONTEXT_INVALID_UID && fchown(sock, uid, (gid_t) -1) < 0) {
1299         return 0;
1300     }
1301     do {
1302         ret = connect(sock, addr, len);
1303     } while (ret == -1 && errno == EINTR);
1304 
1305     if (ret == -1) {
1306         return 0;
1307     }
1308 
1309     if (getsockname(sock, src_addr, &len) == -1) {
1310         return -1;
1311     }
1312 
1313     if (src_addr->sa_family == AF_INET6) {
1314         sockaddr_in6* sin6 = reinterpret_cast<sockaddr_in6*>(src_addr);
1315         if (!allow_v6_linklocal && IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
1316             // There is no point in sending an AAAA query because the device does not have a global
1317             // IP address. The only thing that can be affected is the hostname "localhost". Devices
1318             // with this setting will not be able to get the localhost v6 IP address ::1 via DNS
1319             // lookups, which is accessible by host local. But it is expected that a DNS server that
1320             // replies to "localhost" in AAAA should also reply in A. So it shouldn't cause issues.
1321             // Also, the current behavior will not be changed because hostname “localhost” only gets
1322             // 127.0.0.1 per etc/hosts configs.
1323             return 0;
1324         }
1325     }
1326 
1327     return 1;
1328 }
1329 
1330 /*
1331  * Sort the linked list starting at sentinel->ai_next in RFC6724 order.
1332  * Will leave the list unchanged if an error occurs.
1333  */
1334 
resolv_rfc6724_sort(struct addrinfo * list_sentinel,unsigned mark,uid_t uid)1335 void resolv_rfc6724_sort(struct addrinfo* list_sentinel, unsigned mark, uid_t uid) {
1336     if (list_sentinel == nullptr) return;
1337 
1338     struct addrinfo* cur;
1339     int nelem = 0, i;
1340     struct addrinfo_sort_elem* elems;
1341 
1342     cur = list_sentinel->ai_next;
1343     while (cur) {
1344         ++nelem;
1345         cur = cur->ai_next;
1346     }
1347 
1348     elems = (struct addrinfo_sort_elem*) calloc(nelem, sizeof(struct addrinfo_sort_elem));
1349     if (elems == NULL) {
1350         goto error;
1351     }
1352 
1353     /*
1354      * Convert the linked list to an array that also contains the candidate
1355      * source address for each destination address.
1356      */
1357     for (i = 0, cur = list_sentinel->ai_next; i < nelem; ++i, cur = cur->ai_next) {
1358         int has_src_addr;
1359         assert(cur != NULL);
1360         elems[i].ai = cur;
1361         elems[i].original_order = i;
1362 
1363         has_src_addr = _find_src_addr(cur->ai_addr, &elems[i].src_addr.sa, mark, uid,
1364                                       /*allow_v6_linklocal=*/true);
1365         if (has_src_addr == -1) {
1366             goto error;
1367         }
1368         elems[i].has_src_addr = has_src_addr;
1369     }
1370 
1371     /* Sort the addresses, and rearrange the linked list so it matches the sorted order. */
1372     qsort((void*) elems, nelem, sizeof(struct addrinfo_sort_elem), _rfc6724_compare);
1373 
1374     list_sentinel->ai_next = elems[0].ai;
1375     for (i = 0; i < nelem - 1; ++i) {
1376         elems[i].ai->ai_next = elems[i + 1].ai;
1377     }
1378     elems[nelem - 1].ai->ai_next = NULL;
1379 
1380 error:
1381     free(elems);
1382 }
1383 
dns_getaddrinfo(const char * name,const addrinfo * pai,const android_net_context * netcontext,addrinfo ** rv,NetworkDnsEventReported * event)1384 static int dns_getaddrinfo(const char* name, const addrinfo* pai,
1385                            const android_net_context* netcontext, addrinfo** rv,
1386                            NetworkDnsEventReported* event) {
1387     res_target q = {};
1388     res_target q2 = {};
1389     ResState res(netcontext, event);
1390     setMdnsFlag(name, res.netid, &(res.flags));
1391 
1392     switch (pai->ai_family) {
1393         case AF_UNSPEC: {
1394             /* prefer IPv6 */
1395             q.name = name;
1396             q.qclass = C_IN;
1397             int query_ipv6 = 1, query_ipv4 = 1;
1398             if (pai->ai_flags & AI_ADDRCONFIG) {
1399                 query_ipv6 = have_ipv6(netcontext->app_mark, netcontext->uid,
1400                                        isMdnsResolution(res.flags));
1401                 query_ipv4 = have_ipv4(netcontext->app_mark, netcontext->uid);
1402             }
1403             if (query_ipv6) {
1404                 q.qtype = T_AAAA;
1405                 if (query_ipv4) {
1406                     q.next = &q2;
1407                     q2.name = name;
1408                     q2.qclass = C_IN;
1409                     q2.qtype = T_A;
1410                 }
1411             } else if (query_ipv4) {
1412                 q.qtype = T_A;
1413             } else {
1414                 return EAI_NODATA;
1415             }
1416             break;
1417         }
1418         case AF_INET:
1419             q.name = name;
1420             q.qclass = C_IN;
1421             q.qtype = T_A;
1422             break;
1423         case AF_INET6:
1424             q.name = name;
1425             q.qclass = C_IN;
1426             q.qtype = T_AAAA;
1427             break;
1428         default:
1429             return EAI_FAMILY;
1430     }
1431 
1432     int he;
1433     if (res_searchN(name, &q, &res, &he) < 0) {
1434         // Return h_errno (he) to catch more detailed errors rather than EAI_NODATA.
1435         // Note that res_searchN() doesn't set the pair NETDB_INTERNAL and errno.
1436         // See also herrnoToAiErrno().
1437         return herrnoToAiErrno(he);
1438     }
1439 
1440     addrinfo sentinel = {};
1441     addrinfo* cur = &sentinel;
1442     addrinfo* ai = getanswer(q.answer, q.n, q.name, q.qtype, pai, &he);
1443     if (ai) {
1444         cur->ai_next = ai;
1445         while (cur && cur->ai_next) cur = cur->ai_next;
1446     }
1447     if (q.next) {
1448         ai = getanswer(q2.answer, q2.n, q2.name, q2.qtype, pai, &he);
1449         if (ai) cur->ai_next = ai;
1450     }
1451     if (sentinel.ai_next == NULL) {
1452         // Note that getanswer() doesn't set the pair NETDB_INTERNAL and errno.
1453         // See also herrnoToAiErrno().
1454         return herrnoToAiErrno(he);
1455     }
1456 
1457     resolv_rfc6724_sort(&sentinel, netcontext->app_mark, netcontext->uid);
1458 
1459     *rv = sentinel.ai_next;
1460     return 0;
1461 }
1462 
_sethtent(FILE ** hostf)1463 static void _sethtent(FILE** hostf) {
1464     if (!*hostf)
1465         *hostf = fopen(_PATH_HOSTS, "re");
1466     else
1467         rewind(*hostf);
1468 }
1469 
_endhtent(FILE ** hostf)1470 static void _endhtent(FILE** hostf) {
1471     if (*hostf) {
1472         (void) fclose(*hostf);
1473         *hostf = NULL;
1474     }
1475 }
1476 
_gethtent(FILE ** hostf,const char * name,const struct addrinfo * pai)1477 static struct addrinfo* _gethtent(FILE** hostf, const char* name, const struct addrinfo* pai) {
1478     char* p;
1479     char *cp, *tname, *cname;
1480     struct addrinfo *res0, *res;
1481     int error;
1482     const char* addr;
1483     char hostbuf[8 * 1024];
1484 
1485     assert(name != NULL);
1486     assert(pai != NULL);
1487 
1488     if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "re"))) return (NULL);
1489 again:
1490     if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf))) return (NULL);
1491     if (*p == '#') goto again;
1492     if (!(cp = strpbrk(p, "#\n"))) goto again;
1493     *cp = '\0';
1494     if (!(cp = strpbrk(p, " \t"))) goto again;
1495     *cp++ = '\0';
1496     addr = p;
1497     /* if this is not something we're looking for, skip it. */
1498     cname = NULL;
1499     while (cp && *cp) {
1500         if (*cp == ' ' || *cp == '\t') {
1501             cp++;
1502             continue;
1503         }
1504         if (!cname) cname = cp;
1505         tname = cp;
1506         if ((cp = strpbrk(cp, " \t")) != NULL) *cp++ = '\0';
1507         if (strcasecmp(name, tname) == 0) goto found;
1508     }
1509     goto again;
1510 
1511 found:
1512     error = getaddrinfo_numeric(addr, nullptr, *pai, &res0);
1513     if (error) goto again;
1514     for (res = res0; res; res = res->ai_next) {
1515         /* cover it up */
1516         res->ai_flags = pai->ai_flags;
1517 
1518         if (pai->ai_flags & AI_CANONNAME) {
1519             if (get_canonname(pai, res, cname) != 0) {
1520                 freeaddrinfo(res0);
1521                 goto again;
1522             }
1523         }
1524     }
1525     return res0;
1526 }
1527 
getCustomHosts(const size_t netid,const char * _Nonnull name,const struct addrinfo * _Nonnull pai)1528 static struct addrinfo* getCustomHosts(const size_t netid, const char* _Nonnull name,
1529                                        const struct addrinfo* _Nonnull pai) {
1530     struct addrinfo sentinel = {};
1531     struct addrinfo *res0, *res;
1532     res = &sentinel;
1533     std::vector<std::string> hosts = getCustomizedTableByName(netid, name);
1534     for (const std::string& host : hosts) {
1535         int error = getaddrinfo_numeric(host.c_str(), nullptr, *pai, &res0);
1536         if (!error && res0 != nullptr) {
1537             res->ai_next = res0;
1538             res = res0;
1539             res0 = nullptr;
1540         }
1541     }
1542     return sentinel.ai_next;
1543 }
1544 
files_getaddrinfo(const size_t netid,const char * name,const addrinfo * pai,addrinfo ** res)1545 static bool files_getaddrinfo(const size_t netid, const char* name, const addrinfo* pai,
1546                               addrinfo** res) {
1547     struct addrinfo sentinel = {};
1548     struct addrinfo *p, *cur;
1549     FILE* hostf = nullptr;
1550 
1551     cur = &sentinel;
1552     _sethtent(&hostf);
1553     while ((p = _gethtent(&hostf, name, pai)) != nullptr) {
1554         cur->ai_next = p;
1555         while (cur && cur->ai_next) cur = cur->ai_next;
1556     }
1557     _endhtent(&hostf);
1558 
1559     if ((p = getCustomHosts(netid, name, pai)) != nullptr) {
1560         cur->ai_next = p;
1561     }
1562 
1563     *res = sentinel.ai_next;
1564     return sentinel.ai_next != nullptr;
1565 }
1566 
1567 /* resolver logic */
1568 
1569 namespace {
1570 
1571 constexpr int SLEEP_TIME_MS = 2;
1572 
getHerrnoFromRcode(int rcode)1573 int getHerrnoFromRcode(int rcode) {
1574     switch (rcode) {
1575         // Not defined in RFC.
1576         case RCODE_TIMEOUT:
1577             // DNS metrics monitors DNS query timeout.
1578             return NETD_RESOLV_H_ERRNO_EXT_TIMEOUT;  // extended h_errno.
1579         // Defined in RFC 1035 section 4.1.1.
1580         case NXDOMAIN:
1581             return HOST_NOT_FOUND;
1582         case SERVFAIL:
1583             return TRY_AGAIN;
1584         case NOERROR:
1585             return NO_DATA;
1586         case FORMERR:
1587         case NOTIMP:
1588         case REFUSED:
1589         default:
1590             return NO_RECOVERY;
1591     }
1592 }
1593 
1594 struct QueryResult {
1595     int ancount;
1596     int rcode;
1597     int herrno;
1598     int qerrno;
1599     NetworkDnsEventReported event;
1600 };
1601 
1602 // Formulate a normal query, send, and await answer.
1603 // Caller must parse answer and determine whether it answers the question.
doQuery(const char * name,res_target * t,ResState * res,std::chrono::milliseconds sleepTimeMs)1604 QueryResult doQuery(const char* name, res_target* t, ResState* res,
1605                     std::chrono::milliseconds sleepTimeMs) {
1606     HEADER* hp = (HEADER*)(void*)t->answer.data();
1607 
1608     hp->rcode = NOERROR;  // default
1609 
1610     const int cl = t->qclass;
1611     const int type = t->qtype;
1612     const int anslen = t->answer.size();
1613 
1614     LOG(DEBUG) << __func__ << ": (" << cl << ", " << type << ")";
1615 
1616     uint8_t buf[MAXPACKET];
1617     int n = res_nmkquery(QUERY, name, cl, type, {}, buf, res->netcontext_flags);
1618 
1619     if (n > 0 &&
1620         (res->netcontext_flags & (NET_CONTEXT_FLAG_USE_DNS_OVER_TLS | NET_CONTEXT_FLAG_USE_EDNS))) {
1621         n = res_nopt(res, n, buf, anslen);
1622     }
1623 
1624     NetworkDnsEventReported event;
1625     if (n <= 0) {
1626         LOG(ERROR) << __func__ << ": res_nmkquery failed";
1627         return {
1628                 .ancount = 0,
1629                 .rcode = -1,
1630                 .herrno = NO_RECOVERY,
1631                 .qerrno = errno,
1632                 .event = event,
1633         };
1634     }
1635 
1636     ResState res_temp = res->clone(&event);
1637 
1638     int rcode = NOERROR;
1639     n = res_nsend(&res_temp, std::span(buf, n), std::span(t->answer.data(), anslen), &rcode, 0,
1640                   sleepTimeMs);
1641     if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
1642         if (rcode != RCODE_TIMEOUT) rcode = hp->rcode;
1643         // if the query choked with EDNS0, retry without EDNS0
1644         if ((res_temp.netcontext_flags &
1645              (NET_CONTEXT_FLAG_USE_DNS_OVER_TLS | NET_CONTEXT_FLAG_USE_EDNS)) &&
1646             (res_temp.flags & RES_F_EDNS0ERR)) {
1647             LOG(INFO) << __func__ << ": retry without EDNS0";
1648             n = res_nmkquery(QUERY, name, cl, type, {}, buf, res_temp.netcontext_flags);
1649             n = res_nsend(&res_temp, std::span(buf, n), std::span(t->answer.data(), anslen), &rcode,
1650                           0);
1651         }
1652     }
1653 
1654     LOG(INFO) << __func__ << ": rcode=" << rcode << ", ancount=" << ntohs(hp->ancount)
1655               << ", return value=" << n;
1656 
1657     t->n = n;
1658     return {
1659             .ancount = ntohs(hp->ancount),
1660             .rcode = rcode,
1661             .qerrno = errno,
1662             .event = event,
1663     };
1664 }
1665 
1666 }  // namespace
1667 
1668 // This function runs doQuery() for each res_target in parallel.
1669 // 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)1670 static int res_queryN_parallel(const char* name, res_target* target, ResState* res, int* herrno) {
1671     std::vector<std::future<QueryResult>> results;
1672     results.reserve(2);
1673     std::chrono::milliseconds sleepTimeMs{};
1674     for (res_target* t = target; t; t = t->next) {
1675         results.emplace_back(std::async(std::launch::async, doQuery, name, t, res, sleepTimeMs));
1676         // Avoiding gateways drop packets if queries are sent too close together
1677         // Only needed if we have multiple queries in a row.
1678         if (t->next) {
1679             int sleepFlag = Experiments::getInstance()->getFlag("parallel_lookup_sleep_time",
1680                                                                 SLEEP_TIME_MS);
1681             if (sleepFlag > 1000) sleepFlag = 1000;
1682             sleepTimeMs = std::chrono::milliseconds(sleepFlag);
1683         }
1684     }
1685 
1686     int ancount = 0;
1687     int rcode = 0;
1688 
1689     for (auto& f : results) {
1690         const QueryResult& r = f.get();
1691         if (r.herrno == NO_RECOVERY) {
1692             *herrno = r.herrno;
1693             return -1;
1694         }
1695         res->event->MergeFrom(r.event);
1696         ancount += r.ancount;
1697         rcode = r.rcode;
1698         errno = r.qerrno;
1699     }
1700 
1701     if (ancount == 0) {
1702         *herrno = getHerrnoFromRcode(rcode);
1703         return -1;
1704     }
1705 
1706     return ancount;
1707 }
1708 
1709 /*
1710  * Formulate a normal query, send, and retrieve answer in supplied buffer.
1711  * Return the size of the response on success, -1 on error.
1712  * If enabled, implement search rules until answer or unrecoverable failure
1713  * is detected.  Error code, if any, is left in *herrno.
1714  */
res_searchN(const char * name,res_target * target,ResState * res,int * herrno)1715 static int res_searchN(const char* name, res_target* target, ResState* res, int* herrno) {
1716     const char* cp;
1717     HEADER* hp;
1718     uint32_t dots;
1719     int ret, saved_herrno;
1720     int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
1721 
1722     assert(name != NULL);
1723     assert(target != NULL);
1724 
1725     hp = (HEADER*)(void*)target->answer.data();
1726 
1727     errno = 0;
1728     *herrno = HOST_NOT_FOUND; /* default, if we never query */
1729     dots = 0;
1730     for (cp = name; *cp; cp++) dots += (*cp == '.');
1731     const bool trailing_dot = (cp > name && *--cp == '.') ? true : false;
1732 
1733     /*
1734      * If there are dots in the name already, let's just give it a try
1735      * 'as is'.  The threshold can be set with the "ndots" option.
1736      */
1737     saved_herrno = -1;
1738     if (dots >= res->ndots) {
1739         ret = res_querydomainN(name, NULL, target, res, herrno);
1740         if (ret > 0) return (ret);
1741         saved_herrno = *herrno;
1742         tried_as_is++;
1743     }
1744 
1745     /*
1746      * We do at least one level of search if
1747      *	 - there is no dot, or
1748      *	 - there is at least one dot and there is no trailing dot.
1749      * - this is not a .local mDNS lookup.
1750      */
1751     if ((!dots || (dots && !trailing_dot)) && !isMdnsResolution(res->flags)) {
1752         /* Unfortunately we need to set stuff up before
1753          * the domain stuff is tried.  Will have a better
1754          * fix after thread pools are used.
1755          */
1756         resolv_populate_res_for_net(res);
1757 
1758         for (const auto& domain : res->search_domains) {
1759             ret = res_querydomainN(name, domain.c_str(), target, res, herrno);
1760             if (ret > 0) return ret;
1761 
1762             /*
1763              * If no server present, give up.
1764              * If name isn't found in this domain,
1765              * keep trying higher domains in the search list
1766              * (if that's enabled).
1767              * On a NO_DATA error, keep trying, otherwise
1768              * a wildcard entry of another type could keep us
1769              * from finding this entry higher in the domain.
1770              * If we get some other error (negative answer or
1771              * server failure), then stop searching up,
1772              * but try the input name below in case it's
1773              * fully-qualified.
1774              */
1775             if (errno == ECONNREFUSED) {
1776                 *herrno = TRY_AGAIN;
1777                 return -1;
1778             }
1779 
1780             switch (*herrno) {
1781                 case NO_DATA:
1782                     got_nodata++;
1783                     [[fallthrough]];
1784                 case HOST_NOT_FOUND:
1785                     /* keep trying */
1786                     break;
1787                 case TRY_AGAIN:
1788                     if (hp->rcode == SERVFAIL) {
1789                         /* try next search element, if any */
1790                         got_servfail++;
1791                     }
1792                     break;
1793             }
1794         }
1795     }
1796 
1797     /*
1798      * if we have not already tried the name "as is", do that now.
1799      * note that we do this regardless of how many dots were in the
1800      * name or whether it ends with a dot.
1801      */
1802     if (!tried_as_is) {
1803         ret = res_querydomainN(name, NULL, target, res, herrno);
1804         if (ret > 0) return ret;
1805     }
1806 
1807     /*
1808      * if we got here, we didn't satisfy the search.
1809      * if we did an initial full query, return that query's h_errno
1810      * (note that we wouldn't be here if that query had succeeded).
1811      * else if we ever got a nodata, send that back as the reason.
1812      * else send back meaningless h_errno, that being the one from
1813      * the last DNSRCH we did.
1814      */
1815     if (saved_herrno != -1)
1816         *herrno = saved_herrno;
1817     else if (got_nodata)
1818         *herrno = NO_DATA;
1819     else if (got_servfail)
1820         *herrno = TRY_AGAIN;
1821     return -1;
1822 }
1823 
1824 // Perform a call on res_query on the concatenation of name and domain,
1825 // 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)1826 static int res_querydomainN(const char* name, const char* domain, res_target* target, ResState* res,
1827                             int* herrno) {
1828     char nbuf[MAXDNAME];
1829     const char* longname = nbuf;
1830     size_t n, d;
1831 
1832     assert(name != NULL);
1833 
1834     if (domain == NULL) {
1835         // Check for trailing '.'; copy without '.' if present.
1836         n = strlen(name);
1837         if (n + 1 > sizeof(nbuf)) {
1838             *herrno = NO_RECOVERY;
1839             return -1;
1840         }
1841         if (n > 0 && name[--n] == '.') {
1842             strncpy(nbuf, name, n);
1843             nbuf[n] = '\0';
1844         } else
1845             longname = name;
1846     } else {
1847         n = strlen(name);
1848         d = strlen(domain);
1849         if (n + 1 + d + 1 > sizeof(nbuf)) {
1850             *herrno = NO_RECOVERY;
1851             return -1;
1852         }
1853         snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
1854     }
1855     return res_queryN_parallel(longname, target, res, herrno);
1856 }
1857