* resolv/res_hconf.c (_res_hconf_trim_domain): Use strcasecmp
[platform/upstream/glibc.git] / resolv / nss_dns / dns-host.c
1 /* Copyright (C) 1996-2004, 2007, 2008, 2009 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3    Extended from original form by Ulrich Drepper <drepper@cygnus.com>, 1996.
4
5    The GNU C Library is free software; you can redistribute it and/or
6    modify it under the terms of the GNU Lesser General Public
7    License as published by the Free Software Foundation; either
8    version 2.1 of the License, or (at your option) any later version.
9
10    The GNU C Library is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14
15    You should have received a copy of the GNU Lesser General Public
16    License along with the GNU C Library; if not, write to the Free
17    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18    02111-1307 USA.  */
19
20 /* Parts of this file are plain copies of the file `gethtnamadr.c' from
21    the bind package and it has the following copyright.  */
22
23 /*
24  * ++Copyright++ 1985, 1988, 1993
25  * -
26  * Copyright (c) 1985, 1988, 1993
27  *    The Regents of the University of California.  All rights reserved.
28  *
29  * Redistribution and use in source and binary forms, with or without
30  * modification, are permitted provided that the following conditions
31  * are met:
32  * 1. Redistributions of source code must retain the above copyright
33  *    notice, this list of conditions and the following disclaimer.
34  * 2. Redistributions in binary form must reproduce the above copyright
35  *    notice, this list of conditions and the following disclaimer in the
36  *    documentation and/or other materials provided with the distribution.
37  * 4. Neither the name of the University nor the names of its contributors
38  *    may be used to endorse or promote products derived from this software
39  *    without specific prior written permission.
40  *
41  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * -
53  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
54  *
55  * Permission to use, copy, modify, and distribute this software for any
56  * purpose with or without fee is hereby granted, provided that the above
57  * copyright notice and this permission notice appear in all copies, and that
58  * the name of Digital Equipment Corporation not be used in advertising or
59  * publicity pertaining to distribution of the document or software without
60  * specific, written prior permission.
61  *
62  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
63  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
64  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
65  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
66  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
67  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
68  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
69  * SOFTWARE.
70  * -
71  * --Copyright--
72  */
73
74 #include <assert.h>
75 #include <ctype.h>
76 #include <errno.h>
77 #include <netdb.h>
78 #include <stdio.h>
79 #include <stdlib.h>
80 #include <stddef.h>
81 #include <string.h>
82 #include <sys/syslog.h>
83
84 #include "nsswitch.h"
85
86 /* Get implementation for some internal functions.  */
87 #include <resolv/mapv4v6addr.h>
88 #include <resolv/mapv4v6hostent.h>
89
90 #define RESOLVSORT
91
92 /* Maximum number of aliases we allow.  */
93 #define MAX_NR_ALIASES  48
94 #define MAX_NR_ADDRS    48
95
96 #if PACKETSZ > 65536
97 # define MAXPACKET      PACKETSZ
98 #else
99 # define MAXPACKET      65536
100 #endif
101 /* As per RFC 1034 and 1035 a host name cannot exceed 255 octets in length.  */
102 #ifdef MAXHOSTNAMELEN
103 # undef MAXHOSTNAMELEN
104 #endif
105 #define MAXHOSTNAMELEN 256
106
107 static const char AskedForGot[] = "\
108 gethostby*.getanswer: asked for \"%s\", got \"%s\"";
109
110
111 /* We need this time later.  */
112 typedef union querybuf
113 {
114   HEADER hdr;
115   u_char buf[MAXPACKET];
116 } querybuf;
117
118 /* These functions are defined in res_comp.c.  */
119 #define NS_MAXCDNAME    255     /* maximum compressed domain name */
120 extern int __ns_name_ntop (const u_char *, char *, size_t);
121 extern int __ns_name_unpack (const u_char *, const u_char *,
122                              const u_char *, u_char *, size_t);
123
124
125 static enum nss_status getanswer_r (const querybuf *answer, int anslen,
126                                     const char *qname, int qtype,
127                                     struct hostent *result, char *buffer,
128                                     size_t buflen, int *errnop, int *h_errnop,
129                                     int map, int32_t *ttlp, char **canonp);
130
131 static enum nss_status gaih_getanswer (const querybuf *answer1, int anslen1,
132                                        const querybuf *answer2, int anslen2,
133                                        const char *qname,
134                                        struct gaih_addrtuple **pat,
135                                        char *buffer, size_t buflen,
136                                        int *errnop, int *h_errnop,
137                                        int32_t *ttlp);
138
139 extern enum nss_status _nss_dns_gethostbyname3_r (const char *name, int af,
140                                                   struct hostent *result,
141                                                   char *buffer, size_t buflen,
142                                                   int *errnop, int *h_errnop,
143                                                   int32_t *ttlp,
144                                                   char **canonp);
145 hidden_proto (_nss_dns_gethostbyname3_r)
146
147 enum nss_status
148 _nss_dns_gethostbyname3_r (const char *name, int af, struct hostent *result,
149                            char *buffer, size_t buflen, int *errnop,
150                            int *h_errnop, int32_t *ttlp, char **canonp)
151 {
152   union
153   {
154     querybuf *buf;
155     u_char *ptr;
156   } host_buffer;
157   querybuf *orig_host_buffer;
158   char tmp[NS_MAXDNAME];
159   int size, type, n;
160   const char *cp;
161   int map = 0;
162   int olderr = errno;
163   enum nss_status status;
164
165   if (__res_maybe_init (&_res, 0) == -1)
166     return NSS_STATUS_UNAVAIL;
167
168   switch (af) {
169   case AF_INET:
170     size = INADDRSZ;
171     type = T_A;
172     break;
173   case AF_INET6:
174     size = IN6ADDRSZ;
175     type = T_AAAA;
176     break;
177   default:
178     *h_errnop = NO_DATA;
179     *errnop = EAFNOSUPPORT;
180     return NSS_STATUS_UNAVAIL;
181   }
182
183   result->h_addrtype = af;
184   result->h_length = size;
185
186   /*
187    * if there aren't any dots, it could be a user-level alias.
188    * this is also done in res_query() since we are not the only
189    * function that looks up host names.
190    */
191   if (strchr (name, '.') == NULL
192       && (cp = res_hostalias (&_res, name, tmp, sizeof (tmp))) != NULL)
193     name = cp;
194
195   host_buffer.buf = orig_host_buffer = (querybuf *) alloca (1024);
196
197   n = __libc_res_nsearch (&_res, name, C_IN, type, host_buffer.buf->buf,
198                           1024, &host_buffer.ptr, NULL, NULL, NULL);
199   if (n < 0)
200     {
201       if (errno == ESRCH)
202         {
203           status = NSS_STATUS_TRYAGAIN;
204           h_errno = TRY_AGAIN;
205         }
206       else
207         status = (errno == ECONNREFUSED
208                   ? NSS_STATUS_UNAVAIL : NSS_STATUS_NOTFOUND);
209       *h_errnop = h_errno;
210       if (h_errno == TRY_AGAIN)
211         *errnop = EAGAIN;
212       else
213         __set_errno (olderr);
214
215       /* If we are looking for a IPv6 address and mapping is enabled
216          by having the RES_USE_INET6 bit in _res.options set, we try
217          another lookup.  */
218       if (af == AF_INET6 && (_res.options & RES_USE_INET6))
219         n = __libc_res_nsearch (&_res, name, C_IN, T_A, host_buffer.buf->buf,
220                                 host_buffer.buf != orig_host_buffer
221                                 ? MAXPACKET : 1024, &host_buffer.ptr,
222                                 NULL, NULL, NULL);
223
224       if (n < 0)
225         {
226           if (host_buffer.buf != orig_host_buffer)
227             free (host_buffer.buf);
228           return status;
229         }
230
231       map = 1;
232
233       result->h_addrtype = AF_INET;
234       result->h_length = INADDRSZ;
235     }
236
237   status = getanswer_r (host_buffer.buf, n, name, type, result, buffer, buflen,
238                         errnop, h_errnop, map, ttlp, canonp);
239   if (host_buffer.buf != orig_host_buffer)
240     free (host_buffer.buf);
241   return status;
242 }
243 hidden_def (_nss_dns_gethostbyname3_r)
244
245
246 enum nss_status
247 _nss_dns_gethostbyname2_r (const char *name, int af, struct hostent *result,
248                            char *buffer, size_t buflen, int *errnop,
249                            int *h_errnop)
250 {
251   return _nss_dns_gethostbyname3_r (name, af, result, buffer, buflen, errnop,
252                                     h_errnop, NULL, NULL);
253 }
254
255
256 enum nss_status
257 _nss_dns_gethostbyname_r (const char *name, struct hostent *result,
258                           char *buffer, size_t buflen, int *errnop,
259                           int *h_errnop)
260 {
261   enum nss_status status = NSS_STATUS_NOTFOUND;
262
263   if (_res.options & RES_USE_INET6)
264     status = _nss_dns_gethostbyname3_r (name, AF_INET6, result, buffer,
265                                         buflen, errnop, h_errnop, NULL, NULL);
266   if (status == NSS_STATUS_NOTFOUND)
267     status = _nss_dns_gethostbyname3_r (name, AF_INET, result, buffer,
268                                         buflen, errnop, h_errnop, NULL, NULL);
269
270   return status;
271 }
272
273
274 enum nss_status
275 _nss_dns_gethostbyname4_r (const char *name, struct gaih_addrtuple **pat,
276                            char *buffer, size_t buflen, int *errnop,
277                            int *herrnop, int32_t *ttlp)
278 {
279   if (__res_maybe_init (&_res, 0) == -1)
280     return NSS_STATUS_UNAVAIL;
281
282   /*
283    * if there aren't any dots, it could be a user-level alias.
284    * this is also done in res_query() since we are not the only
285    * function that looks up host names.
286    */
287   if (strchr (name, '.') == NULL)
288     {
289       char *tmp = alloca (NS_MAXDNAME);
290       const char *cp = res_hostalias (&_res, name, tmp, NS_MAXDNAME);
291       if (cp != NULL)
292         name = cp;
293     }
294
295   union
296   {
297     querybuf *buf;
298     u_char *ptr;
299   } host_buffer;
300   querybuf *orig_host_buffer;
301   host_buffer.buf = orig_host_buffer = (querybuf *) alloca (2048);
302   u_char *ans2p = NULL;
303   int nans2p = 0;
304   int resplen2 = 0;
305
306   int olderr = errno;
307   enum nss_status status;
308   int n = __libc_res_nsearch (&_res, name, C_IN, T_UNSPEC,
309                               host_buffer.buf->buf, 2048, &host_buffer.ptr,
310                               &ans2p, &nans2p, &resplen2);
311   if (n < 0)
312     {
313       if (errno == ESRCH)
314         {
315           status = NSS_STATUS_TRYAGAIN;
316           h_errno = TRY_AGAIN;
317         }
318       else
319         status = (errno == ECONNREFUSED
320                   ? NSS_STATUS_UNAVAIL : NSS_STATUS_NOTFOUND);
321       *herrnop = h_errno;
322       if (h_errno == TRY_AGAIN)
323         *errnop = EAGAIN;
324       else
325         __set_errno (olderr);
326
327       if (host_buffer.buf != orig_host_buffer)
328         free (host_buffer.buf);
329
330       return status;
331     }
332
333   status = gaih_getanswer(host_buffer.buf, n, (const querybuf *) ans2p,
334                           resplen2, name, pat, buffer, buflen,
335                           errnop, herrnop, ttlp);
336
337   if (host_buffer.buf != orig_host_buffer)
338     free (host_buffer.buf);
339
340   return status;
341 }
342
343
344 extern enum nss_status _nss_dns_gethostbyaddr2_r (const void *addr,
345                                                   socklen_t len, int af,
346                                                   struct hostent *result,
347                                                   char *buffer, size_t buflen,
348                                                   int *errnop, int *h_errnop,
349                                                   int32_t *ttlp);
350 hidden_proto (_nss_dns_gethostbyaddr2_r)
351
352 enum nss_status
353 _nss_dns_gethostbyaddr2_r (const void *addr, socklen_t len, int af,
354                            struct hostent *result, char *buffer, size_t buflen,
355                            int *errnop, int *h_errnop, int32_t *ttlp)
356 {
357   static const u_char mapped[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
358   static const u_char tunnelled[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0,0 };
359   static const u_char v6local[] = { 0,0, 0,1 };
360   const u_char *uaddr = (const u_char *)addr;
361   struct host_data
362   {
363     char *aliases[MAX_NR_ALIASES];
364     unsigned char host_addr[16];        /* IPv4 or IPv6 */
365     char *h_addr_ptrs[MAX_NR_ADDRS + 1];
366     char linebuffer[0];
367   } *host_data = (struct host_data *) buffer;
368   union
369   {
370     querybuf *buf;
371     u_char *ptr;
372   } host_buffer;
373   querybuf *orig_host_buffer;
374   char qbuf[MAXDNAME+1], *qp = NULL;
375   size_t size;
376   int n, status;
377   int olderr = errno;
378
379  uintptr_t pad = -(uintptr_t) buffer % __alignof__ (struct host_data);
380  buffer += pad;
381  buflen = buflen > pad ? buflen - pad : 0;
382
383  if (__builtin_expect (buflen < sizeof (struct host_data), 0))
384    {
385      *errnop = ERANGE;
386      *h_errnop = NETDB_INTERNAL;
387      return NSS_STATUS_TRYAGAIN;
388    }
389
390  host_data = (struct host_data *) buffer;
391
392   if (__res_maybe_init (&_res, 0) == -1)
393     return NSS_STATUS_UNAVAIL;
394
395   if (af == AF_INET6 && len == IN6ADDRSZ
396       && (memcmp (uaddr, mapped, sizeof mapped) == 0
397           || (memcmp (uaddr, tunnelled, sizeof tunnelled) == 0
398               && memcmp (&uaddr[sizeof tunnelled], v6local, sizeof v6local))))
399     {
400       /* Unmap. */
401       addr += sizeof mapped;
402       uaddr += sizeof mapped;
403       af = AF_INET;
404       len = INADDRSZ;
405     }
406
407   switch (af)
408     {
409     case AF_INET:
410       size = INADDRSZ;
411       break;
412     case AF_INET6:
413       size = IN6ADDRSZ;
414       break;
415     default:
416       *errnop = EAFNOSUPPORT;
417       *h_errnop = NETDB_INTERNAL;
418       return NSS_STATUS_UNAVAIL;
419     }
420   if (size > len)
421     {
422       *errnop = EAFNOSUPPORT;
423       *h_errnop = NETDB_INTERNAL;
424       return NSS_STATUS_UNAVAIL;
425     }
426
427   host_buffer.buf = orig_host_buffer = (querybuf *) alloca (1024);
428
429   switch (af)
430     {
431     case AF_INET:
432       sprintf (qbuf, "%u.%u.%u.%u.in-addr.arpa", (uaddr[3] & 0xff),
433                (uaddr[2] & 0xff), (uaddr[1] & 0xff), (uaddr[0] & 0xff));
434       break;
435     case AF_INET6:
436       /* Only lookup with the byte string format if the user wants it.  */
437       if (__builtin_expect (_res.options & RES_USEBSTRING, 0))
438         {
439           qp = stpcpy (qbuf, "\\[x");
440           for (n = 0; n < IN6ADDRSZ; ++n)
441             qp += sprintf (qp, "%02hhx", uaddr[n]);
442           strcpy (qp, "].ip6.arpa");
443           n = __libc_res_nquery (&_res, qbuf, C_IN, T_PTR,
444                                  host_buffer.buf->buf, 1024, &host_buffer.ptr,
445                                  NULL, NULL, NULL);
446           if (n >= 0)
447             goto got_it_already;
448         }
449       qp = qbuf;
450       for (n = IN6ADDRSZ - 1; n >= 0; n--)
451         {
452           static const char nibblechar[16] = "0123456789abcdef";
453           *qp++ = nibblechar[uaddr[n] & 0xf];
454           *qp++ = '.';
455           *qp++ = nibblechar[(uaddr[n] >> 4) & 0xf];
456           *qp++ = '.';
457         }
458       strcpy(qp, "ip6.arpa");
459       break;
460     default:
461       /* Cannot happen.  */
462       break;
463     }
464
465   n = __libc_res_nquery (&_res, qbuf, C_IN, T_PTR, host_buffer.buf->buf,
466                          1024, &host_buffer.ptr, NULL, NULL, NULL);
467   if (n < 0 && af == AF_INET6 && (_res.options & RES_NOIP6DOTINT) == 0)
468     {
469       strcpy (qp, "ip6.int");
470       n = __libc_res_nquery (&_res, qbuf, C_IN, T_PTR, host_buffer.buf->buf,
471                              host_buffer.buf != orig_host_buffer
472                              ? MAXPACKET : 1024, &host_buffer.ptr,
473                              NULL, NULL, NULL);
474     }
475   if (n < 0)
476     {
477       *h_errnop = h_errno;
478       __set_errno (olderr);
479       if (host_buffer.buf != orig_host_buffer)
480         free (host_buffer.buf);
481       return errno == ECONNREFUSED ? NSS_STATUS_UNAVAIL : NSS_STATUS_NOTFOUND;
482     }
483
484  got_it_already:
485   status = getanswer_r (host_buffer.buf, n, qbuf, T_PTR, result, buffer, buflen,
486                         errnop, h_errnop, 0 /* XXX */, ttlp, NULL);
487   if (host_buffer.buf != orig_host_buffer)
488     free (host_buffer.buf);
489   if (status != NSS_STATUS_SUCCESS)
490     return status;
491
492 #ifdef SUNSECURITY
493   This is not implemented because it is not possible to use the current
494   source from bind in a multi-threaded program.
495 #endif
496
497   result->h_addrtype = af;
498   result->h_length = len;
499   memcpy (host_data->host_addr, addr, len);
500   host_data->h_addr_ptrs[0] = (char *) host_data->host_addr;
501   host_data->h_addr_ptrs[1] = NULL;
502 #if 0
503   /* XXX I think this is wrong.  Why should an IPv4 address be
504      converted to IPv6 if the user explicitly asked for IPv4?  */
505   if (af == AF_INET && (_res.options & RES_USE_INET6))
506     {
507       map_v4v6_address ((char *) host_data->host_addr,
508                         (char *) host_data->host_addr);
509       result->h_addrtype = AF_INET6;
510       result->h_length = IN6ADDRSZ;
511     }
512 #endif
513   *h_errnop = NETDB_SUCCESS;
514   return NSS_STATUS_SUCCESS;
515 }
516 hidden_def (_nss_dns_gethostbyaddr2_r)
517
518
519 enum nss_status
520 _nss_dns_gethostbyaddr_r (const void *addr, socklen_t len, int af,
521                           struct hostent *result, char *buffer, size_t buflen,
522                           int *errnop, int *h_errnop)
523 {
524   return _nss_dns_gethostbyaddr2_r (addr, len, af, result, buffer, buflen,
525                                     errnop, h_errnop, NULL);
526 }
527
528 #ifdef RESOLVSORT
529 static void addrsort (char **ap, int num);
530
531 static void
532 addrsort (char **ap, int num)
533 {
534   int i, j;
535   char **p;
536   short aval[MAX_NR_ADDRS];
537   int needsort = 0;
538
539   p = ap;
540   if (num > MAX_NR_ADDRS)
541     num = MAX_NR_ADDRS;
542   for (i = 0; i < num; i++, p++)
543     {
544       for (j = 0 ; (unsigned)j < _res.nsort; j++)
545         if (_res.sort_list[j].addr.s_addr ==
546             (((struct in_addr *)(*p))->s_addr & _res.sort_list[j].mask))
547           break;
548       aval[i] = j;
549       if (needsort == 0 && i > 0 && j < aval[i-1])
550         needsort = i;
551     }
552   if (!needsort)
553     return;
554
555   while (needsort++ < num)
556     for (j = needsort - 2; j >= 0; j--)
557       if (aval[j] > aval[j+1])
558         {
559           char *hp;
560
561           i = aval[j];
562           aval[j] = aval[j+1];
563           aval[j+1] = i;
564
565           hp = ap[j];
566           ap[j] = ap[j+1];
567           ap[j+1] = hp;
568         }
569       else
570         break;
571 }
572 #endif
573
574 static enum nss_status
575 getanswer_r (const querybuf *answer, int anslen, const char *qname, int qtype,
576              struct hostent *result, char *buffer, size_t buflen,
577              int *errnop, int *h_errnop, int map, int32_t *ttlp, char **canonp)
578 {
579   struct host_data
580   {
581     char *aliases[MAX_NR_ALIASES];
582     unsigned char host_addr[16];        /* IPv4 or IPv6 */
583     char *h_addr_ptrs[0];
584   } *host_data;
585   int linebuflen;
586   register const HEADER *hp;
587   const u_char *end_of_message, *cp;
588   int n, ancount, qdcount;
589   int haveanswer, had_error;
590   char *bp, **ap, **hap;
591   char tbuf[MAXDNAME];
592   const char *tname;
593   int (*name_ok) (const char *);
594   u_char packtmp[NS_MAXCDNAME];
595   int have_to_map = 0;
596   int32_t ttl = 0;
597   uintptr_t pad = -(uintptr_t) buffer % __alignof__ (struct host_data);
598   buffer += pad;
599   if (__builtin_expect (buflen < sizeof (struct host_data) + pad, 0))
600     {
601       /* The buffer is too small.  */
602     too_small:
603       *errnop = ERANGE;
604       *h_errnop = NETDB_INTERNAL;
605       return NSS_STATUS_TRYAGAIN;
606     }
607   host_data = (struct host_data *) buffer;
608   linebuflen = buflen - sizeof (struct host_data);
609   if (buflen - sizeof (struct host_data) != linebuflen)
610     linebuflen = INT_MAX;
611
612   tname = qname;
613   result->h_name = NULL;
614   end_of_message = answer->buf + anslen;
615   switch (qtype)
616     {
617     case T_A:
618     case T_AAAA:
619       name_ok = res_hnok;
620       break;
621     case T_PTR:
622       name_ok = res_dnok;
623       break;
624     default:
625       *errnop = ENOENT;
626       return NSS_STATUS_UNAVAIL;  /* XXX should be abort(); */
627     }
628
629   /*
630    * find first satisfactory answer
631    */
632   hp = &answer->hdr;
633   ancount = ntohs (hp->ancount);
634   qdcount = ntohs (hp->qdcount);
635   cp = answer->buf + HFIXEDSZ;
636   if (__builtin_expect (qdcount, 1) != 1)
637     {
638       *h_errnop = NO_RECOVERY;
639       return NSS_STATUS_UNAVAIL;
640     }
641   if (sizeof (struct host_data) + (ancount + 1) * sizeof (char *) >= buflen)
642     goto too_small;
643   bp = (char *) &host_data->h_addr_ptrs[ancount + 1];
644   linebuflen -= (ancount + 1) * sizeof (char *);
645
646   n = __ns_name_unpack (answer->buf, end_of_message, cp,
647                         packtmp, sizeof packtmp);
648   if (n != -1 && __ns_name_ntop (packtmp, bp, linebuflen) == -1)
649     {
650       if (__builtin_expect (errno, 0) == EMSGSIZE)
651         goto too_small;
652
653       n = -1;
654     }
655
656   if (n > 0 && bp[0] == '.')
657     bp[0] = '\0';
658
659   if (__builtin_expect (n < 0 || ((*name_ok) (bp) == 0 && (errno = EBADMSG)),
660                         0))
661     {
662       *errnop = errno;
663       *h_errnop = NO_RECOVERY;
664       return NSS_STATUS_UNAVAIL;
665     }
666   cp += n + QFIXEDSZ;
667
668   if (qtype == T_A || qtype == T_AAAA)
669     {
670       /* res_send() has already verified that the query name is the
671        * same as the one we sent; this just gets the expanded name
672        * (i.e., with the succeeding search-domain tacked on).
673        */
674       n = strlen (bp) + 1;             /* for the \0 */
675       if (n >= MAXHOSTNAMELEN)
676         {
677           *h_errnop = NO_RECOVERY;
678           *errnop = ENOENT;
679           return NSS_STATUS_TRYAGAIN;
680         }
681       result->h_name = bp;
682       bp += n;
683       linebuflen -= n;
684       if (linebuflen < 0)
685         goto too_small;
686       /* The qname can be abbreviated, but h_name is now absolute. */
687       qname = result->h_name;
688     }
689
690   ap = host_data->aliases;
691   *ap = NULL;
692   result->h_aliases = host_data->aliases;
693   hap = host_data->h_addr_ptrs;
694   *hap = NULL;
695   result->h_addr_list = host_data->h_addr_ptrs;
696   haveanswer = 0;
697   had_error = 0;
698
699   while (ancount-- > 0 && cp < end_of_message && had_error == 0)
700     {
701       int type, class;
702
703       n = __ns_name_unpack (answer->buf, end_of_message, cp,
704                             packtmp, sizeof packtmp);
705       if (n != -1 && __ns_name_ntop (packtmp, bp, linebuflen) == -1)
706         {
707           if (__builtin_expect (errno, 0) == EMSGSIZE)
708             goto too_small;
709
710           n = -1;
711         }
712
713       if (__builtin_expect (n < 0 || (*name_ok) (bp) == 0, 0))
714         {
715           ++had_error;
716           continue;
717         }
718       cp += n;                          /* name */
719
720       if (__builtin_expect (cp + 10 > end_of_message, 0))
721         {
722           ++had_error;
723           continue;
724         }
725
726       type = __ns_get16 (cp);
727       cp += INT16SZ;                    /* type */
728       class = __ns_get16 (cp);
729       cp += INT16SZ;                    /* class */
730       ttl = __ns_get32 (cp);
731       cp += INT32SZ;                    /* TTL */
732       n = __ns_get16 (cp);
733       cp += INT16SZ;                    /* len */
734       if (__builtin_expect (class != C_IN, 0))
735         {
736           /* XXX - debug? syslog? */
737           cp += n;
738           continue;                     /* XXX - had_error++ ? */
739         }
740
741       if ((qtype == T_A || qtype == T_AAAA) && type == T_CNAME)
742         {
743           if (ap >= &host_data->aliases[MAX_NR_ALIASES - 1])
744             continue;
745           n = dn_expand (answer->buf, end_of_message, cp, tbuf, sizeof tbuf);
746           if (__builtin_expect (n < 0 || (*name_ok) (tbuf) == 0, 0))
747             {
748               ++had_error;
749               continue;
750             }
751           cp += n;
752           /* Store alias.  */
753           *ap++ = bp;
754           n = strlen (bp) + 1;          /* For the \0.  */
755           if (__builtin_expect (n, 0) >= MAXHOSTNAMELEN)
756             {
757               ++had_error;
758               continue;
759             }
760           bp += n;
761           linebuflen -= n;
762           /* Get canonical name.  */
763           n = strlen (tbuf) + 1;        /* For the \0.  */
764           if (__builtin_expect (n > linebuflen, 0))
765             goto too_small;
766           if (__builtin_expect (n, 0) >= MAXHOSTNAMELEN)
767             {
768               ++had_error;
769               continue;
770             }
771           result->h_name = bp;
772           bp = __mempcpy (bp, tbuf, n); /* Cannot overflow.  */
773           linebuflen -= n;
774           continue;
775         }
776
777       if (qtype == T_PTR && type == T_CNAME)
778         {
779           n = dn_expand (answer->buf, end_of_message, cp, tbuf, sizeof tbuf);
780           if (__builtin_expect (n < 0 || res_dnok (tbuf) == 0, 0))
781             {
782               ++had_error;
783               continue;
784             }
785           cp += n;
786           /* Get canonical name.  */
787           n = strlen (tbuf) + 1;   /* For the \0.  */
788           if (__builtin_expect (n > linebuflen, 0))
789             goto too_small;
790           if (__builtin_expect (n, 0) >= MAXHOSTNAMELEN)
791             {
792               ++had_error;
793               continue;
794             }
795           tname = bp;
796           bp = __mempcpy (bp, tbuf, n); /* Cannot overflow.  */
797           linebuflen -= n;
798           continue;
799         }
800       if (__builtin_expect (type == T_SIG, 0)
801           || __builtin_expect (type == T_KEY, 0)
802           || __builtin_expect (type == T_NXT, 0))
803         {
804           /* We don't support DNSSEC yet.  For now, ignore the record
805              and send a low priority message to syslog.  */
806           syslog (LOG_DEBUG | LOG_AUTH,
807                "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
808                   qname, p_class (C_IN), p_type(qtype), p_type (type));
809           cp += n;
810           continue;
811         }
812
813       if (type == T_A && qtype == T_AAAA && map)
814         have_to_map = 1;
815       else if (__builtin_expect (type != qtype, 0))
816         {
817           syslog (LOG_NOTICE | LOG_AUTH,
818                "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
819                   qname, p_class (C_IN), p_type (qtype), p_type (type));
820           cp += n;
821           continue;                     /* XXX - had_error++ ? */
822         }
823
824       switch (type)
825         {
826         case T_PTR:
827           if (__builtin_expect (strcasecmp (tname, bp) != 0, 0))
828             {
829               syslog (LOG_NOTICE | LOG_AUTH, AskedForGot, qname, bp);
830               cp += n;
831               continue;                 /* XXX - had_error++ ? */
832             }
833
834           n = __ns_name_unpack (answer->buf, end_of_message, cp,
835                                 packtmp, sizeof packtmp);
836           if (n != -1 && __ns_name_ntop (packtmp, bp, linebuflen) == -1)
837             {
838               if (__builtin_expect (errno, 0) == EMSGSIZE)
839                 goto too_small;
840
841               n = -1;
842             }
843
844           if (__builtin_expect (n < 0 || res_hnok (bp) == 0, 0))
845             {
846               ++had_error;
847               break;
848             }
849 #if MULTI_PTRS_ARE_ALIASES
850           cp += n;
851           if (haveanswer == 0)
852             result->h_name = bp;
853           else if (ap < &host_data->aliases[MAXALIASES-1])
854             *ap++ = bp;
855           else
856             n = -1;
857           if (n != -1)
858             {
859               n = strlen (bp) + 1;      /* for the \0 */
860               if (__builtin_expect (n, 0) >= MAXHOSTNAMELEN)
861                 {
862                   ++had_error;
863                   break;
864                 }
865               bp += n;
866               linebuflen -= n;
867             }
868           break;
869 #else
870           result->h_name = bp;
871           if (have_to_map)
872             {
873               n = strlen (bp) + 1;      /* for the \0 */
874               if (__builtin_expect (n >= MAXHOSTNAMELEN, 0))
875                 {
876                   ++had_error;
877                   break;
878                 }
879               bp += n;
880               linebuflen -= n;
881               map_v4v6_hostent (result, &bp, &linebuflen);
882             }
883           *h_errnop = NETDB_SUCCESS;
884           return NSS_STATUS_SUCCESS;
885 #endif
886         case T_A:
887         case T_AAAA:
888           if (__builtin_expect (strcasecmp (result->h_name, bp), 0) != 0)
889             {
890               syslog (LOG_NOTICE | LOG_AUTH, AskedForGot, result->h_name, bp);
891               cp += n;
892               continue;                 /* XXX - had_error++ ? */
893             }
894           if (n != result->h_length)
895             {
896               cp += n;
897               continue;
898             }
899           if (!haveanswer)
900             {
901               register int nn;
902
903               if (ttlp != NULL && ttl != 0)
904                 *ttlp = ttl;
905               if (canonp != NULL)
906                 *canonp = bp;
907               result->h_name = bp;
908               nn = strlen (bp) + 1;     /* for the \0 */
909               bp += nn;
910               linebuflen -= nn;
911             }
912
913           linebuflen -= sizeof (align) - ((u_long) bp % sizeof (align));
914           bp += sizeof (align) - ((u_long) bp % sizeof (align));
915
916           if (__builtin_expect (n > linebuflen, 0))
917             goto too_small;
918           bp = __mempcpy (*hap++ = bp, cp, n);
919           cp += n;
920           linebuflen -= n;
921           break;
922         default:
923           abort ();
924         }
925       if (had_error == 0)
926         ++haveanswer;
927     }
928
929   if (haveanswer > 0)
930     {
931       *ap = NULL;
932       *hap = NULL;
933 #if defined RESOLVSORT
934       /*
935        * Note: we sort even if host can take only one address
936        * in its return structures - should give it the "best"
937        * address in that case, not some random one
938        */
939       if (_res.nsort && haveanswer > 1 && qtype == T_A)
940         addrsort (host_data->h_addr_ptrs, haveanswer);
941 #endif /*RESOLVSORT*/
942
943       if (result->h_name == NULL)
944         {
945           n = strlen (qname) + 1;       /* For the \0.  */
946           if (n > linebuflen)
947             goto too_small;
948           if (n >= MAXHOSTNAMELEN)
949             goto no_recovery;
950           result->h_name = bp;
951           bp = __mempcpy (bp, qname, n);        /* Cannot overflow.  */
952           linebuflen -= n;
953         }
954
955       if (have_to_map)
956         map_v4v6_hostent (result, &bp, &linebuflen);
957       *h_errnop = NETDB_SUCCESS;
958       return NSS_STATUS_SUCCESS;
959     }
960  no_recovery:
961   *h_errnop = NO_RECOVERY;
962   *errnop = ENOENT;
963   /* Special case here: if the resolver sent a result but it only
964      contains a CNAME while we are looking for a T_A or T_AAAA record,
965      we fail with NOTFOUND instead of TRYAGAIN.  */
966   return ((qtype == T_A || qtype == T_AAAA) && ap != host_data->aliases
967            ? NSS_STATUS_NOTFOUND : NSS_STATUS_TRYAGAIN);
968 }
969
970
971 static enum nss_status
972 gaih_getanswer_slice (const querybuf *answer, int anslen, const char *qname,
973                       struct gaih_addrtuple ***patp,
974                       char **bufferp, size_t *buflenp,
975                       int *errnop, int *h_errnop, int32_t *ttlp, int *firstp)
976 {
977   char *buffer = *bufferp;
978   size_t buflen = *buflenp;
979
980   struct gaih_addrtuple **pat = *patp;
981   const HEADER *hp = &answer->hdr;
982   int ancount = ntohs (hp->ancount);
983   int qdcount = ntohs (hp->qdcount);
984   const u_char *cp = answer->buf + HFIXEDSZ;
985   const u_char *end_of_message = answer->buf + anslen;
986   if (__builtin_expect (qdcount != 1, 0))
987     {
988       *h_errnop = NO_RECOVERY;
989       return NSS_STATUS_UNAVAIL;
990     }
991
992   u_char packtmp[NS_MAXCDNAME];
993   int n = __ns_name_unpack (answer->buf, end_of_message, cp,
994                             packtmp, sizeof packtmp);
995   /* We unpack the name to check it for validity.  But we do not need
996      it later.  */
997   if (n != -1 && __ns_name_ntop (packtmp, buffer, buflen) == -1)
998     {
999       if (__builtin_expect (errno, 0) == EMSGSIZE)
1000         {
1001         too_small:
1002           *errnop = ERANGE;
1003           *h_errnop = NETDB_INTERNAL;
1004           return NSS_STATUS_TRYAGAIN;
1005         }
1006
1007       n = -1;
1008     }
1009
1010   if (__builtin_expect (n < 0 || (res_hnok (buffer) == 0
1011                                   && (errno = EBADMSG)), 0))
1012     {
1013       *errnop = errno;
1014       *h_errnop = NO_RECOVERY;
1015       return NSS_STATUS_UNAVAIL;
1016     }
1017   cp += n + QFIXEDSZ;
1018
1019   int haveanswer = 0;
1020   int had_error = 0;
1021   char *canon = NULL;
1022   char *h_name = NULL;
1023   int h_namelen = 0;
1024
1025   if (ancount == 0)
1026     return NSS_STATUS_NOTFOUND;
1027
1028   while (ancount-- > 0 && cp < end_of_message && had_error == 0)
1029     {
1030       n = __ns_name_unpack (answer->buf, end_of_message, cp,
1031                             packtmp, sizeof packtmp);
1032       if (n != -1 &&
1033           (h_namelen = __ns_name_ntop (packtmp, buffer, buflen)) == -1)
1034         {
1035           if (__builtin_expect (errno, 0) == EMSGSIZE)
1036             goto too_small;
1037
1038           n = -1;
1039         }
1040       if (__builtin_expect (n < 0 || res_hnok (buffer) == 0, 0))
1041         {
1042           ++had_error;
1043           continue;
1044         }
1045       if (*firstp)
1046         {
1047           h_name = buffer;
1048           buffer += h_namelen;
1049           buflen -= h_namelen;
1050         }
1051
1052       cp += n;                          /* name */
1053
1054       if (__builtin_expect (cp + 10 > end_of_message, 0))
1055         {
1056           ++had_error;
1057           continue;
1058         }
1059
1060       int type = __ns_get16 (cp);
1061       cp += INT16SZ;                    /* type */
1062       int class = __ns_get16 (cp);
1063       cp += INT16SZ;                    /* class */
1064       int32_t ttl = __ns_get32 (cp);
1065       cp += INT32SZ;                    /* TTL */
1066       n = __ns_get16 (cp);
1067       cp += INT16SZ;                    /* len */
1068
1069       if (class != C_IN)
1070         {
1071           cp += n;
1072           continue;
1073         }
1074
1075       if (type == T_CNAME)
1076         {
1077           char tbuf[MAXDNAME];
1078           n = dn_expand (answer->buf, end_of_message, cp, tbuf, sizeof tbuf);
1079           if (__builtin_expect (n < 0 || res_hnok (tbuf) == 0, 0))
1080             {
1081               ++had_error;
1082               continue;
1083             }
1084           cp += n;
1085
1086           if (*firstp)
1087             {
1088               /* Reclaim buffer space.  */
1089               if (h_name + h_namelen == buffer)
1090                 {
1091                   buffer = h_name;
1092                   buflen += h_namelen;
1093                 }
1094
1095               n = strlen (tbuf) + 1;
1096               if (__builtin_expect (n > buflen, 0))
1097                 goto too_small;
1098               if (__builtin_expect (n >= MAXHOSTNAMELEN, 0))
1099                 {
1100                   ++had_error;
1101                   continue;
1102                 }
1103
1104               canon = buffer;
1105               buffer = __mempcpy (buffer, tbuf, n);
1106               buflen -= n;
1107               h_namelen = 0;
1108             }
1109           continue;
1110         }
1111 #if 1
1112       // We should not see any types other than those explicitly listed
1113       // below.  Some types sent by server seem missing, though.  Just
1114       // collect the data for now.
1115       if (__builtin_expect (type != T_A && type != T_AAAA, 0))
1116 #else
1117       if (__builtin_expect (type == T_SIG, 0)
1118           || __builtin_expect (type == T_KEY, 0)
1119           || __builtin_expect (type == T_NXT, 0)
1120           || __builtin_expect (type == T_PTR, 0)
1121           || __builtin_expect (type == T_DNAME, 0))
1122 #endif
1123         {
1124           /* We don't support DNSSEC yet.  For now, ignore the record
1125              and send a low priority message to syslog.
1126
1127              We also don't expect T_PTR or T_DNAME messages.  */
1128           syslog (LOG_DEBUG | LOG_AUTH,
1129                   "getaddrinfo*.gaih_getanswer: got type \"%s\"",
1130                   p_type (type));
1131           cp += n;
1132           continue;
1133         }
1134       if (type != T_A && type != T_AAAA)
1135         abort ();
1136
1137       if (*pat == NULL)
1138         {
1139           uintptr_t pad = (-(uintptr_t) buffer
1140                            % __alignof__ (struct gaih_addrtuple));
1141           buffer += pad;
1142           buflen = buflen > pad ? buflen - pad : 0;
1143
1144           if (__builtin_expect (buflen < sizeof (struct gaih_addrtuple),
1145                                 0))
1146             goto too_small;
1147
1148           *pat = (struct gaih_addrtuple *) buffer;
1149           buffer += sizeof (struct gaih_addrtuple);
1150           buflen -= sizeof (struct gaih_addrtuple);
1151         }
1152
1153       (*pat)->name = NULL;
1154       (*pat)->next = NULL;
1155
1156       if (*firstp)
1157         {
1158           if (ttl != 0 && ttlp != NULL)
1159             *ttlp = ttl;
1160
1161           if (canon != NULL)
1162             {
1163               (*pat)->name = canon;
1164
1165               /* Reclaim buffer space.  */
1166               if (h_name + h_namelen == buffer)
1167                 {
1168                   buffer = h_name;
1169                   buflen += h_namelen;
1170                 }
1171             }
1172           else
1173             (*pat)->name = h_name;
1174
1175           *firstp = 0;
1176         }
1177
1178       (*pat)->family = type == T_A ? AF_INET : AF_INET6;
1179       if (__builtin_expect ((type == T_A && n != INADDRSZ)
1180                             || (type == T_AAAA && n != IN6ADDRSZ), 0))
1181         {
1182           ++had_error;
1183           continue;
1184         }
1185       memcpy ((*pat)->addr, cp, n);
1186       cp += n;
1187       (*pat)->scopeid = 0;
1188
1189       pat = &((*pat)->next);
1190
1191       haveanswer = 1;
1192     }
1193
1194   if (haveanswer)
1195     {
1196       *patp = pat;
1197       *bufferp = buffer;
1198       *buflenp = buflen;
1199
1200       *h_errnop = NETDB_SUCCESS;
1201       return NSS_STATUS_SUCCESS;
1202     }
1203
1204   /* Special case here: if the resolver sent a result but it only
1205      contains a CNAME while we are looking for a T_A or T_AAAA record,
1206      we fail with NOTFOUND instead of TRYAGAIN.  */
1207   return canon == NULL ? NSS_STATUS_TRYAGAIN : NSS_STATUS_NOTFOUND;
1208 }
1209
1210
1211 static enum nss_status
1212 gaih_getanswer (const querybuf *answer1, int anslen1, const querybuf *answer2,
1213                 int anslen2, const char *qname,
1214                 struct gaih_addrtuple **pat, char *buffer, size_t buflen,
1215                 int *errnop, int *h_errnop, int32_t *ttlp)
1216 {
1217   int first = 1;
1218
1219   enum nss_status status = NSS_STATUS_NOTFOUND;
1220
1221   if (anslen1 > 0)
1222     status = gaih_getanswer_slice(answer1, anslen1, qname,
1223                                   &pat, &buffer, &buflen,
1224                                   errnop, h_errnop, ttlp,
1225                                   &first);
1226   if ((status == NSS_STATUS_SUCCESS || status == NSS_STATUS_NOTFOUND
1227        || (status == NSS_STATUS_TRYAGAIN
1228            && (errno != ERANGE || *h_errnop != NO_RECOVERY)))
1229       && answer2 != NULL && anslen2 > 0)
1230     {
1231       enum nss_status status2 = gaih_getanswer_slice(answer2, anslen2, qname,
1232                                                      &pat, &buffer, &buflen,
1233                                                      errnop, h_errnop, ttlp,
1234                                                      &first);
1235       if (status != NSS_STATUS_SUCCESS && status2 != NSS_STATUS_NOTFOUND)
1236         status = status2;
1237     }
1238
1239   return status;
1240 }