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 #include "gethnamaddr.h"
55 
56 #include <android-base/logging.h>
57 #include <arpa/inet.h>
58 #include <arpa/nameser.h>
59 #include <assert.h>
60 #include <ctype.h>
61 #include <errno.h>
62 #include <netdb.h>
63 #include <netinet/in.h>
64 #include <stdarg.h>
65 #include <stdbool.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <sys/param.h>
69 #include <sys/socket.h>
70 #include <sys/un.h>
71 #include <unistd.h>
72 #include <functional>
73 #include <vector>
74 
75 #include "hostent.h"
76 #include "netd_resolv/resolv.h"
77 #include "res_comp.h"
78 #include "res_debug.h"  // p_class(), p_type()
79 #include "res_init.h"
80 #include "resolv_cache.h"
81 #include "stats.pb.h"
82 
83 using android::net::NetworkDnsEventReported;
84 
85 // NetBSD uses _DIAGASSERT to null-check arguments and the like,
86 // but it's clear from the number of mistakes in their assertions
87 // that they don't actually test or ship with this.
88 #define _DIAGASSERT(e) /* nothing */
89 
90 // TODO: unify macro ALIGNBYTES and ALIGN for all possible data type alignment of hostent
91 // buffer.
92 #define ALIGNBYTES (sizeof(uintptr_t) - 1)
93 #define ALIGN(p) (((uintptr_t)(p) + ALIGNBYTES) & ~ALIGNBYTES)
94 
95 constexpr int MAXADDRS = 35;
96 
97 typedef union {
98     HEADER hdr;
99     uint8_t buf[MAXPACKET];
100 } querybuf;
101 
102 typedef union {
103     int32_t al;
104     char ac;
105 } align;
106 
107 static void convert_v4v6_hostent(struct hostent* hp, char** bpp, char* ep,
108                                  const std::function<void(struct hostent* hp)>& mapping_param,
109                                  const std::function<void(char* src, char* dst)>& mapping_addr);
110 static void pad_v4v6_hostent(struct hostent* hp, char** bpp, char* ep);
111 
112 static int dns_gethtbyaddr(const unsigned char* uaddr, int len, int af,
113                            const android_net_context* netcontext, getnamaddr* info,
114                            NetworkDnsEventReported* event);
115 static int dns_gethtbyname(ResState* res, const char* name, int af, getnamaddr* info);
116 
117 #define BOUNDED_INCR(x)      \
118     do {                     \
119         BOUNDS_CHECK(cp, x); \
120         cp += (x);           \
121     } while (0)
122 
123 #define BOUNDS_CHECK(ptr, count)                     \
124     do {                                             \
125         if (eom - (ptr) < (count)) goto no_recovery; \
126     } while (0)
127 
getanswer(const querybuf * answer,int anslen,const char * qname,int qtype,struct hostent * hent,char * buf,size_t buflen,int * he)128 static struct hostent* getanswer(const querybuf* answer, int anslen, const char* qname, int qtype,
129                                  struct hostent* hent, char* buf, size_t buflen, int* he) {
130     const HEADER* hp;
131     const uint8_t* cp;
132     int n;
133     size_t qlen;
134     const uint8_t *eom, *erdata;
135     char *bp, **hap, *ep;
136     int ancount, qdcount;
137     int haveanswer, had_error;
138     int toobig = 0;
139     char tbuf[MAXDNAME];
140     char* addr_ptrs[MAXADDRS];
141     const char* tname;
142     std::vector<char*> aliases;
143 
144     _DIAGASSERT(answer != NULL);
145     _DIAGASSERT(qname != NULL);
146 
147     tname = qname;
148     hent->h_name = NULL;
149     eom = answer->buf + anslen;
150 
151     bool (*name_ok)(const char* dn);
152     switch (qtype) {
153         case T_A:
154         case T_AAAA:
155             name_ok = res_hnok;
156             break;
157         case T_PTR:
158             name_ok = res_dnok;
159             break;
160         default:
161             *he = NO_RECOVERY;
162             return NULL; /* XXX should be abort(); */
163     }
164 
165     /*
166      * find first satisfactory answer
167      */
168     hp = &answer->hdr;
169     ancount = ntohs(hp->ancount);
170     qdcount = ntohs(hp->qdcount);
171     bp = buf;
172     ep = buf + buflen;
173     cp = answer->buf;
174     BOUNDED_INCR(HFIXEDSZ);
175     if (qdcount != 1) goto no_recovery;
176 
177     n = dn_expand(answer->buf, eom, cp, bp, (int) (ep - bp));
178     if ((n < 0) || !name_ok(bp)) goto no_recovery;
179 
180     BOUNDED_INCR(n + QFIXEDSZ);
181     if (qtype == T_A || qtype == T_AAAA) {
182         /* res_send() has already verified that the query name is the
183          * same as the one we sent; this just gets the expanded name
184          * (i.e., with the succeeding search-domain tacked on).
185          */
186         n = (int) strlen(bp) + 1; /* for the \0 */
187         if (n >= MAXHOSTNAMELEN) goto no_recovery;
188         hent->h_name = bp;
189         bp += n;
190         /* The qname can be abbreviated, but h_name is now absolute. */
191         qname = hent->h_name;
192     }
193     hent->h_addr_list = hap = addr_ptrs;
194     *hap = NULL;
195     haveanswer = 0;
196     had_error = 0;
197     while (ancount-- > 0 && cp < eom && !had_error) {
198         n = dn_expand(answer->buf, eom, cp, bp, (int) (ep - bp));
199         if ((n < 0) || !name_ok(bp)) {
200             had_error++;
201             continue;
202         }
203         cp += n; /* name */
204         BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
205         int type = ntohs(*reinterpret_cast<const uint16_t*>(cp));
206         cp += INT16SZ; /* type */
207         int cl = ntohs(*reinterpret_cast<const uint16_t*>(cp));
208         cp += INT16SZ + INT32SZ; /* class, TTL */
209         n = ntohs(*reinterpret_cast<const uint16_t*>(cp));
210         cp += INT16SZ; /* len */
211         BOUNDS_CHECK(cp, n);
212         erdata = cp + n;
213         if (cl != C_IN) {
214             /* XXX - debug? syslog? */
215             cp += n;
216             continue; /* XXX - had_error++ ? */
217         }
218         if ((qtype == T_A || qtype == T_AAAA) && type == T_CNAME) {
219             n = dn_expand(answer->buf, eom, cp, tbuf, (int) sizeof tbuf);
220             if ((n < 0) || !name_ok(tbuf)) {
221                 had_error++;
222                 continue;
223             }
224             cp += n;
225             if (cp != erdata) goto no_recovery;
226             /* Store alias. */
227             aliases.push_back(bp);
228             n = (int) strlen(bp) + 1; /* for the \0 */
229             if (n >= MAXHOSTNAMELEN) {
230                 had_error++;
231                 continue;
232             }
233             bp += n;
234             /* Get canonical name. */
235             n = (int) strlen(tbuf) + 1; /* for the \0 */
236             if (n > ep - bp || n >= MAXHOSTNAMELEN) {
237                 had_error++;
238                 continue;
239             }
240             strlcpy(bp, tbuf, (size_t)(ep - bp));
241             hent->h_name = bp;
242             bp += n;
243             continue;
244         }
245         if (qtype == T_PTR && type == T_CNAME) {
246             n = dn_expand(answer->buf, eom, cp, tbuf, (int) sizeof tbuf);
247             if (n < 0 || !res_dnok(tbuf)) {
248                 had_error++;
249                 continue;
250             }
251             cp += n;
252             if (cp != erdata) goto no_recovery;
253             /* Get canonical name. */
254             n = (int) strlen(tbuf) + 1; /* for the \0 */
255             if (n > ep - bp || n >= MAXHOSTNAMELEN) {
256                 had_error++;
257                 continue;
258             }
259             strlcpy(bp, tbuf, (size_t)(ep - bp));
260             tname = bp;
261             bp += n;
262             continue;
263         }
264         if (type != qtype) {
265             if (type != T_KEY && type != T_SIG)
266                 LOG(DEBUG) << __func__ << ": asked for \"" << qname << " " << p_class(C_IN) << " "
267                            << p_type(qtype) << "\", got type \"" << p_type(type) << "\"";
268             cp += n;
269             continue; /* XXX - had_error++ ? */
270         }
271         switch (type) {
272             case T_PTR:
273                 if (strcasecmp(tname, bp) != 0) {
274                     LOG(DEBUG) << __func__ << ": asked for \"" << qname << "\", got \"" << bp
275                                << "\"";
276                     cp += n;
277                     continue; /* XXX - had_error++ ? */
278                 }
279                 n = dn_expand(answer->buf, eom, cp, bp, (int) (ep - bp));
280                 if ((n < 0) || !res_hnok(bp)) {
281                     had_error++;
282                     break;
283                 }
284                 cp += n;
285                 if (cp != erdata) goto no_recovery;
286                 if (!haveanswer)
287                     hent->h_name = bp;
288                 else
289                     aliases.push_back(bp);
290                 if (n != -1) {
291                     n = (int) strlen(bp) + 1; /* for the \0 */
292                     if (n >= MAXHOSTNAMELEN) {
293                         had_error++;
294                         break;
295                     }
296                     bp += n;
297                 }
298                 break;
299             case T_A:
300             case T_AAAA:
301                 if (strcasecmp(hent->h_name, bp) != 0) {
302                     LOG(DEBUG) << __func__ << ": asked for \"" << hent->h_name << "\", got \"" << bp
303                                << "\"";
304                     cp += n;
305                     continue; /* XXX - had_error++ ? */
306                 }
307                 if (n != hent->h_length) {
308                     cp += n;
309                     continue;
310                 }
311                 if (type == T_AAAA) {
312                     struct in6_addr in6;
313                     memcpy(&in6, cp, NS_IN6ADDRSZ);
314                     if (IN6_IS_ADDR_V4MAPPED(&in6)) {
315                         cp += n;
316                         continue;
317                     }
318                 }
319                 if (!haveanswer) {
320                     int nn;
321 
322                     hent->h_name = bp;
323                     nn = (int) strlen(bp) + 1; /* for the \0 */
324                     bp += nn;
325                 }
326 
327                 bp += sizeof(align) - (size_t)((uintptr_t)bp % sizeof(align));
328 
329                 if (bp + n >= ep) {
330                     LOG(DEBUG) << __func__ << ": size (" << n << ") too big";
331                     had_error++;
332                     continue;
333                 }
334                 if (hap >= &addr_ptrs[MAXADDRS - 1]) {
335                     if (!toobig++) {
336                         LOG(DEBUG) << __func__ << ": Too many addresses (" << MAXADDRS << ")";
337                     }
338                     cp += n;
339                     continue;
340                 }
341                 (void) memcpy(*hap++ = bp, cp, (size_t) n);
342                 bp += n;
343                 cp += n;
344                 if (cp != erdata) goto no_recovery;
345                 break;
346             default:
347                 abort();
348         }
349         if (!had_error) haveanswer++;
350     }
351     if (haveanswer) {
352         *hap = NULL;
353         if (!hent->h_name) {
354             n = (int) strlen(qname) + 1; /* for the \0 */
355             if (n > ep - bp || n >= MAXHOSTNAMELEN) goto no_recovery;
356             strlcpy(bp, qname, (size_t)(ep - bp));
357             hent->h_name = bp;
358             bp += n;
359         }
360         if (hent->h_addrtype == AF_INET) pad_v4v6_hostent(hent, &bp, ep);
361         goto success;
362     }
363 no_recovery:
364     *he = NO_RECOVERY;
365     return NULL;
366 success:
367     bp = (char*) ALIGN(bp);
368     aliases.push_back(nullptr);
369     qlen = aliases.size() * sizeof(*hent->h_aliases);
370     if ((size_t)(ep - bp) < qlen) goto nospc;
371     hent->h_aliases = (char**) bp;
372     memcpy(bp, aliases.data(), qlen);
373 
374     bp += qlen;
375     n = (int) (hap - addr_ptrs);
376     qlen = (n + 1) * sizeof(*hent->h_addr_list);
377     if ((size_t)(ep - bp) < qlen) goto nospc;
378     hent->h_addr_list = (char**) bp;
379     memcpy(bp, addr_ptrs, qlen);
380     *he = NETDB_SUCCESS;
381     return hent;
382 nospc:
383     errno = ENOSPC;
384     *he = NETDB_INTERNAL;
385     return NULL;
386 }
387 
resolv_gethostbyname(const char * name,int af,hostent * hp,char * buf,size_t buflen,const android_net_context * netcontext,hostent ** result,NetworkDnsEventReported * event)388 int resolv_gethostbyname(const char* name, int af, hostent* hp, char* buf, size_t buflen,
389                          const android_net_context* netcontext, hostent** result,
390                          NetworkDnsEventReported* event) {
391     getnamaddr info;
392 
393     ResState res;
394     res_init(&res, netcontext, event);
395 
396     size_t size;
397     switch (af) {
398         case AF_INET:
399             size = NS_INADDRSZ;
400             break;
401         case AF_INET6:
402             size = NS_IN6ADDRSZ;
403             break;
404         default:
405             return EAI_FAMILY;
406     }
407     if (buflen < size) goto nospc;
408 
409     hp->h_addrtype = af;
410     hp->h_length = (int) size;
411 
412     /*
413      * disallow names consisting only of digits/dots, unless
414      * they end in a dot.
415      */
416     if (isdigit((uint8_t)name[0])) {
417         for (const char* cp = name;; ++cp) {
418             if (!*cp) {
419                 if (*--cp == '.') break;
420                 /*
421                  * All-numeric, no dot at the end.
422                  * Fake up a hostent as if we'd actually
423                  * done a lookup.
424                  */
425                 goto fake;
426             }
427             if (!isdigit((uint8_t)*cp) && *cp != '.') break;
428         }
429     }
430     if ((isxdigit((uint8_t)name[0]) && strchr(name, ':') != NULL) || name[0] == ':') {
431         for (const char* cp = name;; ++cp) {
432             if (!*cp) {
433                 if (*--cp == '.') break;
434                 /*
435                  * All-IPv6-legal, no dot at the end.
436                  * Fake up a hostent as if we'd actually
437                  * done a lookup.
438                  */
439                 goto fake;
440             }
441             if (!isxdigit((uint8_t)*cp) && *cp != ':' && *cp != '.') break;
442         }
443     }
444 
445     info.hp = hp;
446     info.buf = buf;
447     info.buflen = buflen;
448     if (_hf_gethtbyname2(name, af, &info)) {
449         int error = dns_gethtbyname(&res, name, af, &info);
450         if (error != 0) return error;
451     }
452     *result = hp;
453     return 0;
454 nospc:
455     return EAI_MEMORY;
456 fake:
457     HENT_ARRAY(hp->h_addr_list, 1, buf, buflen);
458     HENT_ARRAY(hp->h_aliases, 0, buf, buflen);
459 
460     hp->h_aliases[0] = NULL;
461     if (size > buflen) goto nospc;
462 
463     if (inet_pton(af, name, buf) <= 0) {
464         return EAI_NODATA;
465     }
466     hp->h_addr_list[0] = buf;
467     hp->h_addr_list[1] = NULL;
468     buf += size;
469     buflen -= size;
470     HENT_SCOPY(hp->h_name, name, buf, buflen);
471     *result = hp;
472     return 0;
473 }
474 
resolv_gethostbyaddr(const void * addr,socklen_t len,int af,hostent * hp,char * buf,size_t buflen,const struct android_net_context * netcontext,hostent ** result,NetworkDnsEventReported * event)475 int resolv_gethostbyaddr(const void* addr, socklen_t len, int af, hostent* hp, char* buf,
476                          size_t buflen, const struct android_net_context* netcontext,
477                          hostent** result, NetworkDnsEventReported* event) {
478     const uint8_t* uaddr = (const uint8_t*)addr;
479     socklen_t size;
480     struct getnamaddr info;
481 
482     _DIAGASSERT(addr != NULL);
483 
484     if (af == AF_INET6 && len == NS_IN6ADDRSZ &&
485         (IN6_IS_ADDR_LINKLOCAL((const struct in6_addr*) addr) ||
486          IN6_IS_ADDR_SITELOCAL((const struct in6_addr*) addr))) {
487         return EAI_NODATA;
488     }
489     if (af == AF_INET6 && len == NS_IN6ADDRSZ &&
490         (IN6_IS_ADDR_V4MAPPED((const struct in6_addr*) addr) ||
491          IN6_IS_ADDR_V4COMPAT((const struct in6_addr*) addr))) {
492         /* Unmap. */
493         uaddr += NS_IN6ADDRSZ - NS_INADDRSZ;
494         addr = uaddr;
495         af = AF_INET;
496         len = NS_INADDRSZ;
497     }
498     switch (af) {
499         case AF_INET:
500             size = NS_INADDRSZ;
501             break;
502         case AF_INET6:
503             size = NS_IN6ADDRSZ;
504             break;
505         default:
506             return EAI_FAMILY;
507     }
508     if (size != len) {
509         // TODO: Consider converting to a private extended EAI_* error code.
510         // Currently, the EAI_* value has no corresponding error code for invalid argument socket
511         // length. In order to not rely on errno, convert the original error code pair, EAI_SYSTEM
512         // and EINVAL, to EAI_FAIL.
513         return EAI_FAIL;
514     }
515     info.hp = hp;
516     info.buf = buf;
517     info.buflen = buflen;
518     if (_hf_gethtbyaddr(uaddr, len, af, &info)) {
519         int error = dns_gethtbyaddr(uaddr, len, af, netcontext, &info, event);
520         if (error != 0) return error;
521     }
522     *result = hp;
523     return 0;
524 }
525 
526 // TODO: Consider leaving function without returning error code as _gethtent() does because
527 // 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)528 struct hostent* netbsd_gethostent_r(FILE* hf, struct hostent* hent, char* buf, size_t buflen,
529                                     int* he) {
530     char *name;
531     char* cp;
532     int af, len;
533     size_t anum;
534     struct in6_addr host_addr;
535     std::vector<char*> aliases;
536 
537     if (hf == NULL) {
538         *he = NETDB_INTERNAL;
539         errno = EINVAL;
540         return NULL;
541     }
542     char* p = NULL;
543 
544     // Allocate a new space to read file lines like upstream does.
545     const size_t line_buf_size = MAXPACKET;
546     if ((p = (char*) malloc(line_buf_size)) == NULL) {
547         goto nospc;
548     }
549     for (;;) {
550         if (!fgets(p, line_buf_size, hf)) {
551             free(p);
552             *he = HOST_NOT_FOUND;
553             return NULL;
554         }
555         if (*p == '#') {
556             continue;
557         }
558         if (!(cp = strpbrk(p, "#\n"))) {
559             continue;
560         }
561         *cp = '\0';
562         if (!(cp = strpbrk(p, " \t"))) continue;
563         *cp++ = '\0';
564         if (inet_pton(AF_INET6, p, &host_addr) > 0) {
565             af = AF_INET6;
566             len = NS_IN6ADDRSZ;
567         } else {
568             if (inet_pton(AF_INET, p, &host_addr) <= 0) continue;
569             af = AF_INET;
570             len = NS_INADDRSZ;
571         }
572 
573         /* if this is not something we're looking for, skip it. */
574         if (hent->h_addrtype != 0 && hent->h_addrtype != af) continue;
575         if (hent->h_length != 0 && hent->h_length != len) continue;
576 
577         while (*cp == ' ' || *cp == '\t') cp++;
578         if ((cp = strpbrk(name = cp, " \t")) != NULL) *cp++ = '\0';
579         while (cp && *cp) {
580             if (*cp == ' ' || *cp == '\t') {
581                 cp++;
582                 continue;
583             }
584             aliases.push_back(cp);
585             if ((cp = strpbrk(cp, " \t")) != NULL) *cp++ = '\0';
586         }
587         break;
588     }
589     hent->h_length = len;
590     hent->h_addrtype = af;
591     HENT_ARRAY(hent->h_addr_list, 1, buf, buflen);
592     anum = aliases.size();
593     HENT_ARRAY(hent->h_aliases, anum, buf, buflen);
594     HENT_COPY(hent->h_addr_list[0], &host_addr, hent->h_length, buf, buflen);
595     hent->h_addr_list[1] = NULL;
596 
597     /* Reserve space for mapping IPv4 address to IPv6 address in place */
598     if (hent->h_addrtype == AF_INET) {
599         HENT_COPY(buf, NAT64_PAD, sizeof(NAT64_PAD), buf, buflen);
600     }
601 
602     HENT_SCOPY(hent->h_name, name, buf, buflen);
603     for (size_t i = 0; i < anum; i++) HENT_SCOPY(hent->h_aliases[i], aliases[i], buf, buflen);
604     hent->h_aliases[anum] = NULL;
605     *he = NETDB_SUCCESS;
606     free(p);
607     return hent;
608 nospc:
609     free(p);
610     errno = ENOSPC;
611     *he = NETDB_INTERNAL;
612     return NULL;
613 }
614 
convert_v4v6_hostent(struct hostent * hp,char ** bpp,char * ep,const std::function<void (struct hostent * hp)> & map_param,const std::function<void (char * src,char * dst)> & map_addr)615 static void convert_v4v6_hostent(struct hostent* hp, char** bpp, char* ep,
616                                  const std::function<void(struct hostent* hp)>& map_param,
617                                  const std::function<void(char* src, char* dst)>& map_addr) {
618     _DIAGASSERT(hp != NULL);
619     _DIAGASSERT(bpp != NULL);
620     _DIAGASSERT(ep != NULL);
621 
622     if (hp->h_addrtype != AF_INET || hp->h_length != NS_INADDRSZ) return;
623     map_param(hp);
624     for (char** ap = hp->h_addr_list; *ap; ap++) {
625         int i = (int)(sizeof(align) - (size_t)((uintptr_t)*bpp % sizeof(align)));
626 
627         if (ep - *bpp < (i + NS_IN6ADDRSZ)) {
628             /* Out of memory.  Truncate address list here.  XXX */
629             *ap = NULL;
630             return;
631         }
632         *bpp += i;
633         map_addr(*ap, *bpp);
634         *ap = *bpp;
635         *bpp += NS_IN6ADDRSZ;
636     }
637 }
638 
639 /* Reserve space for mapping IPv4 address to IPv6 address in place */
pad_v4v6_hostent(struct hostent * hp,char ** bpp,char * ep)640 static void pad_v4v6_hostent(struct hostent* hp, char** bpp, char* ep) {
641     convert_v4v6_hostent(hp, bpp, ep,
642                          [](struct hostent* hp) {
643                              (void) hp; /* unused */
644                          },
645                          [](char* src, char* dst) {
646                              memcpy(dst, src, NS_INADDRSZ);
647                              memcpy(dst + NS_INADDRSZ, NAT64_PAD, sizeof(NAT64_PAD));
648                          });
649 }
650 
dns_gethtbyname(ResState * res,const char * name,int addr_type,getnamaddr * info)651 static int dns_gethtbyname(ResState* res, const char* name, int addr_type, getnamaddr* info) {
652     int n, type;
653     info->hp->h_addrtype = addr_type;
654 
655     switch (info->hp->h_addrtype) {
656         case AF_INET:
657             info->hp->h_length = NS_INADDRSZ;
658             type = T_A;
659             break;
660         case AF_INET6:
661             info->hp->h_length = NS_IN6ADDRSZ;
662             type = T_AAAA;
663             break;
664         default:
665             return EAI_FAMILY;
666     }
667     auto buf = std::make_unique<querybuf>();
668 
669     int he;
670     n = res_nsearch(res, name, C_IN, type, buf->buf, (int)sizeof(buf->buf), &he);
671     if (n < 0) {
672         LOG(DEBUG) << __func__ << ": res_nsearch failed (" << n << ")";
673         // Return h_errno (he) to catch more detailed errors rather than EAI_NODATA.
674         // Note that res_nsearch() doesn't set the pair NETDB_INTERNAL and errno.
675         // See also herrnoToAiErrno().
676         return herrnoToAiErrno(he);
677     }
678     hostent* hp = getanswer(buf.get(), n, name, type, info->hp, info->buf, info->buflen, &he);
679     if (hp == NULL) return herrnoToAiErrno(he);
680 
681     return 0;
682 }
683 
dns_gethtbyaddr(const unsigned char * uaddr,int len,int af,const android_net_context * netcontext,getnamaddr * info,NetworkDnsEventReported * event)684 static int dns_gethtbyaddr(const unsigned char* uaddr, int len, int af,
685                            const android_net_context* netcontext, getnamaddr* info,
686                            NetworkDnsEventReported* event) {
687     char qbuf[MAXDNAME + 1], *qp, *ep;
688     int n;
689     int advance;
690 
691     info->hp->h_length = len;
692     info->hp->h_addrtype = af;
693 
694     switch (info->hp->h_addrtype) {
695         case AF_INET:
696             (void) snprintf(qbuf, sizeof(qbuf), "%u.%u.%u.%u.in-addr.arpa", (uaddr[3] & 0xff),
697                             (uaddr[2] & 0xff), (uaddr[1] & 0xff), (uaddr[0] & 0xff));
698             break;
699 
700         case AF_INET6:
701             qp = qbuf;
702             ep = qbuf + sizeof(qbuf) - 1;
703             for (n = NS_IN6ADDRSZ - 1; n >= 0; n--) {
704                 advance = snprintf(qp, (size_t)(ep - qp), "%x.%x.", uaddr[n] & 0xf,
705                                    ((unsigned int) uaddr[n] >> 4) & 0xf);
706                 if (advance > 0 && qp + advance < ep)
707                     qp += advance;
708                 else {
709                     // TODO: Consider converting to a private extended EAI_* error code.
710                     // Currently, the EAI_* value has no corresponding error code for an internal
711                     // out of buffer space. In order to not rely on errno, convert the original
712                     // error code EAI_SYSTEM to EAI_MEMORY.
713                     return EAI_MEMORY;
714                 }
715             }
716             if (strlcat(qbuf, "ip6.arpa", sizeof(qbuf)) >= sizeof(qbuf)) {
717                 // TODO: Consider converting to a private extended EAI_* error code.
718                 // Currently, the EAI_* value has no corresponding error code for an internal
719                 // out of buffer space. In order to not rely on errno, convert the original
720                 // error code EAI_SYSTEM to EAI_MEMORY.
721                 return EAI_MEMORY;
722             }
723             break;
724         default:
725             return EAI_FAMILY;
726     }
727 
728     auto buf = std::make_unique<querybuf>();
729 
730     ResState res;
731     res_init(&res, netcontext, event);
732     int he;
733     n = res_nquery(&res, qbuf, C_IN, T_PTR, buf->buf, (int)sizeof(buf->buf), &he);
734     if (n < 0) {
735         LOG(DEBUG) << __func__ << ": res_nquery failed (" << n << ")";
736         // Note that res_nquery() doesn't set the pair NETDB_INTERNAL and errno.
737         // Return h_errno (he) to catch more detailed errors rather than EAI_NODATA.
738         // See also herrnoToAiErrno().
739         return herrnoToAiErrno(he);
740     }
741     hostent* hp = getanswer(buf.get(), n, qbuf, T_PTR, info->hp, info->buf, info->buflen, &he);
742     if (hp == NULL) return herrnoToAiErrno(he);
743 
744     char* bf = (char*) (hp->h_addr_list + 2);
745     size_t blen = (size_t)(bf - info->buf);
746     if (blen + info->hp->h_length > info->buflen) goto nospc;
747     hp->h_addr_list[0] = bf;
748     hp->h_addr_list[1] = NULL;
749     memcpy(bf, uaddr, (size_t) info->hp->h_length);
750 
751     /* Reserve enough space for mapping IPv4 address to IPv6 address in place */
752     if (info->hp->h_addrtype == AF_INET) {
753         if (blen + NS_IN6ADDRSZ > info->buflen) goto nospc;
754         // Pad zero to the unused address space
755         memcpy(bf + NS_INADDRSZ, NAT64_PAD, sizeof(NAT64_PAD));
756     }
757 
758     return 0;
759 
760 nospc:
761     return EAI_MEMORY;
762 }
763 
herrnoToAiErrno(int he)764 int herrnoToAiErrno(int he) {
765     switch (he) {
766         // extended h_errno
767         case NETD_RESOLV_H_ERRNO_EXT_TIMEOUT:
768             return NETD_RESOLV_TIMEOUT;
769         // legacy h_errno
770         case NETDB_SUCCESS:
771             return 0;
772         case HOST_NOT_FOUND:  // TODO: Perhaps convert HOST_NOT_FOUND to EAI_NONAME instead
773         case NO_DATA:         // NO_ADDRESS
774             return EAI_NODATA;
775         case TRY_AGAIN:
776             return EAI_AGAIN;
777         case NETDB_INTERNAL:
778             // TODO: Remove ENOSPC and call abort() immediately whenever any allocation fails.
779             if (errno == ENOSPC) return EAI_MEMORY;
780             // Theoretically, this should not happen. Leave this here just in case.
781             // Currently, getanswer() of {gethnamaddr, getaddrinfo}.cpp, res_nsearch() and
782             // res_searchN() use this function to convert error code. Only getanswer()
783             // of gethnamaddr.cpp may return the error code pair, herrno NETDB_INTERNAL and
784             // errno ENOSPC, which has already converted to EAI_MEMORY. The remaining functions
785             // don't set the pair herrno and errno.
786             return EAI_SYSTEM;  // see errno for detail
787         case NO_RECOVERY:
788         default:
789             return EAI_FAIL;  // TODO: Perhaps convert default to EAI_MAX (unknown error) instead
790     }
791 }
792