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_storage sa;
231     return _find_src_addr(&addr.sa, (struct sockaddr*)&sa, mark, uid,
232                           /*allow_v6_linklocal=*/mdns) == 1;
233 }
234 
have_ipv4(unsigned mark,uid_t uid)235 static int have_ipv4(unsigned mark, uid_t uid) {
236     static const struct sockaddr_in sin_test = {
237             .sin_family = AF_INET,
238             .sin_addr.s_addr = __constant_htonl(0x08080808L)  // 8.8.8.8
239     };
240     sockaddr_union addr = {.sin = sin_test};
241     sockaddr_storage sa;
242     return _find_src_addr(&addr.sa, (struct sockaddr*)&sa, mark, uid,
243                           /*(don't care) allow_v6_linklocal=*/false) == 1;
244 }
245 
246 // Internal version of getaddrinfo(), but limited to AI_NUMERICHOST.
247 // NOTE: also called by resolv_set_nameservers().
getaddrinfo_numeric(const char * hostname,const char * servname,addrinfo hints,addrinfo ** result)248 int getaddrinfo_numeric(const char* hostname, const char* servname, addrinfo hints,
249                         addrinfo** result) {
250     hints.ai_flags = AI_NUMERICHOST;
251     const android_net_context netcontext = {
252             .app_netid = NETID_UNSET,
253             .app_mark = MARK_UNSET,
254             .dns_netid = NETID_UNSET,
255             .dns_mark = MARK_UNSET,
256             .uid = NET_CONTEXT_INVALID_UID,
257             .pid = NET_CONTEXT_INVALID_PID,
258     };
259     NetworkDnsEventReported event;
260     return android_getaddrinfofornetcontext(hostname, servname, &hints, &netcontext, result,
261                                             &event);
262 }
263 
264 namespace {
265 
validateHints(const addrinfo * _Nonnull hints)266 int validateHints(const addrinfo* _Nonnull hints) {
267     if (!hints) return EAI_BADHINTS;
268 
269     // error check for hints
270     if (hints->ai_addrlen || hints->ai_canonname || hints->ai_addr || hints->ai_next) {
271         return EAI_BADHINTS;
272     }
273     if (hints->ai_flags & ~AI_MASK) {
274         return EAI_BADFLAGS;
275     }
276     if (!(hints->ai_family == PF_UNSPEC || hints->ai_family == PF_INET ||
277           hints->ai_family == PF_INET6)) {
278         return EAI_FAMILY;
279     }
280 
281     // Socket types which are not in explore_options.
282     switch (hints->ai_socktype) {
283         case SOCK_RAW:
284         case SOCK_DGRAM:
285         case SOCK_STREAM:
286         case ANY:
287             break;
288         default:
289             return EAI_SOCKTYPE;
290     }
291 
292     if (hints->ai_socktype == ANY || hints->ai_protocol == ANY) return 0;
293 
294     // if both socktype/protocol are specified, check if they are meaningful combination.
295     for (const Explore& ex : explore_options) {
296         if (hints->ai_family != ex.e_af) continue;
297         if (ex.e_socktype == ANY) continue;
298         if (ex.e_protocol == ANY) continue;
299         if (hints->ai_socktype == ex.e_socktype && hints->ai_protocol != ex.e_protocol) {
300             return EAI_BADHINTS;
301         }
302     }
303 
304     return 0;
305 }
306 
307 }  // namespace
308 
android_getaddrinfofornetcontext(const char * hostname,const char * servname,const addrinfo * hints,const android_net_context * netcontext,addrinfo ** res,NetworkDnsEventReported * event)309 int android_getaddrinfofornetcontext(const char* hostname, const char* servname,
310                                      const addrinfo* hints, const android_net_context* netcontext,
311                                      addrinfo** res, NetworkDnsEventReported* event) {
312     // hostname is allowed to be nullptr
313     // servname is allowed to be nullptr
314     // hints is allowed to be nullptr
315     assert(res != nullptr);
316     assert(netcontext != nullptr);
317     assert(event != nullptr);
318 
319     addrinfo sentinel = {};
320     addrinfo* cur = &sentinel;
321     int error = 0;
322 
323     do {
324         if (hostname == nullptr && servname == nullptr) {
325             error = EAI_NONAME;
326             break;
327         }
328 
329         if (hints && (error = validateHints(hints))) break;
330         addrinfo ai = hints ? *hints : addrinfo{};
331 
332         // Check for special cases:
333         // (1) numeric servname is disallowed if socktype/protocol are left unspecified.
334         // (2) servname is disallowed for raw and other inet{,6} sockets.
335         if (MATCH_FAMILY(ai.ai_family, PF_INET, 1) || MATCH_FAMILY(ai.ai_family, PF_INET6, 1)) {
336             addrinfo tmp = ai;
337             if (tmp.ai_family == PF_UNSPEC) {
338                 tmp.ai_family = PF_INET6;
339             }
340             error = get_portmatch(&tmp, servname);
341             if (error) break;
342         }
343 
344         // NULL hostname, or numeric hostname
345         for (const Explore& ex : explore_options) {
346             /* PF_UNSPEC entries are prepared for DNS queries only */
347             if (ex.e_af == PF_UNSPEC) continue;
348 
349             if (!MATCH_FAMILY(ai.ai_family, ex.e_af, WILD_AF(ex))) continue;
350             if (!MATCH(ai.ai_socktype, ex.e_socktype, WILD_SOCKTYPE(ex))) continue;
351             if (!MATCH(ai.ai_protocol, ex.e_protocol, WILD_PROTOCOL(ex))) continue;
352 
353             addrinfo tmp = ai;
354             if (tmp.ai_family == PF_UNSPEC) tmp.ai_family = ex.e_af;
355             if (tmp.ai_socktype == ANY && ex.e_socktype != ANY) tmp.ai_socktype = ex.e_socktype;
356             if (tmp.ai_protocol == ANY && ex.e_protocol != ANY) tmp.ai_protocol = ex.e_protocol;
357 
358             LOG(DEBUG) << __func__ << ": explore_numeric: ai_family=" << tmp.ai_family
359                        << " ai_socktype=" << tmp.ai_socktype << " ai_protocol=" << tmp.ai_protocol;
360             if (hostname == nullptr)
361                 error = explore_null(&tmp, servname, &cur->ai_next);
362             else
363                 error = explore_numeric_scope(&tmp, hostname, servname, &cur->ai_next);
364 
365             if (error) break;
366 
367             while (cur->ai_next) cur = cur->ai_next;
368         }
369         if (error) break;
370 
371         // If numeric representation of AF1 can be interpreted as FQDN
372         // representation of AF2, we need to think again about the code below.
373         if (sentinel.ai_next) break;
374 
375         if (hostname == nullptr) {
376             error = EAI_NODATA;
377             break;
378         }
379         if (ai.ai_flags & AI_NUMERICHOST) {
380             error = EAI_NONAME;
381             break;
382         }
383 
384         return resolv_getaddrinfo(hostname, servname, hints, netcontext, res, event);
385     } while (0);
386 
387     if (error) {
388         freeaddrinfo(sentinel.ai_next);
389         *res = nullptr;
390     } else {
391         *res = sentinel.ai_next;
392     }
393     return error;
394 }
395 
resolv_getaddrinfo(const char * _Nonnull hostname,const char * servname,const addrinfo * hints,const android_net_context * _Nonnull netcontext,addrinfo ** _Nonnull res,NetworkDnsEventReported * _Nonnull event)396 int resolv_getaddrinfo(const char* _Nonnull hostname, const char* servname, const addrinfo* hints,
397                        const android_net_context* _Nonnull netcontext, addrinfo** _Nonnull res,
398                        NetworkDnsEventReported* _Nonnull event) {
399     if (hostname == nullptr && servname == nullptr) return EAI_NONAME;
400     if (hostname == nullptr) return EAI_NODATA;
401 
402     // servname is allowed to be nullptr
403     // hints is allowed to be nullptr
404     assert(res != nullptr);
405     assert(netcontext != nullptr);
406     assert(event != nullptr);
407 
408     int error = EAI_FAIL;
409     if (hints && (error = validateHints(hints))) {
410         *res = nullptr;
411         return error;
412     }
413 
414     addrinfo ai = hints ? *hints : addrinfo{};
415     addrinfo sentinel = {};
416     addrinfo* cur = &sentinel;
417     // hostname as alphanumeric name.
418     // We would like to prefer AF_INET6 over AF_INET, so we'll make a outer loop by AFs.
419     for (const Explore& ex : explore_options) {
420         // Require exact match for family field
421         if (ai.ai_family != ex.e_af) continue;
422 
423         if (!MATCH(ai.ai_socktype, ex.e_socktype, WILD_SOCKTYPE(ex))) continue;
424 
425         if (!MATCH(ai.ai_protocol, ex.e_protocol, WILD_PROTOCOL(ex))) continue;
426 
427         addrinfo tmp = ai;
428         if (tmp.ai_socktype == ANY && ex.e_socktype != ANY) tmp.ai_socktype = ex.e_socktype;
429         if (tmp.ai_protocol == ANY && ex.e_protocol != ANY) tmp.ai_protocol = ex.e_protocol;
430 
431         LOG(DEBUG) << __func__ << ": explore_fqdn(): ai_family=" << tmp.ai_family
432                    << " ai_socktype=" << tmp.ai_socktype << " ai_protocol=" << tmp.ai_protocol;
433         error = explore_fqdn(&tmp, hostname, servname, &cur->ai_next, netcontext, event);
434 
435         while (cur->ai_next) cur = cur->ai_next;
436     }
437 
438     // Propagate the last error from explore_fqdn(), but only when *all* attempts failed.
439     if ((*res = sentinel.ai_next)) return 0;
440 
441     // TODO: consider removing freeaddrinfo.
442     freeaddrinfo(sentinel.ai_next);
443     *res = nullptr;
444     return (error == 0) ? EAI_FAIL : error;
445 }
446 
447 // FQDN hostname, DNS lookup
explore_fqdn(const addrinfo * pai,const char * hostname,const char * servname,addrinfo ** res,const android_net_context * netcontext,NetworkDnsEventReported * event)448 static int explore_fqdn(const addrinfo* pai, const char* hostname, const char* servname,
449                         addrinfo** res, const android_net_context* netcontext,
450                         NetworkDnsEventReported* event) {
451     assert(pai != nullptr);
452     // hostname may be nullptr
453     // servname may be nullptr
454     assert(res != nullptr);
455 
456     addrinfo* result = nullptr;
457     int error = 0;
458 
459     // If the servname does not match socktype/protocol, return error code.
460     if ((error = get_portmatch(pai, servname))) return error;
461 
462     if (!files_getaddrinfo(netcontext->dns_netid, hostname, pai, &result)) {
463         error = dns_getaddrinfo(hostname, pai, netcontext, &result, event);
464     }
465     if (error) {
466         freeaddrinfo(result);
467         return error;
468     }
469 
470     for (addrinfo* cur = result; cur; cur = cur->ai_next) {
471         // canonname should be filled already
472         if ((error = get_port(cur, servname, 0))) {
473             freeaddrinfo(result);
474             return error;
475         }
476     }
477     *res = result;
478     return 0;
479 }
480 
481 /*
482  * hostname == NULL.
483  * passive socket -> anyaddr (0.0.0.0 or ::)
484  * non-passive socket -> localhost (127.0.0.1 or ::1)
485  */
explore_null(const struct addrinfo * pai,const char * servname,struct addrinfo ** res)486 static int explore_null(const struct addrinfo* pai, const char* servname, struct addrinfo** res) {
487     int s;
488     const struct afd* afd;
489     struct addrinfo* cur;
490     struct addrinfo sentinel;
491     int error;
492 
493     LOG(DEBUG) << __func__;
494 
495     assert(pai != NULL);
496     /* servname may be NULL */
497     assert(res != NULL);
498 
499     *res = NULL;
500     sentinel.ai_next = NULL;
501     cur = &sentinel;
502 
503     /*
504      * filter out AFs that are not supported by the kernel
505      * XXX errno?
506      */
507     s = socket(pai->ai_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
508     if (s < 0) {
509         if (errno != EMFILE) return 0;
510     } else
511         close(s);
512 
513     /*
514      * if the servname does not match socktype/protocol, ignore it.
515      */
516     if (get_portmatch(pai, servname) != 0) return 0;
517 
518     afd = find_afd(pai->ai_family);
519     if (afd == NULL) return 0;
520 
521     if (pai->ai_flags & AI_PASSIVE) {
522         GET_AI(cur->ai_next, afd, afd->a_addrany);
523         GET_PORT(cur->ai_next, servname);
524     } else {
525         GET_AI(cur->ai_next, afd, afd->a_loopback);
526         GET_PORT(cur->ai_next, servname);
527     }
528     cur = cur->ai_next;
529 
530     *res = sentinel.ai_next;
531     return 0;
532 
533 free:
534     freeaddrinfo(sentinel.ai_next);
535     return error;
536 }
537 
538 /*
539  * numeric hostname
540  */
explore_numeric(const struct addrinfo * pai,const char * hostname,const char * servname,struct addrinfo ** res,const char * canonname)541 static int explore_numeric(const struct addrinfo* pai, const char* hostname, const char* servname,
542                            struct addrinfo** res, const char* canonname) {
543     const struct afd* afd;
544     struct addrinfo* cur;
545     struct addrinfo sentinel;
546     int error;
547     char pton[PTON_MAX];
548 
549     assert(pai != NULL);
550     /* hostname may be NULL */
551     /* servname may be NULL */
552     assert(res != NULL);
553 
554     *res = NULL;
555     sentinel.ai_next = NULL;
556     cur = &sentinel;
557 
558     /*
559      * if the servname does not match socktype/protocol, ignore it.
560      */
561     if (get_portmatch(pai, servname) != 0) return 0;
562 
563     afd = find_afd(pai->ai_family);
564     if (afd == NULL) return 0;
565 
566     if (inet_pton(afd->a_af, hostname, pton) == 1) {
567         if (pai->ai_family == afd->a_af || pai->ai_family == PF_UNSPEC /*?*/) {
568             GET_AI(cur->ai_next, afd, pton);
569             GET_PORT(cur->ai_next, servname);
570             if ((pai->ai_flags & AI_CANONNAME)) {
571                 /*
572                  * Set the numeric address itself as
573                  * the canonical name, based on a
574                  * clarification in rfc2553bis-03.
575                  */
576                 error = get_canonname(pai, cur->ai_next, canonname);
577                 if (error != 0) {
578                     freeaddrinfo(sentinel.ai_next);
579                     return error;
580                 }
581             }
582             while (cur->ai_next) cur = cur->ai_next;
583         } else
584             return EAI_FAMILY;
585     }
586 
587     *res = sentinel.ai_next;
588     return 0;
589 
590 free:
591     freeaddrinfo(sentinel.ai_next);
592     return error;
593 }
594 
595 /*
596  * numeric hostname with scope
597  */
explore_numeric_scope(const struct addrinfo * pai,const char * hostname,const char * servname,struct addrinfo ** res)598 static int explore_numeric_scope(const struct addrinfo* pai, const char* hostname,
599                                  const char* servname, struct addrinfo** res) {
600     const struct afd* afd;
601     struct addrinfo* cur;
602     int error;
603     const char *cp, *scope, *addr;
604     struct sockaddr_in6* sin6;
605 
606     LOG(DEBUG) << __func__;
607 
608     assert(pai != NULL);
609     /* hostname may be NULL */
610     /* servname may be NULL */
611     assert(res != NULL);
612 
613     /*
614      * if the servname does not match socktype/protocol, ignore it.
615      */
616     if (get_portmatch(pai, servname) != 0) return 0;
617 
618     afd = find_afd(pai->ai_family);
619     if (afd == NULL) return 0;
620 
621     if (!afd->a_scoped) return explore_numeric(pai, hostname, servname, res, hostname);
622 
623     cp = strchr(hostname, SCOPE_DELIMITER);
624     if (cp == NULL) return explore_numeric(pai, hostname, servname, res, hostname);
625 
626     /*
627      * Handle special case of <scoped_address><delimiter><scope id>
628      */
629     char* hostname2 = strdup(hostname);
630     if (hostname2 == NULL) return EAI_MEMORY;
631     /* terminate at the delimiter */
632     hostname2[cp - hostname] = '\0';
633     addr = hostname2;
634     scope = cp + 1;
635 
636     error = explore_numeric(pai, addr, servname, res, hostname);
637     if (error == 0) {
638         uint32_t scopeid;
639 
640         for (cur = *res; cur; cur = cur->ai_next) {
641             if (cur->ai_family != AF_INET6) continue;
642             sin6 = (struct sockaddr_in6*) (void*) cur->ai_addr;
643             if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
644                 free(hostname2);
645                 return (EAI_NODATA); /* XXX: is return OK? */
646             }
647             sin6->sin6_scope_id = scopeid;
648         }
649     }
650 
651     free(hostname2);
652 
653     return error;
654 }
655 
get_canonname(const struct addrinfo * pai,struct addrinfo * ai,const char * str)656 static int get_canonname(const struct addrinfo* pai, struct addrinfo* ai, const char* str) {
657     assert(pai != NULL);
658     assert(ai != NULL);
659     assert(str != NULL);
660 
661     if ((pai->ai_flags & AI_CANONNAME) != 0) {
662         ai->ai_canonname = strdup(str);
663         if (ai->ai_canonname == NULL) return EAI_MEMORY;
664     }
665     return 0;
666 }
667 
get_ai(const struct addrinfo * pai,const struct afd * afd,const char * addr)668 static struct addrinfo* get_ai(const struct addrinfo* pai, const struct afd* afd,
669                                const char* addr) {
670     char* p;
671     struct addrinfo* ai;
672 
673     assert(pai != NULL);
674     assert(afd != NULL);
675     assert(addr != NULL);
676 
677     ai = (struct addrinfo*) calloc(1, sizeof(struct addrinfo) + sizeof(sockaddr_union));
678     if (ai == NULL) return NULL;
679 
680     memcpy(ai, pai, sizeof(struct addrinfo));
681     ai->ai_addr = (struct sockaddr*) (void*) (ai + 1);
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 (src_addr->sa_family == AF_INET6) {
1316         sockaddr_in6* sin6 = reinterpret_cast<sockaddr_in6*>(src_addr);
1317         if (!allow_v6_linklocal && IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
1318             // There is no point in sending an AAAA query because the device does not have a global
1319             // IP address. The only thing that can be affected is the hostname "localhost". Devices
1320             // with this setting will not be able to get the localhost v6 IP address ::1 via DNS
1321             // lookups, which is accessible by host local. But it is expected that a DNS server that
1322             // replies to "localhost" in AAAA should also reply in A. So it shouldn't cause issues.
1323             // Also, the current behavior will not be changed because hostname “localhost” only gets
1324             // 127.0.0.1 per etc/hosts configs.
1325             return 0;
1326         }
1327     }
1328 
1329     return 1;
1330 }
1331 
1332 /*
1333  * Sort the linked list starting at sentinel->ai_next in RFC6724 order.
1334  * Will leave the list unchanged if an error occurs.
1335  */
1336 
resolv_rfc6724_sort(struct addrinfo * list_sentinel,unsigned mark,uid_t uid)1337 void resolv_rfc6724_sort(struct addrinfo* list_sentinel, unsigned mark, uid_t uid) {
1338     if (list_sentinel == nullptr) return;
1339 
1340     struct addrinfo* cur;
1341     int nelem = 0, i;
1342     struct addrinfo_sort_elem* elems;
1343 
1344     cur = list_sentinel->ai_next;
1345     while (cur) {
1346         ++nelem;
1347         cur = cur->ai_next;
1348     }
1349 
1350     elems = (struct addrinfo_sort_elem*) calloc(nelem, sizeof(struct addrinfo_sort_elem));
1351     if (elems == NULL) {
1352         goto error;
1353     }
1354 
1355     /*
1356      * Convert the linked list to an array that also contains the candidate
1357      * source address for each destination address.
1358      */
1359     for (i = 0, cur = list_sentinel->ai_next; i < nelem; ++i, cur = cur->ai_next) {
1360         int has_src_addr;
1361         assert(cur != NULL);
1362         elems[i].ai = cur;
1363         elems[i].original_order = i;
1364 
1365         has_src_addr = _find_src_addr(cur->ai_addr, &elems[i].src_addr.sa, mark, uid,
1366                                       /*allow_v6_linklocal=*/true);
1367         if (has_src_addr == -1) {
1368             goto error;
1369         }
1370         elems[i].has_src_addr = has_src_addr;
1371     }
1372 
1373     /* Sort the addresses, and rearrange the linked list so it matches the sorted order. */
1374     qsort((void*) elems, nelem, sizeof(struct addrinfo_sort_elem), _rfc6724_compare);
1375 
1376     list_sentinel->ai_next = elems[0].ai;
1377     for (i = 0; i < nelem - 1; ++i) {
1378         elems[i].ai->ai_next = elems[i + 1].ai;
1379     }
1380     elems[nelem - 1].ai->ai_next = NULL;
1381 
1382 error:
1383     free(elems);
1384 }
1385 
dns_getaddrinfo(const char * name,const addrinfo * pai,const android_net_context * netcontext,addrinfo ** rv,NetworkDnsEventReported * event)1386 static int dns_getaddrinfo(const char* name, const addrinfo* pai,
1387                            const android_net_context* netcontext, addrinfo** rv,
1388                            NetworkDnsEventReported* event) {
1389     res_target q = {};
1390     res_target q2 = {};
1391     ResState res(netcontext, event);
1392     setMdnsFlag(name, res.netid, &(res.flags));
1393 
1394     switch (pai->ai_family) {
1395         case AF_UNSPEC: {
1396             /* prefer IPv6 */
1397             q.name = name;
1398             q.qclass = C_IN;
1399             int query_ipv6 = 1, query_ipv4 = 1;
1400             if (pai->ai_flags & AI_ADDRCONFIG) {
1401                 query_ipv6 = have_ipv6(netcontext->app_mark, netcontext->uid,
1402                                        isMdnsResolution(res.flags));
1403                 query_ipv4 = have_ipv4(netcontext->app_mark, netcontext->uid);
1404             }
1405             if (query_ipv6) {
1406                 q.qtype = T_AAAA;
1407                 if (query_ipv4) {
1408                     q.next = &q2;
1409                     q2.name = name;
1410                     q2.qclass = C_IN;
1411                     q2.qtype = T_A;
1412                 }
1413             } else if (query_ipv4) {
1414                 q.qtype = T_A;
1415             } else {
1416                 return EAI_NODATA;
1417             }
1418             break;
1419         }
1420         case AF_INET:
1421             q.name = name;
1422             q.qclass = C_IN;
1423             q.qtype = T_A;
1424             break;
1425         case AF_INET6:
1426             q.name = name;
1427             q.qclass = C_IN;
1428             q.qtype = T_AAAA;
1429             break;
1430         default:
1431             return EAI_FAMILY;
1432     }
1433 
1434     int he;
1435     if (res_searchN(name, &q, &res, &he) < 0) {
1436         // Return h_errno (he) to catch more detailed errors rather than EAI_NODATA.
1437         // Note that res_searchN() doesn't set the pair NETDB_INTERNAL and errno.
1438         // See also herrnoToAiErrno().
1439         return herrnoToAiErrno(he);
1440     }
1441 
1442     addrinfo sentinel = {};
1443     addrinfo* cur = &sentinel;
1444     addrinfo* ai = getanswer(q.answer, q.n, q.name, q.qtype, pai, &he);
1445     if (ai) {
1446         cur->ai_next = ai;
1447         while (cur && cur->ai_next) cur = cur->ai_next;
1448     }
1449     if (q.next) {
1450         ai = getanswer(q2.answer, q2.n, q2.name, q2.qtype, pai, &he);
1451         if (ai) cur->ai_next = ai;
1452     }
1453     if (sentinel.ai_next == NULL) {
1454         // Note that getanswer() doesn't set the pair NETDB_INTERNAL and errno.
1455         // See also herrnoToAiErrno().
1456         return herrnoToAiErrno(he);
1457     }
1458 
1459     resolv_rfc6724_sort(&sentinel, netcontext->app_mark, netcontext->uid);
1460 
1461     *rv = sentinel.ai_next;
1462     return 0;
1463 }
1464 
_sethtent(FILE ** hostf)1465 static void _sethtent(FILE** hostf) {
1466     if (!*hostf)
1467         *hostf = fopen(_PATH_HOSTS, "re");
1468     else
1469         rewind(*hostf);
1470 }
1471 
_endhtent(FILE ** hostf)1472 static void _endhtent(FILE** hostf) {
1473     if (*hostf) {
1474         (void) fclose(*hostf);
1475         *hostf = NULL;
1476     }
1477 }
1478 
_gethtent(FILE ** hostf,const char * name,const struct addrinfo * pai)1479 static struct addrinfo* _gethtent(FILE** hostf, const char* name, const struct addrinfo* pai) {
1480     char* p;
1481     char *cp, *tname, *cname;
1482     struct addrinfo *res0, *res;
1483     int error;
1484     const char* addr;
1485     char hostbuf[8 * 1024];
1486 
1487     assert(name != NULL);
1488     assert(pai != NULL);
1489 
1490     if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "re"))) return (NULL);
1491 again:
1492     if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf))) return (NULL);
1493     if (*p == '#') goto again;
1494     if (!(cp = strpbrk(p, "#\n"))) goto again;
1495     *cp = '\0';
1496     if (!(cp = strpbrk(p, " \t"))) goto again;
1497     *cp++ = '\0';
1498     addr = p;
1499     /* if this is not something we're looking for, skip it. */
1500     cname = NULL;
1501     while (cp && *cp) {
1502         if (*cp == ' ' || *cp == '\t') {
1503             cp++;
1504             continue;
1505         }
1506         if (!cname) cname = cp;
1507         tname = cp;
1508         if ((cp = strpbrk(cp, " \t")) != NULL) *cp++ = '\0';
1509         if (strcasecmp(name, tname) == 0) goto found;
1510     }
1511     goto again;
1512 
1513 found:
1514     error = getaddrinfo_numeric(addr, nullptr, *pai, &res0);
1515     if (error) goto again;
1516     for (res = res0; res; res = res->ai_next) {
1517         /* cover it up */
1518         res->ai_flags = pai->ai_flags;
1519 
1520         if (pai->ai_flags & AI_CANONNAME) {
1521             if (get_canonname(pai, res, cname) != 0) {
1522                 freeaddrinfo(res0);
1523                 goto again;
1524             }
1525         }
1526     }
1527     return res0;
1528 }
1529 
getCustomHosts(const size_t netid,const char * _Nonnull name,const struct addrinfo * _Nonnull pai)1530 static struct addrinfo* getCustomHosts(const size_t netid, const char* _Nonnull name,
1531                                        const struct addrinfo* _Nonnull pai) {
1532     struct addrinfo sentinel = {};
1533     struct addrinfo *res0, *res;
1534     res = &sentinel;
1535     std::vector<std::string> hosts = getCustomizedTableByName(netid, name);
1536     for (const std::string& host : hosts) {
1537         int error = getaddrinfo_numeric(host.c_str(), nullptr, *pai, &res0);
1538         if (!error && res0 != nullptr) {
1539             res->ai_next = res0;
1540             res = res0;
1541             res0 = nullptr;
1542         }
1543     }
1544     return sentinel.ai_next;
1545 }
1546 
files_getaddrinfo(const size_t netid,const char * name,const addrinfo * pai,addrinfo ** res)1547 static bool files_getaddrinfo(const size_t netid, const char* name, const addrinfo* pai,
1548                               addrinfo** res) {
1549     struct addrinfo sentinel = {};
1550     struct addrinfo *p, *cur;
1551     FILE* hostf = nullptr;
1552 
1553     cur = &sentinel;
1554     _sethtent(&hostf);
1555     while ((p = _gethtent(&hostf, name, pai)) != nullptr) {
1556         cur->ai_next = p;
1557         while (cur && cur->ai_next) cur = cur->ai_next;
1558     }
1559     _endhtent(&hostf);
1560 
1561     if ((p = getCustomHosts(netid, name, pai)) != nullptr) {
1562         cur->ai_next = p;
1563     }
1564 
1565     *res = sentinel.ai_next;
1566     return sentinel.ai_next != nullptr;
1567 }
1568 
1569 /* resolver logic */
1570 
1571 namespace {
1572 
1573 constexpr int SLEEP_TIME_MS = 2;
1574 
getHerrnoFromRcode(int rcode)1575 int getHerrnoFromRcode(int rcode) {
1576     switch (rcode) {
1577         // Not defined in RFC.
1578         case RCODE_TIMEOUT:
1579             // DNS metrics monitors DNS query timeout.
1580             return NETD_RESOLV_H_ERRNO_EXT_TIMEOUT;  // extended h_errno.
1581         // Defined in RFC 1035 section 4.1.1.
1582         case NXDOMAIN:
1583             return HOST_NOT_FOUND;
1584         case SERVFAIL:
1585             return TRY_AGAIN;
1586         case NOERROR:
1587             return NO_DATA;
1588         case FORMERR:
1589         case NOTIMP:
1590         case REFUSED:
1591         default:
1592             return NO_RECOVERY;
1593     }
1594 }
1595 
1596 struct QueryResult {
1597     int ancount;
1598     int rcode;
1599     int herrno;
1600     int qerrno;
1601     NetworkDnsEventReported event;
1602 };
1603 
1604 // Formulate a normal query, send, and await answer.
1605 // Caller must parse answer and determine whether it answers the question.
doQuery(const char * name,res_target * t,ResState * res,std::chrono::milliseconds sleepTimeMs)1606 QueryResult doQuery(const char* name, res_target* t, ResState* res,
1607                     std::chrono::milliseconds sleepTimeMs) {
1608     HEADER* hp = (HEADER*)(void*)t->answer.data();
1609 
1610     hp->rcode = NOERROR;  // default
1611 
1612     const int cl = t->qclass;
1613     const int type = t->qtype;
1614     const int anslen = t->answer.size();
1615 
1616     LOG(DEBUG) << __func__ << ": (" << cl << ", " << type << ")";
1617 
1618     uint8_t buf[MAXPACKET];
1619     int n = res_nmkquery(QUERY, name, cl, type, {}, buf, res->netcontext_flags);
1620 
1621     if (n > 0 &&
1622         (res->netcontext_flags & (NET_CONTEXT_FLAG_USE_DNS_OVER_TLS | NET_CONTEXT_FLAG_USE_EDNS))) {
1623         n = res_nopt(res, n, buf, anslen);
1624     }
1625 
1626     NetworkDnsEventReported event;
1627     if (n <= 0) {
1628         LOG(ERROR) << __func__ << ": res_nmkquery failed";
1629         return {
1630                 .ancount = 0,
1631                 .rcode = -1,
1632                 .herrno = NO_RECOVERY,
1633                 .qerrno = errno,
1634                 .event = event,
1635         };
1636     }
1637 
1638     ResState res_temp = res->clone(&event);
1639 
1640     int rcode = NOERROR;
1641     n = res_nsend(&res_temp, std::span(buf, n), std::span(t->answer.data(), anslen), &rcode, 0,
1642                   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, std::span(buf, n), std::span(t->answer.data(), anslen), &rcode,
1652                           0);
1653         }
1654     }
1655 
1656     LOG(INFO) << __func__ << ": rcode=" << rcode << ", ancount=" << ntohs(hp->ancount)
1657               << ", return value=" << n;
1658 
1659     t->n = n;
1660     return {
1661             .ancount = ntohs(hp->ancount),
1662             .rcode = rcode,
1663             .qerrno = errno,
1664             .event = event,
1665     };
1666 }
1667 
1668 }  // namespace
1669 
1670 // This function runs doQuery() for each res_target in parallel.
1671 // 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)1672 static int res_queryN_parallel(const char* name, res_target* target, ResState* res, int* herrno) {
1673     std::vector<std::future<QueryResult>> results;
1674     results.reserve(2);
1675     std::chrono::milliseconds sleepTimeMs{};
1676     for (res_target* t = target; t; t = t->next) {
1677         results.emplace_back(std::async(std::launch::async, doQuery, name, t, res, sleepTimeMs));
1678         // Avoiding gateways drop packets if queries are sent too close together
1679         // Only needed if we have multiple queries in a row.
1680         if (t->next) {
1681             int sleepFlag = Experiments::getInstance()->getFlag("parallel_lookup_sleep_time",
1682                                                                 SLEEP_TIME_MS);
1683             if (sleepFlag > 1000) sleepFlag = 1000;
1684             sleepTimeMs = std::chrono::milliseconds(sleepFlag);
1685         }
1686     }
1687 
1688     int ancount = 0;
1689     int rcode = 0;
1690 
1691     for (auto& f : results) {
1692         const QueryResult& r = f.get();
1693         if (r.herrno == NO_RECOVERY) {
1694             *herrno = r.herrno;
1695             return -1;
1696         }
1697         res->event->MergeFrom(r.event);
1698         ancount += r.ancount;
1699         rcode = r.rcode;
1700         errno = r.qerrno;
1701     }
1702 
1703     if (ancount == 0) {
1704         *herrno = getHerrnoFromRcode(rcode);
1705         return -1;
1706     }
1707 
1708     return ancount;
1709 }
1710 
1711 /*
1712  * Formulate a normal query, send, and retrieve answer in supplied buffer.
1713  * Return the size of the response on success, -1 on error.
1714  * If enabled, implement search rules until answer or unrecoverable failure
1715  * is detected.  Error code, if any, is left in *herrno.
1716  */
res_searchN(const char * name,res_target * target,ResState * res,int * herrno)1717 static int res_searchN(const char* name, res_target* target, ResState* res, int* herrno) {
1718     const char* cp;
1719     HEADER* hp;
1720     uint32_t dots;
1721     int ret, saved_herrno;
1722     int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
1723 
1724     assert(name != NULL);
1725     assert(target != NULL);
1726 
1727     hp = (HEADER*)(void*)target->answer.data();
1728 
1729     errno = 0;
1730     *herrno = HOST_NOT_FOUND; /* default, if we never query */
1731     dots = 0;
1732     for (cp = name; *cp; cp++) dots += (*cp == '.');
1733     const bool trailing_dot = (cp > name && *--cp == '.') ? true : false;
1734 
1735     /*
1736      * If there are dots in the name already, let's just give it a try
1737      * 'as is'.  The threshold can be set with the "ndots" option.
1738      */
1739     saved_herrno = -1;
1740     if (dots >= res->ndots) {
1741         ret = res_querydomainN(name, NULL, target, res, herrno);
1742         if (ret > 0) return (ret);
1743         saved_herrno = *herrno;
1744         tried_as_is++;
1745     }
1746 
1747     /*
1748      * We do at least one level of search if
1749      *	 - there is no dot, or
1750      *	 - there is at least one dot and there is no trailing dot.
1751      * - this is not a .local mDNS lookup.
1752      */
1753     if ((!dots || (dots && !trailing_dot)) && !isMdnsResolution(res->flags)) {
1754         /* Unfortunately we need to set stuff up before
1755          * the domain stuff is tried.  Will have a better
1756          * fix after thread pools are used.
1757          */
1758         resolv_populate_res_for_net(res);
1759 
1760         for (const auto& domain : res->search_domains) {
1761             ret = res_querydomainN(name, domain.c_str(), target, res, herrno);
1762             if (ret > 0) return ret;
1763 
1764             /*
1765              * If no server present, give up.
1766              * If name isn't found in this domain,
1767              * keep trying higher domains in the search list
1768              * (if that's enabled).
1769              * On a NO_DATA error, keep trying, otherwise
1770              * a wildcard entry of another type could keep us
1771              * from finding this entry higher in the domain.
1772              * If we get some other error (negative answer or
1773              * server failure), then stop searching up,
1774              * but try the input name below in case it's
1775              * fully-qualified.
1776              */
1777             if (errno == ECONNREFUSED) {
1778                 *herrno = TRY_AGAIN;
1779                 return -1;
1780             }
1781 
1782             switch (*herrno) {
1783                 case NO_DATA:
1784                     got_nodata++;
1785                     [[fallthrough]];
1786                 case HOST_NOT_FOUND:
1787                     /* keep trying */
1788                     break;
1789                 case TRY_AGAIN:
1790                     if (hp->rcode == SERVFAIL) {
1791                         /* try next search element, if any */
1792                         got_servfail++;
1793                     }
1794                     break;
1795             }
1796         }
1797     }
1798 
1799     /*
1800      * if we have not already tried the name "as is", do that now.
1801      * note that we do this regardless of how many dots were in the
1802      * name or whether it ends with a dot.
1803      */
1804     if (!tried_as_is) {
1805         ret = res_querydomainN(name, NULL, target, res, herrno);
1806         if (ret > 0) return ret;
1807     }
1808 
1809     /*
1810      * if we got here, we didn't satisfy the search.
1811      * if we did an initial full query, return that query's h_errno
1812      * (note that we wouldn't be here if that query had succeeded).
1813      * else if we ever got a nodata, send that back as the reason.
1814      * else send back meaningless h_errno, that being the one from
1815      * the last DNSRCH we did.
1816      */
1817     if (saved_herrno != -1)
1818         *herrno = saved_herrno;
1819     else if (got_nodata)
1820         *herrno = NO_DATA;
1821     else if (got_servfail)
1822         *herrno = TRY_AGAIN;
1823     return -1;
1824 }
1825 
1826 // Perform a call on res_query on the concatenation of name and domain,
1827 // 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)1828 static int res_querydomainN(const char* name, const char* domain, res_target* target, ResState* res,
1829                             int* herrno) {
1830     char nbuf[MAXDNAME];
1831     const char* longname = nbuf;
1832     size_t n, d;
1833 
1834     assert(name != NULL);
1835 
1836     if (domain == NULL) {
1837         // Check for trailing '.'; copy without '.' if present.
1838         n = strlen(name);
1839         if (n + 1 > sizeof(nbuf)) {
1840             *herrno = NO_RECOVERY;
1841             return -1;
1842         }
1843         if (n > 0 && name[--n] == '.') {
1844             strncpy(nbuf, name, n);
1845             nbuf[n] = '\0';
1846         } else
1847             longname = name;
1848     } else {
1849         n = strlen(name);
1850         d = strlen(domain);
1851         if (n + 1 + d + 1 > sizeof(nbuf)) {
1852             *herrno = NO_RECOVERY;
1853             return -1;
1854         }
1855         snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
1856     }
1857     return res_queryN_parallel(longname, target, res, herrno);
1858 }
1859