(_res_opcodes): Remove.
[kopensolaris-gnu/glibc.git] / resolv / gethnamaddr.c
1 /*
2  * ++Copyright++ 1985, 1988, 1993
3  * -
4  * Copyright (c) 1985, 1988, 1993
5  *    The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 4. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  * -
31  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
32  *
33  * Permission to use, copy, modify, and distribute this software for any
34  * purpose with or without fee is hereby granted, provided that the above
35  * copyright notice and this permission notice appear in all copies, and that
36  * the name of Digital Equipment Corporation not be used in advertising or
37  * publicity pertaining to distribution of the document or software without
38  * specific, written prior permission.
39  *
40  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
41  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
43  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
44  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
45  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
46  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
47  * SOFTWARE.
48  * -
49  * --Copyright--
50  */
51
52 #if defined(LIBC_SCCS) && !defined(lint)
53 static char sccsid[] = "@(#)gethostnamadr.c     8.1 (Berkeley) 6/4/93";
54 static char rcsid[] = "$Id$";
55 #endif /* LIBC_SCCS and not lint */
56
57 #include <sys/types.h>
58 #include <sys/param.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
61 #include <arpa/inet.h>
62 #include <arpa/nameser.h>
63
64 #include <stdio.h>
65 #include <netdb.h>
66 #include <resolv.h>
67 #include <ctype.h>
68 #include <errno.h>
69 #include <syslog.h>
70
71 #define RESOLVSORT
72
73 #ifndef LOG_AUTH
74 # define LOG_AUTH 0
75 #endif
76
77 #define MULTI_PTRS_ARE_ALIASES 1        /* XXX - experimental */
78
79 #if defined(BSD) && (BSD >= 199103) && defined(AF_INET6)
80 # include <stdlib.h>
81 # include <string.h>
82 #else
83 # include "../conf/portability.h"
84 #endif
85
86 #if defined(USE_OPTIONS_H)
87 # include <../conf/options.h>
88 #endif
89
90 #ifdef SPRINTF_CHAR
91 # define SPRINTF(x) strlen(sprintf/**/x)
92 #else
93 # define SPRINTF(x) ((size_t)sprintf x)
94 #endif
95
96 #define MAXALIASES      35
97 #define MAXADDRS        35
98
99 static const char AskedForGot[] =
100                           "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
101
102 static char *h_addr_ptrs[MAXADDRS + 1];
103
104 static struct hostent host;
105 static char *host_aliases[MAXALIASES];
106 static char hostbuf[8*1024];
107 static u_char host_addr[16];    /* IPv4 or IPv6 */
108 static FILE *hostf = NULL;
109 static int stayopen = 0;
110
111 static void map_v4v6_address (const char *src, char *dst) __THROW;
112 static void map_v4v6_hostent (struct hostent *hp, char **bp, int *len) __THROW;
113
114 #ifdef RESOLVSORT
115 extern void addrsort (char **, int) __THROW;
116 #endif
117
118 #if PACKETSZ > 65536
119 #define MAXPACKET       PACKETSZ
120 #else
121 #define MAXPACKET       65536
122 #endif
123
124 /* As per RFC 1034 and 1035 a host name cannot exceed 255 octets in length.  */
125 #ifdef MAXHOSTNAMELEN
126 # undef MAXHOSTNAMELEN
127 #endif
128 #define MAXHOSTNAMELEN 256
129
130 typedef union {
131     HEADER hdr;
132     u_char buf[MAXPACKET];
133 } querybuf;
134
135 typedef union {
136     int32_t al;
137     char ac;
138 } align;
139
140 #ifndef h_errno
141 extern int h_errno;
142 #endif
143
144 #ifdef DEBUG
145 static void
146 Dprintf(msg, num)
147         char *msg;
148         int num;
149 {
150         if (_res.options & RES_DEBUG) {
151                 int save = errno;
152
153                 printf(msg, num);
154                 __set_errno (save);
155         }
156 }
157 #else
158 # define Dprintf(msg, num) /*nada*/
159 #endif
160
161 #define BOUNDED_INCR(x) \
162         do { \
163                 cp += x; \
164                 if (cp > eom) { \
165                         __set_h_errno (NO_RECOVERY); \
166                         return (NULL); \
167                 } \
168         } while (0)
169
170 #define BOUNDS_CHECK(ptr, count) \
171         do { \
172                 if ((ptr) + (count) > eom) { \
173                         __set_h_errno (NO_RECOVERY); \
174                         return (NULL); \
175                 } \
176         } while (0)
177
178
179 static struct hostent *
180 getanswer(answer, anslen, qname, qtype)
181         const querybuf *answer;
182         int anslen;
183         const char *qname;
184         int qtype;
185 {
186         register const HEADER *hp;
187         register const u_char *cp;
188         register int n;
189         const u_char *eom, *erdata;
190         char *bp, **ap, **hap;
191         int type, class, buflen, ancount, qdcount;
192         int haveanswer, had_error;
193         int toobig = 0;
194         char tbuf[MAXDNAME];
195         const char *tname;
196         int (*name_ok) (const char *);
197
198         tname = qname;
199         host.h_name = NULL;
200         eom = answer->buf + anslen;
201         switch (qtype) {
202         case T_A:
203         case T_AAAA:
204                 name_ok = res_hnok;
205                 break;
206         case T_PTR:
207                 name_ok = res_dnok;
208                 break;
209         default:
210                 return (NULL);  /* XXX should be abort(); */
211         }
212         /*
213          * find first satisfactory answer
214          */
215         hp = &answer->hdr;
216         ancount = ntohs(hp->ancount);
217         qdcount = ntohs(hp->qdcount);
218         bp = hostbuf;
219         buflen = sizeof hostbuf;
220         cp = answer->buf;
221         BOUNDED_INCR(HFIXEDSZ);
222         if (qdcount != 1) {
223                 __set_h_errno (NO_RECOVERY);
224                 return (NULL);
225         }
226         n = dn_expand(answer->buf, eom, cp, bp, buflen);
227         if ((n < 0) || !(*name_ok)(bp)) {
228                 __set_h_errno (NO_RECOVERY);
229                 return (NULL);
230         }
231         BOUNDED_INCR(n + QFIXEDSZ);
232         if (qtype == T_A || qtype == T_AAAA) {
233                 /* res_send() has already verified that the query name is the
234                  * same as the one we sent; this just gets the expanded name
235                  * (i.e., with the succeeding search-domain tacked on).
236                  */
237                 n = strlen(bp) + 1;             /* for the \0 */
238                 if (n >= MAXHOSTNAMELEN) {
239                         __set_h_errno (NO_RECOVERY);
240                         return (NULL);
241                 }
242                 host.h_name = bp;
243                 bp += n;
244                 buflen -= n;
245                 /* The qname can be abbreviated, but h_name is now absolute. */
246                 qname = host.h_name;
247         }
248         ap = host_aliases;
249         *ap = NULL;
250         host.h_aliases = host_aliases;
251         hap = h_addr_ptrs;
252         *hap = NULL;
253         host.h_addr_list = h_addr_ptrs;
254         haveanswer = 0;
255         had_error = 0;
256         while (ancount-- > 0 && cp < eom && !had_error) {
257                 n = dn_expand(answer->buf, eom, cp, bp, buflen);
258                 if ((n < 0) || !(*name_ok)(bp)) {
259                         had_error++;
260                         continue;
261                 }
262                 cp += n;                        /* name */
263                 BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
264                 type = ns_get16(cp);
265                 cp += INT16SZ;                  /* type */
266                 class = ns_get16(cp);
267                 cp += INT16SZ + INT32SZ;        /* class, TTL */
268                 n = ns_get16(cp);
269                 cp += INT16SZ;                  /* len */
270                 BOUNDS_CHECK(cp, n);
271                 erdata = cp + n;
272                 if (class != C_IN) {
273                         /* XXX - debug? syslog? */
274                         cp += n;
275                         continue;               /* XXX - had_error++ ? */
276                 }
277                 if ((qtype == T_A || qtype == T_AAAA) && type == T_CNAME) {
278                         if (ap >= &host_aliases[MAXALIASES-1])
279                                 continue;
280                         n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
281                         if ((n < 0) || !(*name_ok)(tbuf)) {
282                                 had_error++;
283                                 continue;
284                         }
285                         cp += n;
286                         if (cp != erdata) {
287                                 __set_h_errno (NO_RECOVERY);
288                                 return (NULL);
289                         }
290                         /* Store alias. */
291                         *ap++ = bp;
292                         n = strlen(bp) + 1;     /* for the \0 */
293                         if (n >= MAXHOSTNAMELEN) {
294                                 had_error++;
295                                 continue;
296                         }
297                         bp += n;
298                         buflen -= n;
299                         /* Get canonical name. */
300                         n = strlen(tbuf) + 1;   /* for the \0 */
301                         if (n > buflen || n >= MAXHOSTNAMELEN) {
302                                 had_error++;
303                                 continue;
304                         }
305                         strcpy(bp, tbuf);
306                         host.h_name = bp;
307                         bp += n;
308                         buflen -= n;
309                         continue;
310                 }
311                 if (qtype == T_PTR && type == T_CNAME) {
312                         n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
313                         if (n < 0 || !res_dnok(tbuf)) {
314                                 had_error++;
315                                 continue;
316                         }
317                         cp += n;
318                         if (cp != erdata) {
319                                 __set_h_errno (NO_RECOVERY);
320                                 return (NULL);
321                         }
322                         /* Get canonical name. */
323                         n = strlen(tbuf) + 1;   /* for the \0 */
324                         if (n > buflen || n >= MAXHOSTNAMELEN) {
325                                 had_error++;
326                                 continue;
327                         }
328                         strcpy(bp, tbuf);
329                         tname = bp;
330                         bp += n;
331                         buflen -= n;
332                         continue;
333                 }
334                 if ((type == T_SIG) || (type == T_KEY) || (type == T_NXT)) {
335                         /* We don't support DNSSEC yet.  For now, ignore
336                          * the record and send a low priority message
337                          * to syslog.
338                          */
339                         syslog(LOG_DEBUG|LOG_AUTH,
340                "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
341                                qname, p_class(C_IN), p_type(qtype),
342                                p_type(type));
343                         cp += n;
344                         continue;
345                 }
346                 if (type != qtype) {
347                         syslog(LOG_NOTICE|LOG_AUTH,
348                "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
349                                qname, p_class(C_IN), p_type(qtype),
350                                p_type(type));
351                         cp += n;
352                         continue;               /* XXX - had_error++ ? */
353                 }
354                 switch (type) {
355                 case T_PTR:
356                         if (strcasecmp(tname, bp) != 0) {
357                                 syslog(LOG_NOTICE|LOG_AUTH,
358                                        AskedForGot, qname, bp);
359                                 cp += n;
360                                 continue;       /* XXX - had_error++ ? */
361                         }
362                         n = dn_expand(answer->buf, eom, cp, bp, buflen);
363                         if ((n < 0) || !res_hnok(bp)) {
364                                 had_error++;
365                                 break;
366                         }
367 #if MULTI_PTRS_ARE_ALIASES
368                         cp += n;
369                         if (cp != erdata) {
370                                 __set_h_errno (NO_RECOVERY);
371                                 return (NULL);
372                         }
373                         if (!haveanswer)
374                                 host.h_name = bp;
375                         else if (ap < &host_aliases[MAXALIASES-1])
376                                 *ap++ = bp;
377                         else
378                                 n = -1;
379                         if (n != -1) {
380                                 n = strlen(bp) + 1;     /* for the \0 */
381                                 if (n >= MAXHOSTNAMELEN) {
382                                         had_error++;
383                                         break;
384                                 }
385                                 bp += n;
386                                 buflen -= n;
387                         }
388                         break;
389 #else
390                         host.h_name = bp;
391                         if (_res.options & RES_USE_INET6) {
392                                 n = strlen(bp) + 1;     /* for the \0 */
393                                 if (n >= MAXHOSTNAMELEN) {
394                                         had_error++;
395                                         break;
396                                 }
397                                 bp += n;
398                                 buflen -= n;
399                                 map_v4v6_hostent(&host, &bp, &buflen);
400                         }
401                         __set_h_errno (NETDB_SUCCESS);
402                         return (&host);
403 #endif
404                 case T_A:
405                 case T_AAAA:
406                         if (strcasecmp(host.h_name, bp) != 0) {
407                                 syslog(LOG_NOTICE|LOG_AUTH,
408                                        AskedForGot, host.h_name, bp);
409                                 cp += n;
410                                 continue;       /* XXX - had_error++ ? */
411                         }
412                         if (n != host.h_length) {
413                                 cp += n;
414                                 continue;
415                         }
416                         if (!haveanswer) {
417                                 register int nn;
418
419                                 host.h_name = bp;
420                                 nn = strlen(bp) + 1;    /* for the \0 */
421                                 bp += nn;
422                                 buflen -= nn;
423                         }
424
425                         /* XXX: when incrementing bp, we have to decrement
426                          * buflen by the same amount --okir */
427                         buflen -= sizeof(align) - ((u_long)bp % sizeof(align));
428
429                         bp += sizeof(align) - ((u_long)bp % sizeof(align));
430
431                         if (bp + n >= &hostbuf[sizeof hostbuf]) {
432                                 Dprintf("size (%d) too big\n", n);
433                                 had_error++;
434                                 continue;
435                         }
436                         if (hap >= &h_addr_ptrs[MAXADDRS-1]) {
437                                 if (!toobig++) {
438                                         Dprintf("Too many addresses (%d)\n",
439                                                 MAXADDRS);
440                                 }
441                                 cp += n;
442                                 continue;
443                         }
444                         memmove(*hap++ = bp, cp, n);
445                         bp += n;
446                         buflen -= n;
447                         cp += n;
448                         if (cp != erdata) {
449                                 __set_h_errno (NO_RECOVERY);
450                                 return (NULL);
451                         }
452                         break;
453                 default:
454                         abort();
455                 }
456                 if (!had_error)
457                         haveanswer++;
458         }
459         if (haveanswer) {
460                 *ap = NULL;
461                 *hap = NULL;
462 # if defined(RESOLVSORT)
463                 /*
464                  * Note: we sort even if host can take only one address
465                  * in its return structures - should give it the "best"
466                  * address in that case, not some random one
467                  */
468                 if (_res.nsort && haveanswer > 1 && qtype == T_A)
469                         addrsort(h_addr_ptrs, haveanswer);
470 # endif /*RESOLVSORT*/
471                 if (!host.h_name) {
472                         n = strlen(qname) + 1;  /* for the \0 */
473                         if (n > buflen || n >= MAXHOSTNAMELEN)
474                                 goto no_recovery;
475                         strcpy(bp, qname);
476                         host.h_name = bp;
477                         bp += n;
478                         buflen -= n;
479                 }
480                 if (_res.options & RES_USE_INET6)
481                         map_v4v6_hostent(&host, &bp, &buflen);
482                 __set_h_errno (NETDB_SUCCESS);
483                 return (&host);
484         }
485  no_recovery:
486         __set_h_errno (NO_RECOVERY);
487         return (NULL);
488 }
489
490 extern struct hostent *gethostbyname2(const char *name, int af);
491 libresolv_hidden_proto (gethostbyname2)
492
493 struct hostent *
494 gethostbyname(name)
495         const char *name;
496 {
497         struct hostent *hp;
498
499         if (__res_maybe_init (&_res, 0) == -1) {
500                 __set_h_errno (NETDB_INTERNAL);
501                 return (NULL);
502         }
503         if (_res.options & RES_USE_INET6) {
504                 hp = gethostbyname2(name, AF_INET6);
505                 if (hp)
506                         return (hp);
507         }
508         return (gethostbyname2(name, AF_INET));
509 }
510
511 struct hostent *
512 gethostbyname2(name, af)
513         const char *name;
514         int af;
515 {
516         union
517         {
518           querybuf *buf;
519           u_char *ptr;
520         } buf;
521         querybuf *origbuf;
522         register const char *cp;
523         char *bp;
524         int n, size, type, len;
525         struct hostent *ret;
526         extern struct hostent *_gethtbyname2();
527
528         if (__res_maybe_init (&_res, 0) == -1) {
529                 __set_h_errno (NETDB_INTERNAL);
530                 return (NULL);
531         }
532
533         switch (af) {
534         case AF_INET:
535                 size = INADDRSZ;
536                 type = T_A;
537                 break;
538         case AF_INET6:
539                 size = IN6ADDRSZ;
540                 type = T_AAAA;
541                 break;
542         default:
543                 __set_h_errno (NETDB_INTERNAL);
544                 __set_errno (EAFNOSUPPORT);
545                 return (NULL);
546         }
547
548         host.h_addrtype = af;
549         host.h_length = size;
550
551         /*
552          * if there aren't any dots, it could be a user-level alias.
553          * this is also done in res_query() since we are not the only
554          * function that looks up host names.
555          */
556         if (!strchr(name, '.') && (cp = __hostalias(name)))
557                 name = cp;
558
559         /*
560          * disallow names consisting only of digits/dots, unless
561          * they end in a dot.
562          */
563         if (isdigit(name[0]))
564                 for (cp = name;; ++cp) {
565                         if (!*cp) {
566                                 if (*--cp == '.')
567                                         break;
568                                 /*
569                                  * All-numeric, no dot at the end.
570                                  * Fake up a hostent as if we'd actually
571                                  * done a lookup.
572                                  */
573                                 if (inet_pton(af, name, host_addr) <= 0) {
574                                         __set_h_errno (HOST_NOT_FOUND);
575                                         return (NULL);
576                                 }
577                                 strncpy(hostbuf, name, MAXDNAME);
578                                 hostbuf[MAXDNAME] = '\0';
579                                 bp = hostbuf + MAXDNAME;
580                                 len = sizeof hostbuf - MAXDNAME;
581                                 host.h_name = hostbuf;
582                                 host.h_aliases = host_aliases;
583                                 host_aliases[0] = NULL;
584                                 h_addr_ptrs[0] = (char *)host_addr;
585                                 h_addr_ptrs[1] = NULL;
586                                 host.h_addr_list = h_addr_ptrs;
587                                 if (_res.options & RES_USE_INET6)
588                                         map_v4v6_hostent(&host, &bp, &len);
589                                 __set_h_errno (NETDB_SUCCESS);
590                                 return (&host);
591                         }
592                         if (!isdigit(*cp) && *cp != '.')
593                                 break;
594                }
595         if ((isxdigit(name[0]) && strchr(name, ':') != NULL) ||
596             name[0] == ':')
597                 for (cp = name;; ++cp) {
598                         if (!*cp) {
599                                 if (*--cp == '.')
600                                         break;
601                                 /*
602                                  * All-IPv6-legal, no dot at the end.
603                                  * Fake up a hostent as if we'd actually
604                                  * done a lookup.
605                                  */
606                                 if (inet_pton(af, name, host_addr) <= 0) {
607                                         __set_h_errno (HOST_NOT_FOUND);
608                                         return (NULL);
609                                 }
610                                 strncpy(hostbuf, name, MAXDNAME);
611                                 hostbuf[MAXDNAME] = '\0';
612                                 bp = hostbuf + MAXDNAME;
613                                 len = sizeof hostbuf - MAXDNAME;
614                                 host.h_name = hostbuf;
615                                 host.h_aliases = host_aliases;
616                                 host_aliases[0] = NULL;
617                                 h_addr_ptrs[0] = (char *)host_addr;
618                                 h_addr_ptrs[1] = NULL;
619                                 host.h_addr_list = h_addr_ptrs;
620                                 __set_h_errno (NETDB_SUCCESS);
621                                 return (&host);
622                         }
623                         if (!isxdigit(*cp) && *cp != ':' && *cp != '.')
624                                 break;
625                 }
626
627         buf.buf = origbuf = (querybuf *) alloca (1024);
628
629         if ((n = __libc_res_nsearch(&_res, name, C_IN, type, buf.buf->buf, 1024,
630                                     &buf.ptr)) < 0) {
631                 if (buf.buf != origbuf)
632                         free (buf.buf);
633                 Dprintf("res_nsearch failed (%d)\n", n);
634                 if (errno == ECONNREFUSED)
635                         return (_gethtbyname2(name, af));
636                 return (NULL);
637         }
638         ret = getanswer(buf.buf, n, name, type);
639         if (buf.buf != origbuf)
640                 free (buf.buf);
641         return ret;
642 }
643 libresolv_hidden_def (gethostbyname2)
644
645 struct hostent *
646 gethostbyaddr(addr, len, af)
647         const void *addr;
648         socklen_t len;
649         int af;
650 {
651         const u_char *uaddr = (const u_char *)addr;
652         static const u_char mapped[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
653         static const u_char tunnelled[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0,0 };
654         int n;
655         socklen_t size;
656         union
657         {
658           querybuf *buf;
659           u_char *ptr;
660         } buf;
661         querybuf *orig_buf;
662         register struct hostent *hp;
663         char qbuf[MAXDNAME+1], *qp = NULL;
664 #ifdef SUNSECURITY
665         register struct hostent *rhp;
666         char **haddr;
667         u_long old_options;
668         char hname2[MAXDNAME+1];
669 #endif /*SUNSECURITY*/
670         extern struct hostent *_gethtbyaddr();
671
672         if (__res_maybe_init (&_res, 0) == -1) {
673                 __set_h_errno (NETDB_INTERNAL);
674                 return (NULL);
675         }
676         if (af == AF_INET6 && len == IN6ADDRSZ &&
677             (!bcmp(uaddr, mapped, sizeof mapped) ||
678              !bcmp(uaddr, tunnelled, sizeof tunnelled))) {
679                 /* Unmap. */
680                 addr += sizeof mapped;
681                 uaddr += sizeof mapped;
682                 af = AF_INET;
683                 len = INADDRSZ;
684         }
685         switch (af) {
686         case AF_INET:
687                 size = INADDRSZ;
688                 break;
689         case AF_INET6:
690                 size = IN6ADDRSZ;
691                 break;
692         default:
693                 __set_errno (EAFNOSUPPORT);
694                 __set_h_errno (NETDB_INTERNAL);
695                 return (NULL);
696         }
697         if (size != len) {
698                 __set_errno (EINVAL);
699                 __set_h_errno (NETDB_INTERNAL);
700                 return (NULL);
701         }
702         switch (af) {
703         case AF_INET:
704                 (void) sprintf(qbuf, "%u.%u.%u.%u.in-addr.arpa",
705                                (uaddr[3] & 0xff),
706                                (uaddr[2] & 0xff),
707                                (uaddr[1] & 0xff),
708                                (uaddr[0] & 0xff));
709                 break;
710         case AF_INET6:
711                 qp = qbuf;
712                 for (n = IN6ADDRSZ - 1; n >= 0; n--) {
713                         qp += SPRINTF((qp, "%x.%x.",
714                                        uaddr[n] & 0xf,
715                                        (uaddr[n] >> 4) & 0xf));
716                 }
717                 strcpy(qp, "ip6.arpa");
718                 break;
719         default:
720                 abort();
721         }
722
723         buf.buf = orig_buf = (querybuf *) alloca (1024);
724
725         n = __libc_res_nquery(&_res, qbuf, C_IN, T_PTR, buf.buf->buf, 1024,
726                               &buf.ptr);
727         if (n < 0 && af == AF_INET6 && (_res.options & RES_NOIP6DOTINT) == 0) {
728                 strcpy(qp, "ip6.int");
729                 n = __libc_res_nquery(&_res, qbuf, C_IN, T_PTR, buf.buf->buf,
730                                       buf.buf != orig_buf ? MAXPACKET : 1024,
731                                       &buf.ptr);
732         }
733         if (n < 0) {
734                 if (buf.buf != orig_buf)
735                         free (buf.buf);
736                 Dprintf("res_nquery failed (%d)\n", n);
737                 if (errno == ECONNREFUSED)
738                         return (_gethtbyaddr(addr, len, af));
739                 return (NULL);
740         }
741         hp = getanswer(buf.buf, n, qbuf, T_PTR);
742         if (buf.buf != orig_buf)
743                 free (buf.buf);
744         if (!hp)
745                 return (NULL);  /* h_errno was set by getanswer() */
746 #ifdef SUNSECURITY
747         if (af == AF_INET) {
748             /*
749              * turn off search as the name should be absolute,
750              * 'localhost' should be matched by defnames
751              */
752             strncpy(hname2, hp->h_name, MAXDNAME);
753             hname2[MAXDNAME] = '\0';
754             old_options = _res.options;
755             _res.options &= ~RES_DNSRCH;
756             _res.options |= RES_DEFNAMES;
757             if (!(rhp = gethostbyname(hname2))) {
758                 syslog(LOG_NOTICE|LOG_AUTH,
759                        "gethostbyaddr: No A record for %s (verifying [%s])",
760                        hname2, inet_ntoa(*((struct in_addr *)addr)));
761                 _res.options = old_options;
762                 __set_h_errno (HOST_NOT_FOUND);
763                 return (NULL);
764             }
765             _res.options = old_options;
766             for (haddr = rhp->h_addr_list; *haddr; haddr++)
767                 if (!memcmp(*haddr, addr, INADDRSZ))
768                         break;
769             if (!*haddr) {
770                 syslog(LOG_NOTICE|LOG_AUTH,
771                        "gethostbyaddr: A record of %s != PTR record [%s]",
772                        hname2, inet_ntoa(*((struct in_addr *)addr)));
773                 __set_h_errno (HOST_NOT_FOUND);
774                 return (NULL);
775             }
776         }
777 #endif /*SUNSECURITY*/
778         hp->h_addrtype = af;
779         hp->h_length = len;
780         memmove(host_addr, addr, len);
781         h_addr_ptrs[0] = (char *)host_addr;
782         h_addr_ptrs[1] = NULL;
783         if (af == AF_INET && (_res.options & RES_USE_INET6)) {
784                 map_v4v6_address((char*)host_addr, (char*)host_addr);
785                 hp->h_addrtype = AF_INET6;
786                 hp->h_length = IN6ADDRSZ;
787         }
788         __set_h_errno (NETDB_SUCCESS);
789         return (hp);
790 }
791
792 void
793 _sethtent(f)
794         int f;
795 {
796         if (!hostf)
797                 hostf = fopen(_PATH_HOSTS, "r" );
798         else
799                 rewind(hostf);
800         stayopen = f;
801 }
802 libresolv_hidden_def (_sethtent)
803
804 void
805 _endhtent()
806 {
807         if (hostf && !stayopen) {
808                 (void) fclose(hostf);
809                 hostf = NULL;
810         }
811 }
812
813 struct hostent *
814 _gethtent()
815 {
816         char *p;
817         register char *cp, **q;
818         int af, len;
819
820         if (!hostf && !(hostf = fopen(_PATH_HOSTS, "r" ))) {
821                 __set_h_errno (NETDB_INTERNAL);
822                 return (NULL);
823         }
824  again:
825         if (!(p = fgets(hostbuf, sizeof hostbuf, hostf))) {
826                 __set_h_errno (HOST_NOT_FOUND);
827                 return (NULL);
828         }
829         if (*p == '#')
830                 goto again;
831         if (!(cp = strpbrk(p, "#\n")))
832                 goto again;
833         *cp = '\0';
834         if (!(cp = strpbrk(p, " \t")))
835                 goto again;
836         *cp++ = '\0';
837         if (inet_pton(AF_INET6, p, host_addr) > 0) {
838                 af = AF_INET6;
839                 len = IN6ADDRSZ;
840         } else if (inet_pton(AF_INET, p, host_addr) > 0) {
841                 if (_res.options & RES_USE_INET6) {
842                         map_v4v6_address((char*)host_addr, (char*)host_addr);
843                         af = AF_INET6;
844                         len = IN6ADDRSZ;
845                 } else {
846                         af = AF_INET;
847                         len = INADDRSZ;
848                 }
849         } else {
850                 goto again;
851         }
852         h_addr_ptrs[0] = (char *)host_addr;
853         h_addr_ptrs[1] = NULL;
854         host.h_addr_list = h_addr_ptrs;
855         host.h_length = len;
856         host.h_addrtype = af;
857         while (*cp == ' ' || *cp == '\t')
858                 cp++;
859         host.h_name = cp;
860         q = host.h_aliases = host_aliases;
861         if ((cp = strpbrk(cp, " \t")))
862                 *cp++ = '\0';
863         while (cp && *cp) {
864                 if (*cp == ' ' || *cp == '\t') {
865                         cp++;
866                         continue;
867                 }
868                 if (q < &host_aliases[MAXALIASES - 1])
869                         *q++ = cp;
870                 if ((cp = strpbrk(cp, " \t")))
871                         *cp++ = '\0';
872         }
873         *q = NULL;
874         __set_h_errno (NETDB_SUCCESS);
875         return (&host);
876 }
877 libresolv_hidden_def (_gethtent)
878
879 struct hostent *
880 _gethtbyname(name)
881         const char *name;
882 {
883         extern struct hostent *_gethtbyname2();
884         struct hostent *hp;
885
886         if (_res.options & RES_USE_INET6) {
887                 hp = _gethtbyname2(name, AF_INET6);
888                 if (hp)
889                         return (hp);
890         }
891         return (_gethtbyname2(name, AF_INET));
892 }
893
894 struct hostent *
895 _gethtbyname2(name, af)
896         const char *name;
897         int af;
898 {
899         register struct hostent *p;
900         register char **cp;
901
902         _sethtent(0);
903         while ((p = _gethtent())) {
904                 if (p->h_addrtype != af)
905                         continue;
906                 if (strcasecmp(p->h_name, name) == 0)
907                         break;
908                 for (cp = p->h_aliases; *cp != 0; cp++)
909                         if (strcasecmp(*cp, name) == 0)
910                                 goto found;
911         }
912  found:
913         _endhtent();
914         return (p);
915 }
916 libresolv_hidden_def (_gethtbyname2)
917
918 struct hostent *
919 _gethtbyaddr(addr, len, af)
920         const char *addr;
921         size_t len;
922         int af;
923 {
924         register struct hostent *p;
925
926         _sethtent(0);
927         while ((p = _gethtent()))
928                 if (p->h_addrtype == af && !bcmp(p->h_addr, addr, len))
929                         break;
930         _endhtent();
931         return (p);
932 }
933 libresolv_hidden_def (_gethtbyaddr)
934
935 static void
936 map_v4v6_address(src, dst)
937         const char *src;
938         char *dst;
939 {
940         u_char *p = (u_char *)dst;
941         char tmp[INADDRSZ];
942         int i;
943
944         /* Stash a temporary copy so our caller can update in place. */
945         memcpy(tmp, src, INADDRSZ);
946         /* Mark this ipv6 addr as a mapped ipv4. */
947         for (i = 0; i < 10; i++)
948                 *p++ = 0x00;
949         *p++ = 0xff;
950         *p++ = 0xff;
951         /* Retrieve the saved copy and we're done. */
952         memcpy((void*)p, tmp, INADDRSZ);
953 }
954
955 static void
956 map_v4v6_hostent(hp, bpp, lenp)
957         struct hostent *hp;
958         char **bpp;
959         int *lenp;
960 {
961         char **ap;
962
963         if (hp->h_addrtype != AF_INET || hp->h_length != INADDRSZ)
964                 return;
965         hp->h_addrtype = AF_INET6;
966         hp->h_length = IN6ADDRSZ;
967         for (ap = hp->h_addr_list; *ap; ap++) {
968                 int i = sizeof(align) - ((u_long)*bpp % sizeof(align));
969
970                 if (*lenp < (i + IN6ADDRSZ)) {
971                         /* Out of memory.  Truncate address list here.  XXX */
972                         *ap = NULL;
973                         return;
974                 }
975                 *bpp += i;
976                 *lenp -= i;
977                 map_v4v6_address(*ap, *bpp);
978                 *ap = *bpp;
979                 *bpp += IN6ADDRSZ;
980                 *lenp -= IN6ADDRSZ;
981         }
982 }
983
984 #ifdef RESOLVSORT
985 extern void
986 addrsort(ap, num)
987         char **ap;
988         int num;
989 {
990         int i, j;
991         char **p;
992         short aval[MAXADDRS];
993         int needsort = 0;
994
995         p = ap;
996         for (i = 0; i < num; i++, p++) {
997             for (j = 0 ; (unsigned)j < _res.nsort; j++)
998                 if (_res.sort_list[j].addr.s_addr ==
999                     (((struct in_addr *)(*p))->s_addr & _res.sort_list[j].mask))
1000                         break;
1001             aval[i] = j;
1002             if (needsort == 0 && i > 0 && j < aval[i-1])
1003                 needsort = i;
1004         }
1005         if (!needsort)
1006             return;
1007
1008         while (needsort < num) {
1009             for (j = needsort - 1; j >= 0; j--) {
1010                 if (aval[j] > aval[j+1]) {
1011                     char *hp;
1012
1013                     i = aval[j];
1014                     aval[j] = aval[j+1];
1015                     aval[j+1] = i;
1016
1017                     hp = ap[j];
1018                     ap[j] = ap[j+1];
1019                     ap[j+1] = hp;
1020
1021                 } else
1022                     break;
1023             }
1024             needsort++;
1025         }
1026 }
1027 #endif
1028
1029 #if defined(BSD43_BSD43_NFS) || defined(sun)
1030 /* some libc's out there are bound internally to these names (UMIPS) */
1031 void
1032 ht_sethostent(stayopen)
1033         int stayopen;
1034 {
1035         _sethtent(stayopen);
1036 }
1037
1038 void
1039 ht_endhostent()
1040 {
1041         _endhtent();
1042 }
1043
1044 struct hostent *
1045 ht_gethostbyname(name)
1046         char *name;
1047 {
1048         return (_gethtbyname(name));
1049 }
1050
1051 struct hostent *
1052 ht_gethostbyaddr(addr, len, af)
1053         const char *addr;
1054         size_t len;
1055         int af;
1056 {
1057         return (_gethtbyaddr(addr, len, af));
1058 }
1059
1060 struct hostent *
1061 gethostent()
1062 {
1063         return (_gethtent());
1064 }
1065
1066 void
1067 dns_service()
1068 {
1069         return;
1070 }
1071
1072 #undef dn_skipname
1073 dn_skipname(comp_dn, eom)
1074         const u_char *comp_dn, *eom;
1075 {
1076         return (__dn_skipname(comp_dn, eom));
1077 }
1078 #endif /*old-style libc with yp junk in it*/