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