1 /*	$NetBSD: gethnamaddr.c,v 1.91 2014/06/19 15:08:18 christos Exp $	*/
2 
3 /*
4  * ++Copyright++ 1985, 1988, 1993
5  * -
6  * Copyright (c) 1985, 1988, 1993
7  *    The Regents of the University of California.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  * -
33  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
34  *
35  * Permission to use, copy, modify, and distribute this software for any
36  * purpose with or without fee is hereby granted, provided that the above
37  * copyright notice and this permission notice appear in all copies, and that
38  * the name of Digital Equipment Corporation not be used in advertising or
39  * publicity pertaining to distribution of the document or software without
40  * specific, written prior permission.
41  *
42  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
43  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
44  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
45  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
46  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
47  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
48  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
49  * SOFTWARE.
50  * -
51  * --Copyright--
52  */
53 
54 #define LOG_TAG "resolv"
55 
56 #include "gethnamaddr.h"
57 
58 #include <android-base/logging.h>
59 #include <arpa/inet.h>
60 #include <arpa/nameser.h>
61 #include <assert.h>
62 #include <ctype.h>
63 #include <errno.h>
64 #include <netdb.h>
65 #include <netinet/in.h>
66 #include <stdarg.h>
67 #include <stdbool.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <sys/param.h>
71 #include <sys/socket.h>
72 #include <sys/un.h>
73 #include <unistd.h>
74 #include <functional>
75 #include <vector>
76 
77 #include "Experiments.h"
78 #include "hostent.h"
79 #include "netd_resolv/resolv.h"
80 #include "res_comp.h"
81 #include "res_debug.h"  // p_class(), p_type()
82 #include "resolv_cache.h"
83 #include "resolv_private.h"
84 #include "stats.pb.h"
85 
86 using android::net::NetworkDnsEventReported;
87 
88 constexpr int MAXADDRS = 35;
89 
90 typedef union {
91     HEADER hdr;
92     uint8_t buf[MAXPACKET];
93 } querybuf;
94 
95 static void pad_v4v6_hostent(struct hostent* hp, char** bpp, char* ep);
96 static int dns_gethtbyaddr(const unsigned char* uaddr, int len, int af,
97                            const android_net_context* netcontext, getnamaddr* info,
98                            NetworkDnsEventReported* event);
99 static int dns_gethtbyname(ResState* res, const char* name, int af, getnamaddr* info);
100 
101 #define BOUNDED_INCR(x)      \
102     do {                     \
103         BOUNDS_CHECK(cp, x); \
104         cp += (x);           \
105     } while (0)
106 
107 #define BOUNDS_CHECK(ptr, count)                     \
108     do {                                             \
109         if (eom - (ptr) < (count)) goto no_recovery; \
110     } while (0)
111 
getanswer(const querybuf * _Nonnull answer,int anslen,const char * qname,int qtype,struct hostent * hent,char * buf,size_t buflen,int * he)112 static struct hostent* getanswer(const querybuf* _Nonnull answer, int anslen, const char* qname,
113                                  int qtype, struct hostent* hent, char* buf, size_t buflen,
114                                  int* he) {
115     const HEADER* hp;
116     const uint8_t* cp;
117     int n;
118     size_t qlen;
119     const uint8_t *eom, *erdata;
120     char *bp, **hap, *ep;
121     int ancount, qdcount;
122     int haveanswer, had_error;
123     int toobig = 0;
124     char tbuf[MAXDNAME];
125     char* addr_ptrs[MAXADDRS];
126     const char* tname;
127     std::vector<char*> aliases;
128 
129     tname = qname;
130     hent->h_name = NULL;
131     eom = answer->buf + anslen;
132 
133     bool (*name_ok)(const char* dn);
134     switch (qtype) {
135         case T_A:
136         case T_AAAA:
137             name_ok = res_hnok;
138             break;
139         case T_PTR:
140             name_ok = res_dnok;
141             break;
142         default:
143             *he = NO_RECOVERY;
144             return NULL; /* XXX should be abort(); */
145     }
146 
147     /*
148      * find first satisfactory answer
149      */
150     hp = &answer->hdr;
151     ancount = ntohs(hp->ancount);
152     qdcount = ntohs(hp->qdcount);
153     bp = buf;
154     ep = buf + buflen;
155     cp = answer->buf;
156     BOUNDED_INCR(HFIXEDSZ);
157     if (qdcount != 1) goto no_recovery;
158 
159     n = dn_expand(answer->buf, eom, cp, bp, (int) (ep - bp));
160     if ((n < 0) || !name_ok(bp)) goto no_recovery;
161 
162     BOUNDED_INCR(n + QFIXEDSZ);
163     if (qtype == T_A || qtype == T_AAAA) {
164         /* res_send() has already verified that the query name is the
165          * same as the one we sent; this just gets the expanded name
166          * (i.e., with the succeeding search-domain tacked on).
167          */
168         n = (int) strlen(bp) + 1; /* for the \0 */
169         if (n >= MAXHOSTNAMELEN) goto no_recovery;
170         hent->h_name = bp;
171         bp += n;
172         /* The qname can be abbreviated, but h_name is now absolute. */
173         qname = hent->h_name;
174     }
175     hent->h_addr_list = hap = addr_ptrs;
176     *hap = NULL;
177     haveanswer = 0;
178     had_error = 0;
179     while (ancount-- > 0 && cp < eom && !had_error) {
180         n = dn_expand(answer->buf, eom, cp, bp, (int) (ep - bp));
181         if ((n < 0) || !name_ok(bp)) {
182             had_error++;
183             continue;
184         }
185         cp += n; /* name */
186         BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
187         int type = ntohs(*reinterpret_cast<const uint16_t*>(cp));
188         cp += INT16SZ; /* type */
189         int cl = ntohs(*reinterpret_cast<const uint16_t*>(cp));
190         cp += INT16SZ + INT32SZ; /* class, TTL */
191         n = ntohs(*reinterpret_cast<const uint16_t*>(cp));
192         cp += INT16SZ; /* len */
193         BOUNDS_CHECK(cp, n);
194         erdata = cp + n;
195         if (cl != C_IN) {
196             /* XXX - debug? syslog? */
197             cp += n;
198             continue; /* XXX - had_error++ ? */
199         }
200         if ((qtype == T_A || qtype == T_AAAA) && type == T_CNAME) {
201             n = dn_expand(answer->buf, eom, cp, tbuf, (int) sizeof tbuf);
202             if ((n < 0) || !name_ok(tbuf)) {
203                 had_error++;
204                 continue;
205             }
206             cp += n;
207             if (cp != erdata) goto no_recovery;
208             /* Store alias. */
209             aliases.push_back(bp);
210             n = (int) strlen(bp) + 1; /* for the \0 */
211             if (n >= MAXHOSTNAMELEN) {
212                 had_error++;
213                 continue;
214             }
215             bp += n;
216             /* Get canonical name. */
217             n = (int) strlen(tbuf) + 1; /* for the \0 */
218             if (n > ep - bp || n >= MAXHOSTNAMELEN) {
219                 had_error++;
220                 continue;
221             }
222             strlcpy(bp, tbuf, (size_t)(ep - bp));
223             hent->h_name = bp;
224             bp += n;
225             continue;
226         }
227         if (qtype == T_PTR && type == T_CNAME) {
228             n = dn_expand(answer->buf, eom, cp, tbuf, (int) sizeof tbuf);
229             if (n < 0 || !res_dnok(tbuf)) {
230                 had_error++;
231                 continue;
232             }
233             cp += n;
234             if (cp != erdata) goto no_recovery;
235             /* Get canonical name. */
236             n = (int) strlen(tbuf) + 1; /* for the \0 */
237             if (n > ep - bp || n >= MAXHOSTNAMELEN) {
238                 had_error++;
239                 continue;
240             }
241             strlcpy(bp, tbuf, (size_t)(ep - bp));
242             tname = bp;
243             bp += n;
244             continue;
245         }
246         if (type != qtype) {
247             if (type != T_KEY && type != T_SIG)
248                 LOG(DEBUG) << __func__ << ": asked for \"" << qname << " " << p_class(C_IN) << " "
249                            << p_type(qtype) << "\", got type \"" << p_type(type) << "\"";
250             cp += n;
251             continue; /* XXX - had_error++ ? */
252         }
253         switch (type) {
254             case T_PTR:
255                 if (strcasecmp(tname, bp) != 0) {
256                     LOG(DEBUG) << __func__ << ": asked for \"" << qname << "\", got \"" << bp
257                                << "\"";
258                     cp += n;
259                     continue; /* XXX - had_error++ ? */
260                 }
261                 n = dn_expand(answer->buf, eom, cp, bp, (int) (ep - bp));
262                 if ((n < 0) || !res_hnok(bp)) {
263                     had_error++;
264                     break;
265                 }
266                 cp += n;
267                 if (cp != erdata) goto no_recovery;
268                 if (!haveanswer)
269                     hent->h_name = bp;
270                 else
271                     aliases.push_back(bp);
272                 if (n != -1) {
273                     n = (int) strlen(bp) + 1; /* for the \0 */
274                     if (n >= MAXHOSTNAMELEN) {
275                         had_error++;
276                         break;
277                     }
278                     bp += n;
279                 }
280                 break;
281             case T_A:
282             case T_AAAA: {
283                 if (hent->h_name == NULL) goto no_recovery;
284                 const char* h_name = hent->h_name;
285                 if (strcasecmp(h_name, bp) != 0) {
286                     LOG(DEBUG) << __func__ << ": asked for \"" << h_name << "\", got \"" << bp
287                                << "\"";
288                     cp += n;
289                     continue; /* XXX - had_error++ ? */
290                 }
291                 if (n != hent->h_length) {
292                     cp += n;
293                     continue;
294                 }
295                 if (type == T_AAAA) {
296                     struct in6_addr in6;
297                     memcpy(&in6, cp, NS_IN6ADDRSZ);
298                     if (IN6_IS_ADDR_V4MAPPED(&in6)) {
299                         cp += n;
300                         continue;
301                     }
302                 }
303                 if (!haveanswer) {
304                     int nn;
305 
306                     hent->h_name = bp;
307                     nn = (int) strlen(bp) + 1; /* for the \0 */
308                     bp += nn;
309                 }
310 
311                 bp = align_ptr<sizeof(int32_t)>(bp);
312 
313                 if (bp + n >= ep) {
314                     LOG(DEBUG) << __func__ << ": size (" << n << ") too big";
315                     had_error++;
316                     continue;
317                 }
318                 if (hap >= &addr_ptrs[MAXADDRS - 1]) {
319                     if (!toobig++) {
320                         LOG(DEBUG) << __func__ << ": Too many addresses (" << MAXADDRS << ")";
321                     }
322                     cp += n;
323                     continue;
324                 }
325                 (void) memcpy(*hap++ = bp, cp, (size_t) n);
326                 bp += n;
327                 cp += n;
328                 if (cp != erdata) goto no_recovery;
329                 break;
330             }
331             default:
332                 abort();
333         }
334         if (!had_error) haveanswer++;
335     }
336     if (haveanswer) {
337         *hap = NULL;
338         if (!hent->h_name) {
339             n = (int) strlen(qname) + 1; /* for the \0 */
340             if (n > ep - bp || n >= MAXHOSTNAMELEN) goto no_recovery;
341             strlcpy(bp, qname, (size_t)(ep - bp));
342             hent->h_name = bp;
343             bp += n;
344         }
345         if (hent->h_addrtype == AF_INET) pad_v4v6_hostent(hent, &bp, ep);
346         goto success;
347     }
348 no_recovery:
349     *he = NO_RECOVERY;
350     return NULL;
351 success:
352     bp = align_ptr(bp);
353     aliases.push_back(nullptr);
354     qlen = aliases.size() * sizeof(*hent->h_aliases);
355     if ((size_t)(ep - bp) < qlen) goto nospc;
356     hent->h_aliases = (char**) bp;
357     memcpy(bp, aliases.data(), qlen);
358 
359     bp += qlen;
360     n = (int) (hap - addr_ptrs);
361     qlen = (n + 1) * sizeof(*hent->h_addr_list);
362     if ((size_t)(ep - bp) < qlen) goto nospc;
363     hent->h_addr_list = (char**) bp;
364     memcpy(bp, addr_ptrs, qlen);
365     *he = NETDB_SUCCESS;
366     return hent;
367 nospc:
368     errno = ENOSPC;
369     *he = NETDB_INTERNAL;
370     return NULL;
371 }
372 
resolv_gethostbyname(const char * name,int af,hostent * hp,char * buf,size_t buflen,const android_net_context * netcontext,hostent ** result,NetworkDnsEventReported * event)373 int resolv_gethostbyname(const char* name, int af, hostent* hp, char* buf, size_t buflen,
374                          const android_net_context* netcontext, hostent** result,
375                          NetworkDnsEventReported* event) {
376     if (name == nullptr || hp == nullptr) {
377         return EAI_SYSTEM;
378     }
379 
380     getnamaddr info;
381     ResState res(netcontext, event);
382 
383     setMdnsFlag(name, res.netid, &(res.flags));
384 
385     size_t size;
386     switch (af) {
387         case AF_INET:
388             size = NS_INADDRSZ;
389             break;
390         case AF_INET6:
391             size = NS_IN6ADDRSZ;
392             break;
393         default:
394             return EAI_FAMILY;
395     }
396     if (buflen < size) goto nospc;
397 
398     hp->h_addrtype = af;
399     hp->h_length = (int) size;
400 
401     /*
402      * disallow names consisting only of digits/dots, unless
403      * they end in a dot.
404      */
405     if (isdigit((uint8_t)name[0])) {
406         for (const char* cp = name;; ++cp) {
407             if (!*cp) {
408                 if (*--cp == '.') break;
409                 /*
410                  * All-numeric, no dot at the end.
411                  * Fake up a hostent as if we'd actually
412                  * done a lookup.
413                  */
414                 goto fake;
415             }
416             if (!isdigit((uint8_t)*cp) && *cp != '.') break;
417         }
418     }
419     if ((isxdigit((uint8_t)name[0]) && strchr(name, ':') != NULL) || name[0] == ':') {
420         for (const char* cp = name;; ++cp) {
421             if (!*cp) {
422                 if (*--cp == '.') break;
423                 /*
424                  * All-IPv6-legal, no dot at the end.
425                  * Fake up a hostent as if we'd actually
426                  * done a lookup.
427                  */
428                 goto fake;
429             }
430             if (!isxdigit((uint8_t)*cp) && *cp != ':' && *cp != '.') break;
431         }
432     }
433 
434     info.hp = hp;
435     info.buf = buf;
436     info.buflen = buflen;
437     if (_hf_gethtbyname2(name, af, &info)) {
438         int error = dns_gethtbyname(&res, name, af, &info);
439         if (error != 0) return error;
440     }
441     *result = hp;
442     return 0;
443 nospc:
444     return EAI_MEMORY;
445 fake:
446     HENT_ARRAY(hp->h_addr_list, 1, buf, buflen);
447     HENT_ARRAY(hp->h_aliases, 0, buf, buflen);
448 
449     hp->h_aliases[0] = NULL;
450     if (size > buflen) goto nospc;
451 
452     if (inet_pton(af, name, buf) <= 0) {
453         return EAI_NODATA;
454     }
455     hp->h_addr_list[0] = buf;
456     hp->h_addr_list[1] = NULL;
457     buf += size;
458     buflen -= size;
459     HENT_SCOPY(hp->h_name, name, buf, buflen);
460     *result = hp;
461     return 0;
462 }
463 
resolv_gethostbyaddr(const void * _Nonnull addr,socklen_t len,int af,hostent * hp,char * buf,size_t buflen,const struct android_net_context * netcontext,hostent ** result,NetworkDnsEventReported * event)464 int resolv_gethostbyaddr(const void* _Nonnull addr, socklen_t len, int af, hostent* hp, char* buf,
465                          size_t buflen, const struct android_net_context* netcontext,
466                          hostent** result, NetworkDnsEventReported* event) {
467     const uint8_t* uaddr = (const uint8_t*)addr;
468     socklen_t size;
469     struct getnamaddr info;
470 
471     if (af == AF_INET6 && len == NS_IN6ADDRSZ &&
472         (IN6_IS_ADDR_LINKLOCAL((const struct in6_addr*) addr) ||
473          IN6_IS_ADDR_SITELOCAL((const struct in6_addr*) addr))) {
474         return EAI_NODATA;
475     }
476     if (af == AF_INET6 && len == NS_IN6ADDRSZ &&
477         (IN6_IS_ADDR_V4MAPPED((const struct in6_addr*) addr) ||
478          IN6_IS_ADDR_V4COMPAT((const struct in6_addr*) addr))) {
479         /* Unmap. */
480         uaddr += NS_IN6ADDRSZ - NS_INADDRSZ;
481         addr = uaddr;
482         af = AF_INET;
483         len = NS_INADDRSZ;
484     }
485     switch (af) {
486         case AF_INET:
487             size = NS_INADDRSZ;
488             break;
489         case AF_INET6:
490             size = NS_IN6ADDRSZ;
491             break;
492         default:
493             return EAI_FAMILY;
494     }
495     if (size != len) {
496         // TODO: Consider converting to a private extended EAI_* error code.
497         // Currently, the EAI_* value has no corresponding error code for invalid argument socket
498         // length. In order to not rely on errno, convert the original error code pair, EAI_SYSTEM
499         // and EINVAL, to EAI_FAIL.
500         return EAI_FAIL;
501     }
502     info.hp = hp;
503     info.buf = buf;
504     info.buflen = buflen;
505     if (_hf_gethtbyaddr(uaddr, len, af, &info)) {
506         int error = dns_gethtbyaddr(uaddr, len, af, netcontext, &info, event);
507         if (error != 0) return error;
508     }
509     *result = hp;
510     return 0;
511 }
512 
513 // TODO: Consider leaving function without returning error code as _gethtent() does because
514 // the error code of the caller does not currently return to netd.
netbsd_gethostent_r(FILE * hf,struct hostent * hent,char * buf,size_t buflen,int * he)515 struct hostent* netbsd_gethostent_r(FILE* hf, struct hostent* hent, char* buf, size_t buflen,
516                                     int* he) {
517     char *name;
518     char* cp;
519     int af, len;
520     size_t anum;
521     struct in6_addr host_addr;
522     std::vector<char*> aliases;
523 
524     if (hf == NULL) {
525         *he = NETDB_INTERNAL;
526         errno = EINVAL;
527         return NULL;
528     }
529     char* p = NULL;
530 
531     // Allocate a new space to read file lines like upstream does.
532     const size_t line_buf_size = MAXPACKET;
533     if ((p = (char*) malloc(line_buf_size)) == NULL) {
534         goto nospc;
535     }
536     for (;;) {
537         if (!fgets(p, line_buf_size, hf)) {
538             free(p);
539             *he = HOST_NOT_FOUND;
540             return NULL;
541         }
542         if (*p == '#') {
543             continue;
544         }
545         if (!(cp = strpbrk(p, "#\n"))) {
546             continue;
547         }
548         *cp = '\0';
549         if (!(cp = strpbrk(p, " \t"))) continue;
550         *cp++ = '\0';
551         if (inet_pton(AF_INET6, p, &host_addr) > 0) {
552             af = AF_INET6;
553             len = NS_IN6ADDRSZ;
554         } else {
555             if (inet_pton(AF_INET, p, &host_addr) <= 0) continue;
556             af = AF_INET;
557             len = NS_INADDRSZ;
558         }
559 
560         /* if this is not something we're looking for, skip it. */
561         if (hent->h_addrtype != 0 && hent->h_addrtype != af) continue;
562         if (hent->h_length != 0 && hent->h_length != len) continue;
563 
564         while (*cp == ' ' || *cp == '\t') cp++;
565         if ((cp = strpbrk(name = cp, " \t")) != NULL) *cp++ = '\0';
566         while (cp && *cp) {
567             if (*cp == ' ' || *cp == '\t') {
568                 cp++;
569                 continue;
570             }
571             aliases.push_back(cp);
572             if ((cp = strpbrk(cp, " \t")) != NULL) *cp++ = '\0';
573         }
574         break;
575     }
576     hent->h_length = len;
577     hent->h_addrtype = af;
578     HENT_ARRAY(hent->h_addr_list, 1, buf, buflen);
579     anum = aliases.size();
580     HENT_ARRAY(hent->h_aliases, anum, buf, buflen);
581     HENT_COPY(hent->h_addr_list[0], &host_addr, hent->h_length, buf, buflen);
582     hent->h_addr_list[1] = NULL;
583 
584     /* Reserve space for mapping IPv4 address to IPv6 address in place */
585     if (hent->h_addrtype == AF_INET) {
586         HENT_COPY(buf, NAT64_PAD, sizeof(NAT64_PAD), buf, buflen);
587     }
588 
589     HENT_SCOPY(hent->h_name, name, buf, buflen);
590     for (size_t i = 0; i < anum; i++) HENT_SCOPY(hent->h_aliases[i], aliases[i], buf, buflen);
591     hent->h_aliases[anum] = NULL;
592     *he = NETDB_SUCCESS;
593     free(p);
594     return hent;
595 nospc:
596     free(p);
597     errno = ENOSPC;
598     *he = NETDB_INTERNAL;
599     return NULL;
600 }
601 
602 /* Reserve space for mapping IPv4 address to IPv6 address in place */
pad_v4v6_hostent(struct hostent * _Nonnull hp,char ** _Nonnull bpp,char * _Nonnull ep)603 static void pad_v4v6_hostent(struct hostent* _Nonnull hp, char** _Nonnull bpp, char* _Nonnull ep) {
604     if (hp->h_addrtype != AF_INET || hp->h_length != NS_INADDRSZ) return;
605     for (char** ap = hp->h_addr_list; *ap; ap++) {
606         char* const bp = align_ptr<sizeof(int32_t)>(*bpp);
607 
608         if (ep - bp < NS_IN6ADDRSZ) {
609             // Out of space.  Truncate address list here.
610             *ap = nullptr;
611             return;
612         }
613         memcpy(bp, *ap, NS_INADDRSZ);
614         memcpy(bp + NS_INADDRSZ, NAT64_PAD, sizeof(NAT64_PAD));
615         *ap = bp;
616         *bpp = bp + NS_IN6ADDRSZ;
617     }
618 }
619 
dns_gethtbyname(ResState * res,const char * name,int addr_type,getnamaddr * info)620 static int dns_gethtbyname(ResState* res, const char* name, int addr_type, getnamaddr* info) {
621     int n, type;
622     info->hp->h_addrtype = addr_type;
623 
624     switch (info->hp->h_addrtype) {
625         case AF_INET:
626             info->hp->h_length = NS_INADDRSZ;
627             type = T_A;
628             break;
629         case AF_INET6:
630             info->hp->h_length = NS_IN6ADDRSZ;
631             type = T_AAAA;
632             break;
633         default:
634             return EAI_FAMILY;
635     }
636     auto buf = std::make_unique<querybuf>();
637 
638     int he;
639     n = res_nsearch(res, name, C_IN, type, {buf->buf, (int)sizeof(buf->buf)}, &he);
640     if (n < 0) {
641         LOG(DEBUG) << __func__ << ": res_nsearch failed (" << n << ")";
642         // Return h_errno (he) to catch more detailed errors rather than EAI_NODATA.
643         // Note that res_nsearch() doesn't set the pair NETDB_INTERNAL and errno.
644         // See also herrnoToAiErrno().
645         return herrnoToAiErrno(he);
646     }
647     hostent* hp = getanswer(buf.get(), n, name, type, info->hp, info->buf, info->buflen, &he);
648     if (hp == NULL) return herrnoToAiErrno(he);
649 
650     return 0;
651 }
652 
dns_gethtbyaddr(const unsigned char * uaddr,int len,int af,const android_net_context * netcontext,getnamaddr * info,NetworkDnsEventReported * event)653 static int dns_gethtbyaddr(const unsigned char* uaddr, int len, int af,
654                            const android_net_context* netcontext, getnamaddr* info,
655                            NetworkDnsEventReported* event) {
656     char qbuf[MAXDNAME + 1], *qp, *ep;
657     int n;
658     int advance;
659 
660     info->hp->h_length = len;
661     info->hp->h_addrtype = af;
662 
663     switch (info->hp->h_addrtype) {
664         case AF_INET:
665             (void) snprintf(qbuf, sizeof(qbuf), "%u.%u.%u.%u.in-addr.arpa", (uaddr[3] & 0xff),
666                             (uaddr[2] & 0xff), (uaddr[1] & 0xff), (uaddr[0] & 0xff));
667             break;
668 
669         case AF_INET6:
670             qp = qbuf;
671             ep = qbuf + sizeof(qbuf) - 1;
672             for (n = NS_IN6ADDRSZ - 1; n >= 0; n--) {
673                 advance = snprintf(qp, (size_t)(ep - qp), "%x.%x.", uaddr[n] & 0xf,
674                                    ((unsigned int) uaddr[n] >> 4) & 0xf);
675                 if (advance > 0 && qp + advance < ep)
676                     qp += advance;
677                 else {
678                     // TODO: Consider converting to a private extended EAI_* error code.
679                     // Currently, the EAI_* value has no corresponding error code for an internal
680                     // out of buffer space. In order to not rely on errno, convert the original
681                     // error code EAI_SYSTEM to EAI_MEMORY.
682                     return EAI_MEMORY;
683                 }
684             }
685             if (strlcat(qbuf, "ip6.arpa", sizeof(qbuf)) >= sizeof(qbuf)) {
686                 // TODO: Consider converting to a private extended EAI_* error code.
687                 // Currently, the EAI_* value has no corresponding error code for an internal
688                 // out of buffer space. In order to not rely on errno, convert the original
689                 // error code EAI_SYSTEM to EAI_MEMORY.
690                 return EAI_MEMORY;
691             }
692             break;
693         default:
694             return EAI_FAMILY;
695     }
696 
697     auto buf = std::make_unique<querybuf>();
698 
699     ResState res(netcontext, event);
700     int he;
701     n = res_nquery(&res, qbuf, C_IN, T_PTR, {buf->buf, (int)sizeof(buf->buf)}, &he);
702     if (n < 0) {
703         LOG(DEBUG) << __func__ << ": res_nquery failed (" << n << ")";
704         // Note that res_nquery() doesn't set the pair NETDB_INTERNAL and errno.
705         // Return h_errno (he) to catch more detailed errors rather than EAI_NODATA.
706         // See also herrnoToAiErrno().
707         return herrnoToAiErrno(he);
708     }
709     hostent* hp = getanswer(buf.get(), n, qbuf, T_PTR, info->hp, info->buf, info->buflen, &he);
710     if (hp == NULL) return herrnoToAiErrno(he);
711 
712     char* bf = (char*) (hp->h_addr_list + 2);
713     size_t blen = (size_t)(bf - info->buf);
714     if (blen + info->hp->h_length > info->buflen) goto nospc;
715     hp->h_addr_list[0] = bf;
716     hp->h_addr_list[1] = NULL;
717     memcpy(bf, uaddr, (size_t) info->hp->h_length);
718 
719     /* Reserve enough space for mapping IPv4 address to IPv6 address in place */
720     if (info->hp->h_addrtype == AF_INET) {
721         if (blen + NS_IN6ADDRSZ > info->buflen) goto nospc;
722         // Pad zero to the unused address space
723         memcpy(bf + NS_INADDRSZ, NAT64_PAD, sizeof(NAT64_PAD));
724     }
725 
726     return 0;
727 
728 nospc:
729     return EAI_MEMORY;
730 }
731 
herrnoToAiErrno(int he)732 int herrnoToAiErrno(int he) {
733     switch (he) {
734         // extended h_errno
735         case NETD_RESOLV_H_ERRNO_EXT_TIMEOUT:
736             return NETD_RESOLV_TIMEOUT;
737         // legacy h_errno
738         case NETDB_SUCCESS:
739             return 0;
740         case HOST_NOT_FOUND:  // TODO: Perhaps convert HOST_NOT_FOUND to EAI_NONAME instead
741         case NO_DATA:         // NO_ADDRESS
742             return EAI_NODATA;
743         case TRY_AGAIN:
744             return EAI_AGAIN;
745         case NETDB_INTERNAL:
746             // TODO: Remove ENOSPC and call abort() immediately whenever any allocation fails.
747             if (errno == ENOSPC) return EAI_MEMORY;
748             // Theoretically, this should not happen. Leave this here just in case.
749             // Currently, getanswer() of {gethnamaddr, getaddrinfo}.cpp, res_nsearch() and
750             // res_searchN() use this function to convert error code. Only getanswer()
751             // of gethnamaddr.cpp may return the error code pair, herrno NETDB_INTERNAL and
752             // errno ENOSPC, which has already converted to EAI_MEMORY. The remaining functions
753             // don't set the pair herrno and errno.
754             return EAI_SYSTEM;  // see errno for detail
755         case NO_RECOVERY:
756         default:
757             return EAI_FAIL;  // TODO: Perhaps convert default to EAI_MAX (unknown error) instead
758     }
759 }
760 
setMdnsFlag(std::string_view hostname,unsigned netid,uint32_t * flags)761 void setMdnsFlag(std::string_view hostname, unsigned netid, uint32_t* flags) {
762     if (hostname.ends_with(".local") && is_mdns_supported_network(netid) &&
763         android::net::Experiments::getInstance()->getFlag("mdns_resolution", 1))
764         *flags |= RES_F_MDNS;
765 }
766 
isMdnsResolution(uint32_t flags)767 bool isMdnsResolution(uint32_t flags) {
768     return flags & RES_F_MDNS;
769 }
770