update from main archive 970218
[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                                 if (!strchr(name, ':'))
517                                         break;
518                                 /*
519                                  * All-IPv6-legal, no dot at the end.
520                                  * Fake up a hostent as if we'd actually
521                                  * done a lookup.
522                                  */
523                                 if (inet_pton(af, name, host_addr) <= 0) {
524                                         __set_h_errno (HOST_NOT_FOUND);
525                                         return (NULL);
526                                 }
527                                 strncpy(hostbuf, name, MAXDNAME);
528                                 hostbuf[MAXDNAME] = '\0';
529                                 bp = hostbuf + MAXDNAME;
530                                 len = sizeof hostbuf - MAXDNAME;
531                                 host.h_name = hostbuf;
532                                 host.h_aliases = host_aliases;
533                                 host_aliases[0] = NULL;
534                                 h_addr_ptrs[0] = (char *)host_addr;
535                                 h_addr_ptrs[1] = NULL;
536                                 host.h_addr_list = h_addr_ptrs;
537                                 __set_h_errno (NETDB_SUCCESS);
538                                 return (&host);
539                         }
540                         if (!isxdigit(*cp) && *cp != ':' && *cp != '.')
541                                 break;
542                 }
543
544         if ((n = res_search(name, C_IN, type, buf.buf, sizeof(buf.buf))) < 0) {
545                 dprintf("res_search failed (%d)\n", n);
546                 if (errno == ECONNREFUSED)
547                         return (_gethtbyname2(name, af));
548                 return (NULL);
549         }
550         return (getanswer(&buf, n, name, type));
551 }
552
553 struct hostent *
554 gethostbyaddr(addr, len, af)
555         const char *addr;       /* XXX should have been def'd as u_char! */
556         int len, af;
557 {
558         const u_char *uaddr = (const u_char *)addr;
559         static const u_char mapped[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
560         static const u_char tunnelled[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0,0 };
561         int n, size;
562         querybuf buf;
563         register struct hostent *hp;
564         char qbuf[MAXDNAME+1], *qp;
565 #ifdef SUNSECURITY
566         register struct hostent *rhp;
567         char **haddr;
568         u_long old_options;
569         char hname2[MAXDNAME+1];
570 #endif /*SUNSECURITY*/
571         extern struct hostent *_gethtbyaddr();
572
573         if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
574                 __set_h_errno (NETDB_INTERNAL);
575                 return (NULL);
576         }
577         if (af == AF_INET6 && len == IN6ADDRSZ &&
578             (!bcmp(uaddr, mapped, sizeof mapped) ||
579              !bcmp(uaddr, tunnelled, sizeof tunnelled))) {
580                 /* Unmap. */
581                 addr += sizeof mapped;
582                 uaddr += sizeof mapped;
583                 af = AF_INET;
584                 len = INADDRSZ;
585         }
586         switch (af) {
587         case AF_INET:
588                 size = INADDRSZ;
589                 break;
590         case AF_INET6:
591                 size = IN6ADDRSZ;
592                 break;
593         default:
594                 __set_errno (EAFNOSUPPORT);
595                 __set_h_errno (NETDB_INTERNAL);
596                 return (NULL);
597         }
598         if (size != len) {
599                 __set_errno (EINVAL);
600                 __set_h_errno (NETDB_INTERNAL);
601                 return (NULL);
602         }
603         switch (af) {
604         case AF_INET:
605                 (void) sprintf(qbuf, "%u.%u.%u.%u.in-addr.arpa",
606                                (uaddr[3] & 0xff),
607                                (uaddr[2] & 0xff),
608                                (uaddr[1] & 0xff),
609                                (uaddr[0] & 0xff));
610                 break;
611         case AF_INET6:
612                 qp = qbuf;
613                 for (n = IN6ADDRSZ - 1; n >= 0; n--) {
614                         qp += SPRINTF((qp, "%x.%x.",
615                                        uaddr[n] & 0xf,
616                                        (uaddr[n] >> 4) & 0xf));
617                 }
618                 strcpy(qp, "ip6.int");
619                 break;
620         default:
621                 abort();
622         }
623         n = res_query(qbuf, C_IN, T_PTR, (u_char *)buf.buf, sizeof buf.buf);
624         if (n < 0) {
625                 dprintf("res_query failed (%d)\n", n);
626                 if (errno == ECONNREFUSED)
627                         return (_gethtbyaddr(addr, len, af));
628                 return (NULL);
629         }
630         if (!(hp = getanswer(&buf, n, qbuf, T_PTR)))
631                 return (NULL);  /* h_errno was set by getanswer() */
632 #ifdef SUNSECURITY
633         if (af == AF_INET) {
634             /*
635              * turn off search as the name should be absolute,
636              * 'localhost' should be matched by defnames
637              */
638             strncpy(hname2, hp->h_name, MAXDNAME);
639             hname2[MAXDNAME] = '\0';
640             old_options = _res.options;
641             _res.options &= ~RES_DNSRCH;
642             _res.options |= RES_DEFNAMES;
643             if (!(rhp = gethostbyname(hname2))) {
644                 syslog(LOG_NOTICE|LOG_AUTH,
645                        "gethostbyaddr: No A record for %s (verifying [%s])",
646                        hname2, inet_ntoa(*((struct in_addr *)addr)));
647                 _res.options = old_options;
648                 __set_h_errno (HOST_NOT_FOUND);
649                 return (NULL);
650             }
651             _res.options = old_options;
652             for (haddr = rhp->h_addr_list; *haddr; haddr++)
653                 if (!memcmp(*haddr, addr, INADDRSZ))
654                         break;
655             if (!*haddr) {
656                 syslog(LOG_NOTICE|LOG_AUTH,
657                        "gethostbyaddr: A record of %s != PTR record [%s]",
658                        hname2, inet_ntoa(*((struct in_addr *)addr)));
659                 __set_h_errno (HOST_NOT_FOUND);
660                 return (NULL);
661             }
662         }
663 #endif /*SUNSECURITY*/
664         hp->h_addrtype = af;
665         hp->h_length = len;
666         bcopy(addr, host_addr, len);
667         h_addr_ptrs[0] = (char *)host_addr;
668         h_addr_ptrs[1] = NULL;
669         if (af == AF_INET && (_res.options & RES_USE_INET6)) {
670                 map_v4v6_address((char*)host_addr, (char*)host_addr);
671                 hp->h_addrtype = AF_INET6;
672                 hp->h_length = IN6ADDRSZ;
673         }
674         __set_h_errno (NETDB_SUCCESS);
675         return (hp);
676 }
677
678 void
679 _sethtent(f)
680         int f;
681 {
682         if (!hostf)
683                 hostf = fopen(_PATH_HOSTS, "r" );
684         else
685                 rewind(hostf);
686         stayopen = f;
687 }
688
689 void
690 _endhtent()
691 {
692         if (hostf && !stayopen) {
693                 (void) fclose(hostf);
694                 hostf = NULL;
695         }
696 }
697
698 struct hostent *
699 _gethtent()
700 {
701         char *p;
702         register char *cp, **q;
703         int af, len;
704
705         if (!hostf && !(hostf = fopen(_PATH_HOSTS, "r" ))) {
706                 __set_h_errno (NETDB_INTERNAL);
707                 return (NULL);
708         }
709  again:
710         if (!(p = fgets(hostbuf, sizeof hostbuf, hostf))) {
711                 __set_h_errno (HOST_NOT_FOUND);
712                 return (NULL);
713         }
714         if (*p == '#')
715                 goto again;
716         if (!(cp = strpbrk(p, "#\n")))
717                 goto again;
718         *cp = '\0';
719         if (!(cp = strpbrk(p, " \t")))
720                 goto again;
721         *cp++ = '\0';
722         if ((_res.options & RES_USE_INET6) &&
723             inet_pton(AF_INET6, p, host_addr) > 0) {
724                 af = AF_INET6;
725                 len = IN6ADDRSZ;
726         } else if (inet_pton(AF_INET, p, host_addr) > 0) {
727                 if (_res.options & RES_USE_INET6) {
728                         map_v4v6_address((char*)host_addr, (char*)host_addr);
729                         af = AF_INET6;
730                         len = IN6ADDRSZ;
731                 } else {
732                         af = AF_INET;
733                         len = INADDRSZ;
734                 }
735         } else {
736                 goto again;
737         }
738         h_addr_ptrs[0] = (char *)host_addr;
739         h_addr_ptrs[1] = NULL;
740         host.h_addr_list = h_addr_ptrs;
741         host.h_length = len;
742         host.h_addrtype = af;
743         while (*cp == ' ' || *cp == '\t')
744                 cp++;
745         host.h_name = cp;
746         q = host.h_aliases = host_aliases;
747         if (cp = strpbrk(cp, " \t"))
748                 *cp++ = '\0';
749         while (cp && *cp) {
750                 if (*cp == ' ' || *cp == '\t') {
751                         cp++;
752                         continue;
753                 }
754                 if (q < &host_aliases[MAXALIASES - 1])
755                         *q++ = cp;
756                 if (cp = strpbrk(cp, " \t"))
757                         *cp++ = '\0';
758         }
759         *q = NULL;
760         if (_res.options & RES_USE_INET6) {
761                 char *bp = hostbuf;
762                 int buflen = sizeof hostbuf;
763
764                 map_v4v6_hostent(&host, &bp, &buflen);
765         }
766         __set_h_errno (NETDB_SUCCESS);
767         return (&host);
768 }
769
770 struct hostent *
771 _gethtbyname(name)
772         const char *name;
773 {
774         extern struct hostent *_gethtbyname2();
775         struct hostent *hp;
776
777         if (_res.options & RES_USE_INET6) {
778                 hp = _gethtbyname2(name, AF_INET6);
779                 if (hp)
780                         return (hp);
781         }
782         return (_gethtbyname2(name, AF_INET));
783 }
784
785 struct hostent *
786 _gethtbyname2(name, af)
787         const char *name;
788         int af;
789 {
790         register struct hostent *p;
791         register char **cp;
792
793         _sethtent(0);
794         while (p = _gethtent()) {
795                 if (p->h_addrtype != af)
796                         continue;
797                 if (strcasecmp(p->h_name, name) == 0)
798                         break;
799                 for (cp = p->h_aliases; *cp != 0; cp++)
800                         if (strcasecmp(*cp, name) == 0)
801                                 goto found;
802         }
803  found:
804         _endhtent();
805         return (p);
806 }
807
808 struct hostent *
809 _gethtbyaddr(addr, len, af)
810         const char *addr;
811         int len, af;
812 {
813         register struct hostent *p;
814
815         _sethtent(0);
816         while (p = _gethtent())
817                 if (p->h_addrtype == af && !bcmp(p->h_addr, addr, len))
818                         break;
819         _endhtent();
820         return (p);
821 }
822
823 static void
824 map_v4v6_address(src, dst)
825         const char *src;
826         char *dst;
827 {
828         u_char *p = (u_char *)dst;
829         char tmp[INADDRSZ];
830         int i;
831
832         /* Stash a temporary copy so our caller can update in place. */
833         bcopy(src, tmp, INADDRSZ);
834         /* Mark this ipv6 addr as a mapped ipv4. */
835         for (i = 0; i < 10; i++)
836                 *p++ = 0x00;
837         *p++ = 0xff;
838         *p++ = 0xff;
839         /* Retrieve the saved copy and we're done. */
840         bcopy(tmp, (void*)p, INADDRSZ);
841 }
842
843 static void
844 map_v4v6_hostent(hp, bpp, lenp)
845         struct hostent *hp;
846         char **bpp;
847         int *lenp;
848 {
849         char **ap;
850
851         if (hp->h_addrtype != AF_INET || hp->h_length != INADDRSZ)
852                 return;
853         hp->h_addrtype = AF_INET6;
854         hp->h_length = IN6ADDRSZ;
855         for (ap = hp->h_addr_list; *ap; ap++) {
856                 int i = sizeof(align) - ((u_long)*bpp % sizeof(align));
857
858                 if (*lenp < (i + IN6ADDRSZ)) {
859                         /* Out of memory.  Truncate address list here.  XXX */
860                         *ap = NULL;
861                         return;
862                 }
863                 *bpp += i;
864                 *lenp -= i;
865                 map_v4v6_address(*ap, *bpp);
866                 *ap = *bpp;
867                 *bpp += IN6ADDRSZ;
868                 *lenp -= IN6ADDRSZ;
869         }
870 }
871
872 #ifdef RESOLVSORT
873 static void
874 addrsort(ap, num)
875         char **ap;
876         int num;
877 {
878         int i, j;
879         char **p;
880         short aval[MAXADDRS];
881         int needsort = 0;
882
883         p = ap;
884         for (i = 0; i < num; i++, p++) {
885             for (j = 0 ; (unsigned)j < _res.nsort; j++)
886                 if (_res.sort_list[j].addr.s_addr ==
887                     (((struct in_addr *)(*p))->s_addr & _res.sort_list[j].mask))
888                         break;
889             aval[i] = j;
890             if (needsort == 0 && i > 0 && j < aval[i-1])
891                 needsort = i;
892         }
893         if (!needsort)
894             return;
895
896         while (needsort < num) {
897             for (j = needsort - 1; j >= 0; j--) {
898                 if (aval[j] > aval[j+1]) {
899                     char *hp;
900
901                     i = aval[j];
902                     aval[j] = aval[j+1];
903                     aval[j+1] = i;
904
905                     hp = ap[j];
906                     ap[j] = ap[j+1];
907                     ap[j+1] = hp;
908
909                 } else
910                     break;
911             }
912             needsort++;
913         }
914 }
915 #endif
916
917 #if defined(BSD43_BSD43_NFS) || defined(sun)
918 /* some libc's out there are bound internally to these names (UMIPS) */
919 void
920 ht_sethostent(stayopen)
921         int stayopen;
922 {
923         _sethtent(stayopen);
924 }
925
926 void
927 ht_endhostent()
928 {
929         _endhtent();
930 }
931
932 struct hostent *
933 ht_gethostbyname(name)
934         char *name;
935 {
936         return (_gethtbyname(name));
937 }
938
939 struct hostent *
940 ht_gethostbyaddr(addr, len, af)
941         const char *addr;
942         int len, af;
943 {
944         return (_gethtbyaddr(addr, len, af));
945 }
946
947 struct hostent *
948 gethostent()
949 {
950         return (_gethtent());
951 }
952
953 void
954 dns_service()
955 {
956         return;
957 }
958
959 #undef dn_skipname
960 dn_skipname(comp_dn, eom)
961         const u_char *comp_dn, *eom;
962 {
963         return (__dn_skipname(comp_dn, eom));
964 }
965 #endif /*old-style libc with yp junk in it*/