OSDN Git Service

req_search returned garbage. This teaches it to behave itself and
[uclinux-h8/uClibc.git] / libc / inet / resolv.c
1 /* resolv.c: DNS Resolver
2  *
3  * Copyright (C) 1998  Kenneth Albanowski <kjahds@kjahds.com>,
4  *                     The Silver Hammer Group, Ltd.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10 */
11
12 /*
13  * Portions Copyright (c) 1985, 1993
14  *    The Regents of the University of California.  All rights reserved.
15  * 
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  * 
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40
41 /*
42  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
43  * 
44  * Permission to use, copy, modify, and distribute this software for any
45  * purpose with or without fee is hereby granted, provided that the above
46  * copyright notice and this permission notice appear in all copies, and that
47  * the name of Digital Equipment Corporation not be used in advertising or
48  * publicity pertaining to distribution of the document or software without
49  * specific, written prior permission.
50  * 
51  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
52  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
53  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
54  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
55  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
56  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
57  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
58  * SOFTWARE.
59  */
60
61 /*
62  * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
63  *
64  * Permission to use, copy, modify, and distribute this software for any
65  * purpose with or without fee is hereby granted, provided that the above
66  * copyright notice and this permission notice appear in all copies.
67  *
68  * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
69  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
70  * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
71  * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
72  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
73  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
74  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
75  * SOFTWARE.
76  */
77
78 /*
79  *
80  *  5-Oct-2000 W. Greathouse  wgreathouse@smva.com
81  *                              Fix memory leak and memory corruption.
82  *                              -- Every name resolution resulted in
83  *                                 a new parse of resolv.conf and new
84  *                                 copy of nameservers allocated by
85  *                                 strdup.
86  *                              -- Every name resolution resulted in
87  *                                 a new read of resolv.conf without
88  *                                 resetting index from prior read...
89  *                                 resulting in exceeding array bounds.
90  *
91  *                              Limit nameservers read from resolv.conf
92  *
93  *                              Add "search" domains from resolv.conf
94  *
95  *                              Some systems will return a security
96  *                              signature along with query answer for
97  *                              dynamic DNS entries.
98  *                              -- skip/ignore this answer
99  *
100  *                              Include arpa/nameser.h for defines.
101  *
102  *                              General cleanup
103  *
104  * 20-Jun-2001 Michal Moskal <malekith@pld.org.pl>
105  *   partial IPv6 support (i.e. gethostbyname2() and resolve_address2()
106  *   functions added), IPv6 nameservers are also supported.
107  *
108  * 6-Oct-2001 Jari Korva <jari.korva@iki.fi>
109  *   more IPv6 support (IPv6 support for gethostbyaddr();
110  *   address family parameter and improved IPv6 support for get_hosts_byname
111  *   and read_etc_hosts; getnameinfo() port from glibc; defined
112  *   defined ip6addr_any and in6addr_loopback)
113  *
114  * 2-Feb-2002 Erik Andersen <andersee@debian.org>
115  * Added gethostent(), sethostent(), and endhostent()
116  *
117  * 17-Aug-2002 Manuel Novoa III <mjn3@codepoet.org>
118  *   Fixed __read_etc_hosts_r to return alias list, and modified buffer
119  *   allocation accordingly.  See MAX_ALIASES and ALIAS_DIM below.
120  *   This fixes the segfault in the Python 2.2.1 socket test.
121  *
122  * 04-Jan-2003 Jay Kulpinski <jskulpin@berkshire.rr.com>
123  *   Fixed __decode_dotted to count the terminating null character
124  *   in a host name.
125  *
126  * 02-Oct-2003 Tony J. White <tjw@tjw.org>
127  *   Lifted dn_expand() and dependent ns_name_uncompress(), ns_name_unpack(),
128  *   and ns_name_ntop() from glibc 2.3.2 for compatibility with ipsec-tools 
129  *   and openldap.
130  *
131  */
132
133 #define __FORCE_GLIBC
134 #include <features.h>
135 #include <string.h>
136 #include <stdio.h>
137 #include <signal.h>
138 #include <errno.h>
139 #include <sys/socket.h>
140 #include <sys/types.h>
141 #include <sys/time.h>
142 #include <netinet/in.h>
143 #include <arpa/inet.h>
144 #include <stdlib.h>
145 #include <unistd.h>
146 #include <resolv.h>
147 #include <netdb.h>
148 #include <ctype.h>
149 #include <arpa/nameser.h>
150 #include <sys/utsname.h>
151 #include <sys/un.h>
152
153 #define MAX_RECURSE 5
154 #define REPLY_TIMEOUT 10
155 #define MAX_RETRIES 3
156 #define MAX_SERVERS 3
157 #define MAX_SEARCH 4
158
159 #define MAX_ALIASES     5
160
161 /* 1:ip + 1:full + MAX_ALIASES:aliases + 1:NULL */
162 #define         ALIAS_DIM               (2 + MAX_ALIASES + 1)
163
164 #undef DEBUG
165 /* #define DEBUG */
166
167 #ifdef DEBUG
168 #define DPRINTF(X,args...) fprintf(stderr, X, ##args)
169 #else
170 #define DPRINTF(X,args...)
171 #endif /* DEBUG */
172
173
174 /* Global stuff (stuff needing to be locked to be thread safe)... */
175 extern int __nameservers;
176 extern char * __nameserver[MAX_SERVERS];
177 extern int __searchdomains;
178 extern char * __searchdomain[MAX_SEARCH];
179
180 #ifdef __UCLIBC_HAS_THREADS__
181 #include <pthread.h>
182 extern pthread_mutex_t __resolv_lock;
183 # define BIGLOCK        __pthread_mutex_lock(&__resolv_lock)
184 # define BIGUNLOCK      __pthread_mutex_unlock(&__resolv_lock);
185 #else
186 # define BIGLOCK
187 # define BIGUNLOCK
188 #endif
189
190
191
192 /* Structs */
193 struct resolv_header {
194         int id;
195         int qr,opcode,aa,tc,rd,ra,rcode;
196         int qdcount;
197         int ancount;
198         int nscount;
199         int arcount;
200 };
201
202 struct resolv_question {
203         char * dotted;
204         int qtype;
205         int qclass;
206 };
207
208 struct resolv_answer {
209         char * dotted;
210         int atype;
211         int aclass;
212         int ttl;
213         int rdlength;
214         unsigned char * rdata;
215         int rdoffset;
216 };
217
218 enum etc_hosts_action {
219     GET_HOSTS_BYNAME = 0,
220     GETHOSTENT,
221     GET_HOSTS_BYADDR,
222 };
223
224 /* function prototypes */
225 extern int __get_hosts_byname_r(const char * name, int type,
226                               struct hostent * result_buf,
227                               char * buf, size_t buflen,
228                               struct hostent ** result,
229                               int * h_errnop);
230 extern int __get_hosts_byaddr_r(const char * addr, int len, int type,
231                               struct hostent * result_buf,
232                               char * buf, size_t buflen,
233                               struct hostent ** result,
234                               int * h_errnop);
235 extern void __open_etc_hosts(FILE **fp);
236 extern int __read_etc_hosts_r(FILE *fp, const char * name, int type,
237                             enum etc_hosts_action action,
238                             struct hostent * result_buf,
239                             char * buf, size_t buflen,
240                             struct hostent ** result,
241                             int * h_errnop);
242 extern int __dns_lookup(const char * name, int type, int nscount, 
243         char ** nsip, unsigned char ** outpacket, struct resolv_answer * a);
244
245 extern int __encode_dotted(const char * dotted, unsigned char * dest, int maxlen);
246 extern int __decode_dotted(const unsigned char * message, int offset, 
247         char * dest, int maxlen);
248 extern int __length_dotted(const unsigned char * message, int offset);
249 extern int __encode_header(struct resolv_header * h, unsigned char * dest, int maxlen);
250 extern int __decode_header(unsigned char * data, struct resolv_header * h);
251 extern int __encode_question(struct resolv_question * q,
252         unsigned char * dest, int maxlen);
253 extern int __decode_question(unsigned char * message, int offset,
254         struct resolv_question * q);
255 extern int __encode_answer(struct resolv_answer * a,
256         unsigned char * dest, int maxlen);
257 extern int __decode_answer(unsigned char * message, int offset,
258         struct resolv_answer * a);
259 extern int __length_question(unsigned char * message, int offset);
260 extern int __open_nameservers(void);
261 extern void __close_nameservers(void);
262 extern int __dn_expand(const u_char *, const u_char *, const u_char *,
263         char *, int);
264 extern int __ns_name_uncompress(const u_char *, const u_char *, 
265                 const u_char *, char *, size_t);
266 extern int __ns_name_ntop(const u_char *, char *, size_t);
267 extern int __ns_name_unpack(const u_char *, const u_char *, const u_char *,
268                u_char *, size_t);
269
270
271 #ifdef L_encodeh
272 int __encode_header(struct resolv_header *h, unsigned char *dest, int maxlen)
273 {
274         if (maxlen < HFIXEDSZ)
275                 return -1;
276
277         dest[0] = (h->id & 0xff00) >> 8;
278         dest[1] = (h->id & 0x00ff) >> 0;
279         dest[2] = (h->qr ? 0x80 : 0) |
280                 ((h->opcode & 0x0f) << 3) |
281                 (h->aa ? 0x04 : 0) | 
282                 (h->tc ? 0x02 : 0) | 
283                 (h->rd ? 0x01 : 0);
284         dest[3] = (h->ra ? 0x80 : 0) | (h->rcode & 0x0f);
285         dest[4] = (h->qdcount & 0xff00) >> 8;
286         dest[5] = (h->qdcount & 0x00ff) >> 0;
287         dest[6] = (h->ancount & 0xff00) >> 8;
288         dest[7] = (h->ancount & 0x00ff) >> 0;
289         dest[8] = (h->nscount & 0xff00) >> 8;
290         dest[9] = (h->nscount & 0x00ff) >> 0;
291         dest[10] = (h->arcount & 0xff00) >> 8;
292         dest[11] = (h->arcount & 0x00ff) >> 0;
293
294         return HFIXEDSZ;
295 }
296 #endif
297
298 #ifdef L_decodeh
299 int __decode_header(unsigned char *data, struct resolv_header *h)
300 {
301         h->id = (data[0] << 8) | data[1];
302         h->qr = (data[2] & 0x80) ? 1 : 0;
303         h->opcode = (data[2] >> 3) & 0x0f;
304         h->aa = (data[2] & 0x04) ? 1 : 0;
305         h->tc = (data[2] & 0x02) ? 1 : 0;
306         h->rd = (data[2] & 0x01) ? 1 : 0;
307         h->ra = (data[3] & 0x80) ? 1 : 0;
308         h->rcode = data[3] & 0x0f;
309         h->qdcount = (data[4] << 8) | data[5];
310         h->ancount = (data[6] << 8) | data[7];
311         h->nscount = (data[8] << 8) | data[9];
312         h->arcount = (data[10] << 8) | data[11];
313
314         return HFIXEDSZ;
315 }
316 #endif
317
318 #ifdef L_encoded
319 /* Encode a dotted string into nameserver transport-level encoding.
320    This routine is fairly dumb, and doesn't attempt to compress
321    the data */
322
323 int __encode_dotted(const char *dotted, unsigned char *dest, int maxlen)
324 {
325         int used = 0;
326
327         while (dotted && *dotted) {
328                 char *c = strchr(dotted, '.');
329                 int l = c ? c - dotted : strlen(dotted);
330
331                 if (l >= (maxlen - used - 1))
332                         return -1;
333
334                 dest[used++] = l;
335                 memcpy(dest + used, dotted, l);
336                 used += l;
337
338                 if (c)
339                         dotted = c + 1;
340                 else
341                         break;
342         }
343
344         if (maxlen < 1)
345                 return -1;
346
347         dest[used++] = 0;
348
349         return used;
350 }
351 #endif
352
353 #ifdef L_decoded
354 /* Decode a dotted string from nameserver transport-level encoding.
355    This routine understands compressed data. */
356
357 int __decode_dotted(const unsigned char *data, int offset,
358                                   char *dest, int maxlen)
359 {
360         int l;
361         int measure = 1;
362         int total = 0;
363         int used = 0;
364
365         if (!data)
366                 return -1;
367
368         while ((l=data[offset++])) {
369                 if (measure)
370                     total++;
371                 if ((l & 0xc0) == (0xc0)) {
372                         if (measure)
373                                 total++;
374                         /* compressed item, redirect */
375                         offset = ((l & 0x3f) << 8) | data[offset];
376                         measure = 0;
377                         continue;
378                 }
379
380                 if ((used + l + 1) >= maxlen)
381                         return -1;
382
383                 memcpy(dest + used, data + offset, l);
384                 offset += l;
385                 used += l;
386                 if (measure)
387                         total += l;
388
389                 if (data[offset] != 0)
390                         dest[used++] = '.';
391                 else
392                         dest[used++] = '\0';
393         }
394
395         /* The null byte must be counted too */
396         if (measure) {
397             total++;
398         }
399
400         DPRINTF("Total decode len = %d\n", total);
401
402         return total;
403 }
404 #endif
405
406 #ifdef L_lengthd
407
408 int __length_dotted(const unsigned char *data, int offset)
409 {
410         int orig_offset = offset;
411         int l;
412
413         if (!data)
414                 return -1;
415
416         while ((l = data[offset++])) {
417
418                 if ((l & 0xc0) == (0xc0)) {
419                         offset++;
420                         break;
421                 }
422
423                 offset += l;
424         }
425
426         return offset - orig_offset;
427 }
428 #endif
429
430 #ifdef L_encodeq
431 int __encode_question(struct resolv_question *q,
432                                         unsigned char *dest, int maxlen)
433 {
434         int i;
435
436         i = __encode_dotted(q->dotted, dest, maxlen);
437         if (i < 0)
438                 return i;
439
440         dest += i;
441         maxlen -= i;
442
443         if (maxlen < 4)
444                 return -1;
445
446         dest[0] = (q->qtype & 0xff00) >> 8;
447         dest[1] = (q->qtype & 0x00ff) >> 0;
448         dest[2] = (q->qclass & 0xff00) >> 8;
449         dest[3] = (q->qclass & 0x00ff) >> 0;
450
451         return i + 4;
452 }
453 #endif
454
455 #ifdef L_decodeq
456 int __decode_question(unsigned char *message, int offset,
457                                         struct resolv_question *q)
458 {
459         char temp[256];
460         int i;
461
462         i = __decode_dotted(message, offset, temp, sizeof(temp));
463         if (i < 0)
464                 return i;
465
466         offset += i;
467
468         q->dotted = strdup(temp);
469         q->qtype = (message[offset + 0] << 8) | message[offset + 1];
470         q->qclass = (message[offset + 2] << 8) | message[offset + 3];
471
472         return i + 4;
473 }
474 #endif
475
476 #ifdef L_lengthq
477 int __length_question(unsigned char *message, int offset)
478 {
479         int i;
480
481         i = __length_dotted(message, offset);
482         if (i < 0)
483                 return i;
484
485         return i + 4;
486 }
487 #endif
488
489 #ifdef L_encodea
490 int __encode_answer(struct resolv_answer *a, unsigned char *dest, int maxlen)
491 {
492         int i;
493
494         i = __encode_dotted(a->dotted, dest, maxlen);
495         if (i < 0)
496                 return i;
497
498         dest += i;
499         maxlen -= i;
500
501         if (maxlen < (RRFIXEDSZ+a->rdlength))
502                 return -1;
503
504         *dest++ = (a->atype & 0xff00) >> 8;
505         *dest++ = (a->atype & 0x00ff) >> 0;
506         *dest++ = (a->aclass & 0xff00) >> 8;
507         *dest++ = (a->aclass & 0x00ff) >> 0;
508         *dest++ = (a->ttl & 0xff000000) >> 24;
509         *dest++ = (a->ttl & 0x00ff0000) >> 16;
510         *dest++ = (a->ttl & 0x0000ff00) >> 8;
511         *dest++ = (a->ttl & 0x000000ff) >> 0;
512         *dest++ = (a->rdlength & 0xff00) >> 8;
513         *dest++ = (a->rdlength & 0x00ff) >> 0;
514         memcpy(dest, a->rdata, a->rdlength);
515
516         return i + RRFIXEDSZ + a->rdlength;
517 }
518 #endif
519
520 #ifdef L_decodea
521 int __decode_answer(unsigned char *message, int offset,
522                                   struct resolv_answer *a)
523 {
524         char temp[256];
525         int i;
526
527         i = __decode_dotted(message, offset, temp, sizeof(temp));
528         if (i < 0)
529                 return i;
530
531         message += offset + i;
532
533         a->dotted = strdup(temp);
534         a->atype = (message[0] << 8) | message[1];
535         message += 2;
536         a->aclass = (message[0] << 8) | message[1];
537         message += 2;
538         a->ttl = (message[0] << 24) |
539                 (message[1] << 16) | (message[2] << 8) | (message[3] << 0);
540         message += 4;
541         a->rdlength = (message[0] << 8) | message[1];
542         message += 2;
543         a->rdata = message;
544         a->rdoffset = offset + i + RRFIXEDSZ;
545
546         DPRINTF("i=%d,rdlength=%d\n", i, a->rdlength);
547
548         return i + RRFIXEDSZ + a->rdlength;
549 }
550 #endif
551
552 #ifdef L_encodep
553 int __encode_packet(struct resolv_header *h,
554         struct resolv_question **q,
555         struct resolv_answer **an,
556         struct resolv_answer **ns,
557         struct resolv_answer **ar,
558         unsigned char *dest, int maxlen)
559 {
560         int i, total = 0;
561         int j;
562
563         i = __encode_header(h, dest, maxlen);
564         if (i < 0)
565                 return i;
566
567         dest += i;
568         maxlen -= i;
569         total += i;
570
571         for (j = 0; j < h->qdcount; j++) {
572                 i = __encode_question(q[j], dest, maxlen);
573                 if (i < 0)
574                         return i;
575                 dest += i;
576                 maxlen -= i;
577                 total += i;
578         }
579
580         for (j = 0; j < h->ancount; j++) {
581                 i = __encode_answer(an[j], dest, maxlen);
582                 if (i < 0)
583                         return i;
584                 dest += i;
585                 maxlen -= i;
586                 total += i;
587         }
588         for (j = 0; j < h->nscount; j++) {
589                 i = __encode_answer(ns[j], dest, maxlen);
590                 if (i < 0)
591                         return i;
592                 dest += i;
593                 maxlen -= i;
594                 total += i;
595         }
596         for (j = 0; j < h->arcount; j++) {
597                 i = __encode_answer(ar[j], dest, maxlen);
598                 if (i < 0)
599                         return i;
600                 dest += i;
601                 maxlen -= i;
602                 total += i;
603         }
604
605         return total;
606 }
607 #endif
608
609 #ifdef L_decodep
610 int __decode_packet(unsigned char *data, struct resolv_header *h)
611 {
612         return __decode_header(data, h);
613 }
614 #endif
615
616 #ifdef L_formquery
617 int __form_query(int id, const char *name, int type, unsigned char *packet,
618                            int maxlen)
619 {
620         struct resolv_header h;
621         struct resolv_question q;
622         int i, j;
623
624         memset(&h, 0, sizeof(h));
625         h.id = id;
626         h.qdcount = 1;
627
628         q.dotted = (char *) name;
629         q.qtype = type;
630         q.qclass = C_IN; /* CLASS_IN */
631
632         i = __encode_header(&h, packet, maxlen);
633         if (i < 0)
634                 return i;
635
636         j = __encode_question(&q, packet + i, maxlen - i);
637         if (j < 0)
638                 return j;
639
640         return i + j;
641 }
642 #endif
643
644 #ifdef L_dnslookup
645
646 #ifdef __UCLIBC_HAS_THREADS__
647 static pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
648 # define LOCK   __pthread_mutex_lock(&mylock)
649 # define UNLOCK __pthread_mutex_unlock(&mylock);
650 #else
651 # define LOCK
652 # define UNLOCK
653 #endif
654
655 /* Just for the record, having to lock __dns_lookup() just for these two globals
656  * is pretty lame.  I think these two variables can probably be de-global-ized, 
657  * which should eliminate the need for doing locking here...  Needs a closer 
658  * look anyways. */
659 static int ns=0, id=1;
660
661 int __dns_lookup(const char *name, int type, int nscount, char **nsip,
662                            unsigned char **outpacket, struct resolv_answer *a)
663 {
664         int i, j, len, fd, pos, rc;
665         struct timeval tv;
666         fd_set fds;
667         struct resolv_header h;
668         struct resolv_question q;
669         int retries = 0;
670         unsigned char * packet = malloc(PACKETSZ);
671         char *dns, *lookup = malloc(MAXDNAME);
672         int variant = 0;
673         struct sockaddr_in sa;
674 #ifdef __UCLIBC_HAS_IPV6__
675         int v6;
676         struct sockaddr_in6 sa6;
677 #endif
678
679         fd = -1;
680
681         if (!packet || !lookup || !nscount)
682             goto fail;
683
684         DPRINTF("Looking up type %d answer for '%s'\n", type, name);
685
686         LOCK;
687         ns %= nscount;
688         UNLOCK;
689
690         while (retries < MAX_RETRIES) {
691                 if (fd != -1)
692                         close(fd);
693
694                 memset(packet, 0, PACKETSZ);
695
696                 memset(&h, 0, sizeof(h));
697
698                 /* Mess with globals while under lock */
699                 LOCK;
700                 ++id;
701                 id &= 0xffff;
702                 h.id = id;
703                 dns = nsip[ns];
704                 UNLOCK;
705
706                 h.qdcount = 1;
707                 h.rd = 1;
708
709                 DPRINTF("encoding header\n", h.rd);
710
711                 i = __encode_header(&h, packet, PACKETSZ);
712                 if (i < 0)
713                         goto fail;
714
715                 strncpy(lookup,name,MAXDNAME);
716                 BIGLOCK;
717                 if (variant < __searchdomains && strchr(lookup, '.') == NULL)
718                 {
719                     strncat(lookup,".", MAXDNAME);
720                     strncat(lookup,__searchdomain[variant], MAXDNAME);
721                 }
722                 BIGUNLOCK;
723                 DPRINTF("lookup name: %s\n", lookup);
724                 q.dotted = (char *)lookup;
725                 q.qtype = type;
726                 q.qclass = C_IN; /* CLASS_IN */
727
728                 j = __encode_question(&q, packet+i, PACKETSZ-i);
729                 if (j < 0)
730                         goto fail;
731
732                 len = i + j;
733
734                 DPRINTF("On try %d, sending query to port %d of machine %s\n",
735                                 retries+1, NAMESERVER_PORT, dns);
736
737 #ifdef __UCLIBC_HAS_IPV6__
738                 v6 = inet_pton(AF_INET6, dns, &sa6.sin6_addr) > 0;
739                 fd = socket(v6 ? AF_INET6 : AF_INET, SOCK_DGRAM, IPPROTO_UDP);
740 #else
741                 fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
742 #endif
743                 if (fd < 0) {
744                     retries++;
745                     continue;
746                 }
747
748                 /* Connect to the UDP socket so that asyncronous errors are returned */          
749 #ifdef __UCLIBC_HAS_IPV6__
750                 if (v6) {
751                     sa6.sin6_family = AF_INET6;
752                     sa6.sin6_port = htons(NAMESERVER_PORT);
753                     /* sa6.sin6_addr is already here */
754                     rc = connect(fd, (struct sockaddr *) &sa6, sizeof(sa6));
755                 } else {
756 #endif
757                     sa.sin_family = AF_INET;
758                     sa.sin_port = htons(NAMESERVER_PORT);
759                     sa.sin_addr.s_addr = inet_addr(dns);
760                     rc = connect(fd, (struct sockaddr *) &sa, sizeof(sa));
761 #ifdef __UCLIBC_HAS_IPV6__
762                 }
763 #endif
764                 if (rc < 0) {
765                     if (errno == ENETUNREACH) {
766                         /* routing error, presume not transient */
767                         goto tryall;
768                     } else
769                         /* retry */
770                         retries++;
771                         continue;
772                 }
773
774                 DPRINTF("Transmitting packet of length %d, id=%d, qr=%d\n",
775                                 len, h.id, h.qr);
776
777                 send(fd, packet, len, 0);
778
779                 FD_ZERO(&fds);
780                 FD_SET(fd, &fds);
781                 tv.tv_sec = REPLY_TIMEOUT;
782                 tv.tv_usec = 0;
783                 if (select(fd + 1, &fds, NULL, NULL, &tv) <= 0) {
784                     DPRINTF("Timeout\n");
785
786                         /* timed out, so retry send and receive, 
787                          * to next nameserver on queue */
788                         goto tryall;
789                 }
790
791                 len = recv(fd, packet, 512, 0);
792                 if (len < HFIXEDSZ) {
793                         /* too short ! */
794                         goto again;
795                 }
796
797                 __decode_header(packet, &h);
798
799                 DPRINTF("id = %d, qr = %d\n", h.id, h.qr);
800
801                 LOCK;
802                 if ((h.id != id) || (!h.qr)) {
803                         UNLOCK;
804                         /* unsolicited */
805                         goto again;
806                 }
807                 UNLOCK;
808
809
810                 DPRINTF("Got response %s\n", "(i think)!");
811                 DPRINTF("qrcount=%d,ancount=%d,nscount=%d,arcount=%d\n",
812                                 h.qdcount, h.ancount, h.nscount, h.arcount);
813                 DPRINTF("opcode=%d,aa=%d,tc=%d,rd=%d,ra=%d,rcode=%d\n",
814                                 h.opcode, h.aa, h.tc, h.rd, h.ra, h.rcode);
815
816                 if ((h.rcode) || (h.ancount < 1)) {
817                         /* negative result, not present */
818                         goto again;
819                 }
820
821                 pos = HFIXEDSZ;
822
823                 for (j = 0; j < h.qdcount; j++) {
824                         DPRINTF("Skipping question %d at %d\n", j, pos);
825                         i = __length_question(packet, pos);
826                         DPRINTF("Length of question %d is %d\n", j, i);
827                         if (i < 0)
828                                 goto again;
829                         pos += i;
830                 }
831                 DPRINTF("Decoding answer at pos %d\n", pos);
832
833                 for (j=0;j<h.ancount;j++)
834                 {
835                     i = __decode_answer(packet, pos, a);
836
837                     if (i<0) {
838                         DPRINTF("failed decode %d\n", i);
839                         goto again;
840                     }
841                     /* For all but T_SIG, accept first answer */
842                     if (a->atype != T_SIG)
843                         break;
844
845                     DPRINTF("skipping T_SIG %d\n", i);
846                     free(a->dotted);
847                     pos += i;
848                 }
849
850                 DPRINTF("Answer name = |%s|\n", a->dotted);
851                 DPRINTF("Answer type = |%d|\n", a->atype);
852
853                 close(fd);
854
855                 if (outpacket)
856                         *outpacket = packet;
857                 else
858                         free(packet);
859                 free(lookup);
860                 return (len);                           /* success! */
861
862           tryall:
863                 /* if there are other nameservers, give them a go,
864                    otherwise return with error */
865                 {
866                     variant = 0;
867                     LOCK;
868                     ns = (ns + 1) % nscount;
869                     if (ns == 0)
870                       retries++;
871
872                     UNLOCK;
873                     continue;
874                 }
875
876           again:
877                 /* if there are searchdomains, try them or fallback as passed */
878                 {
879                     int sdomains;
880                     BIGLOCK;
881                     sdomains=__searchdomains;
882                     BIGUNLOCK;
883
884                     if (variant < ((sdomains - 1) && strchr(lookup, '.') == NULL)) {
885                         /* next search */
886                         variant++;
887                     } else {
888                         /* next server, first search */
889                         LOCK;
890                         ns = (ns + 1) % nscount;
891                         if (ns == 0)
892                           retries++;
893
894                         UNLOCK;
895                         variant = 0;
896                     }
897                 }
898         }
899
900 fail:
901         if (fd != -1)
902             close(fd);
903         if (lookup)
904             free(lookup);
905         if (packet)
906             free(packet);
907         h_errno = NETDB_INTERNAL;
908         return -1;
909 }
910 #endif
911
912 #ifdef L_opennameservers
913
914 int __nameservers;
915 char * __nameserver[MAX_SERVERS];
916 int __searchdomains;
917 char * __searchdomain[MAX_SEARCH];
918 #ifdef __UCLIBC_HAS_THREADS__
919 pthread_mutex_t __resolv_lock = PTHREAD_MUTEX_INITIALIZER;
920 #endif
921
922 /*
923  *      we currently read formats not quite the same as that on normal
924  *      unix systems, we can have a list of nameservers after the keyword.
925  */
926
927 int __open_nameservers()
928 {
929         FILE *fp;
930         int i;
931 #define RESOLV_ARGS 5
932         char szBuffer[128], *p, *argv[RESOLV_ARGS];
933         int argc;
934
935         BIGLOCK;
936         if (__nameservers > 0) { 
937             BIGUNLOCK;
938             return 0;
939         }
940
941         if ((fp = fopen("/etc/resolv.conf", "r")) ||
942                         (fp = fopen("/etc/config/resolv.conf", "r")))
943         {
944
945                 while (fgets(szBuffer, sizeof(szBuffer), fp) != NULL) {
946
947                         for (p = szBuffer; *p && isspace(*p); p++)
948                                 /* skip white space */;
949                         if (*p == '\0' || *p == '\n' || *p == '#') /* skip comments etc */
950                                 continue;
951                         argc = 0;
952                         while (*p && argc < RESOLV_ARGS) {
953                                 argv[argc++] = p;
954                                 while (*p && !isspace(*p) && *p != '\n')
955                                         p++;
956                                 while (*p && (isspace(*p) || *p == '\n')) /* remove spaces */
957                                         *p++ = '\0';
958                         }
959
960                         if (strcmp(argv[0], "nameserver") == 0) {
961                                 for (i = 1; i < argc && __nameservers < MAX_SERVERS; i++) {
962                                         __nameserver[__nameservers++] = strdup(argv[i]);
963                                         DPRINTF("adding nameserver %s\n", argv[i]);
964                                 }
965                         }
966
967                         /* domain and search are mutually exclusive, the last one wins */
968                         if (strcmp(argv[0],"domain")==0 || strcmp(argv[0],"search")==0) {
969                                 while (__searchdomains > 0) {
970                                         free(__searchdomain[--__searchdomains]);
971                                         __searchdomain[__searchdomains] = NULL;
972                                 }
973                                 for (i=1; i < argc && __searchdomains < MAX_SEARCH; i++) {
974                                         __searchdomain[__searchdomains++] = strdup(argv[i]);
975                                         DPRINTF("adding search %s\n", argv[i]);
976                                 }
977                         }
978                 }
979                 fclose(fp);
980                 DPRINTF("nameservers = %d\n", __nameservers);
981                 BIGUNLOCK;
982                 return 0;
983         }
984         DPRINTF("failed to open %s\n", "resolv.conf");
985         h_errno = NO_RECOVERY;
986         BIGUNLOCK;
987         return -1;
988 }
989 #endif
990
991
992 #ifdef L_closenameservers
993
994 void __close_nameservers(void)
995 {
996         BIGLOCK;
997         while (__nameservers > 0) {
998                 free(__nameserver[--__nameservers]);
999                 __nameserver[__nameservers] = NULL;
1000         }
1001         while (__searchdomains > 0) {
1002                 free(__searchdomain[--__searchdomains]);
1003                 __searchdomain[__searchdomains] = NULL;
1004         }
1005         BIGUNLOCK;
1006 }
1007 #endif
1008
1009 #ifdef L_gethostbyname
1010
1011 struct hostent *gethostbyname(const char *name)
1012 {
1013         static struct hostent h;
1014         static char buf[sizeof(struct in_addr) +
1015                         sizeof(struct in_addr *)*2 +
1016                         sizeof(char *)*(ALIAS_DIM) + 256/*namebuffer*/ + 32/* margin */];
1017         struct hostent *hp;
1018
1019         gethostbyname_r(name, &h, buf, sizeof(buf), &hp, &h_errno);
1020
1021         return hp;
1022 }
1023 #endif
1024
1025 #ifdef L_gethostbyname2
1026
1027 struct hostent *gethostbyname2(const char *name, int family)
1028 {
1029 #ifndef __UCLIBC_HAS_IPV6__
1030         return family == AF_INET ? gethostbyname(name) : (struct hostent*)0;
1031 #else /* __UCLIBC_HAS_IPV6__ */
1032         static struct hostent h;
1033         static char buf[sizeof(struct in6_addr) +
1034                         sizeof(struct in6_addr *)*2 +
1035                         sizeof(char *)*(ALIAS_DIM) + 256/*namebuffer*/ + 32/* margin */];
1036         struct hostent *hp;
1037
1038         gethostbyname2_r(name, family, &h, buf, sizeof(buf), &hp, &h_errno);
1039
1040         return hp;
1041 #endif /* __UCLIBC_HAS_IPV6__ */
1042 }
1043 #endif
1044
1045 #ifdef L_getnetbyname
1046
1047 struct netent * getnetbyname(const char * name)
1048 {
1049         return NULL;
1050 }
1051 #endif
1052
1053
1054 #ifdef L_res_init
1055 struct __res_state _res;
1056
1057 int res_init(void)
1058 {
1059         struct __res_state *rp = &(_res);
1060
1061         __close_nameservers();
1062         if (__open_nameservers()) {
1063                 return(-1);
1064         }
1065         rp->retrans = RES_TIMEOUT;
1066         rp->retry = 4;
1067         rp->options = RES_INIT;
1068         rp->id = (u_int) random();
1069         rp->nsaddr.sin_addr.s_addr = INADDR_ANY;
1070         rp->nsaddr.sin_family = AF_INET;
1071         rp->nsaddr.sin_port = htons(NAMESERVER_PORT);
1072         rp->ndots = 1;
1073         /** rp->pfcode = 0; **/
1074         rp->_vcsock = -1;
1075         /** rp->_flags = 0; **/
1076         /** rp->qhook = NULL; **/
1077         /** rp->rhook = NULL; **/
1078         /** rp->_u._ext.nsinit = 0; **/
1079
1080         BIGLOCK;
1081         if(__searchdomains) {
1082                 int i;
1083                 for(i=0; i<__searchdomains; i++) {
1084                         rp->dnsrch[i] = __searchdomain[i];
1085                 }
1086         }
1087
1088         if(__nameservers) {
1089                 int i;
1090                 struct in_addr a;
1091                 for(i=0; i<__nameservers; i++) {
1092                         if (inet_aton(__nameserver[i], &a)) {
1093                                 rp->nsaddr_list[i].sin_addr = a;
1094                                 rp->nsaddr_list[i].sin_family = AF_INET;
1095                                 rp->nsaddr_list[i].sin_port = htons(NAMESERVER_PORT);
1096                         }
1097                 }
1098         }
1099         rp->nscount = __nameservers;
1100         BIGUNLOCK;
1101
1102         return(0);
1103 }
1104
1105 void res_close( void )
1106 {
1107         return;
1108 }
1109
1110 #endif
1111
1112
1113 #ifdef L_res_query
1114
1115 #ifndef MIN
1116 #define MIN(x, y)       ((x) < (y) ? (x) : (y))
1117 #endif
1118
1119 int res_query(const char *dname, int class, int type,
1120               unsigned char *answer, int anslen)
1121 {
1122         int i;
1123         unsigned char * packet = 0;
1124         struct resolv_answer a;
1125         int __nameserversXX;
1126         char ** __nameserverXX;
1127
1128         if (__open_nameservers() || !dname || class != 1 /* CLASS_IN */) {
1129                 h_errno = NO_RECOVERY;
1130                 return(-1);
1131         }
1132
1133         memset((char *) &a, '\0', sizeof(a));
1134
1135         BIGLOCK;
1136         __nameserversXX=__nameservers;
1137         __nameserverXX=__nameserver;
1138         BIGUNLOCK;
1139         i = __dns_lookup(dname, type, __nameserversXX, __nameserverXX, &packet, &a);
1140
1141         if (i < 0) {
1142                 h_errno = TRY_AGAIN;
1143                 return(-1);
1144         }
1145
1146         free(a.dotted);
1147
1148         if (a.atype == type) { /* CNAME*/
1149                 int len = MIN(anslen, i);
1150                 memcpy(answer, packet, len);
1151                 if (packet)
1152                         free(packet);
1153                 return(len);
1154         }
1155         if (packet)
1156                 free(packet);
1157         return i;
1158 }
1159
1160 /*
1161  * Formulate a normal query, send, and retrieve answer in supplied buffer.
1162  * Return the size of the response on success, -1 on error.
1163  * If enabled, implement search rules until answer or unrecoverable failure
1164  * is detected.  Error code, if any, is left in h_errno.
1165  */
1166 int res_search(name, class, type, answer, anslen)
1167         const char *name;       /* domain name */
1168         int class, type;        /* class and type of query */
1169         u_char *answer;         /* buffer to put answer */
1170         int anslen;             /* size of answer */
1171 {
1172         const char *cp, * const *domain;
1173         HEADER *hp = (HEADER *)(void *)answer;
1174         u_int dots;
1175         int trailing_dot, ret, saved_herrno;
1176         int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
1177
1178         if ((!name || !answer) || ((_res.options & RES_INIT) == 0 && res_init() == -1)) {
1179                 h_errno = NETDB_INTERNAL;
1180                 return (-1);
1181         }
1182
1183         errno = 0;
1184         h_errno = HOST_NOT_FOUND;       /* default, if we never query */
1185         dots = 0;
1186         for (cp = name; *cp; cp++)
1187                 dots += (*cp == '.');
1188         trailing_dot = 0;
1189         if (cp > name && *--cp == '.')
1190                 trailing_dot++;
1191
1192         /*
1193          * If there are dots in the name already, let's just give it a try
1194          * 'as is'.  The threshold can be set with the "ndots" option.
1195          */
1196         saved_herrno = -1;
1197         if (dots >= _res.ndots) {
1198                 ret = res_querydomain(name, NULL, class, type, answer, anslen);
1199                 if (ret > 0)
1200                         return (ret);
1201                 saved_herrno = h_errno;
1202                 tried_as_is++;
1203         }
1204
1205         /*
1206          * We do at least one level of search if
1207          *      - there is no dot and RES_DEFNAME is set, or
1208          *      - there is at least one dot, there is no trailing dot,
1209          *        and RES_DNSRCH is set.
1210          */
1211         if ((!dots && (_res.options & RES_DEFNAMES)) ||
1212             (dots && !trailing_dot && (_res.options & RES_DNSRCH))) {
1213                 int done = 0;
1214
1215                 for (domain = (const char * const *)_res.dnsrch;
1216                    *domain && !done;
1217                    domain++) {
1218
1219                         ret = res_querydomain(name, *domain, class, type,
1220                             answer, anslen);
1221                         if (ret > 0)
1222                                 return (ret);
1223
1224                         /*
1225                          * If no server present, give up.
1226                          * If name isn't found in this domain,
1227                          * keep trying higher domains in the search list
1228                          * (if that's enabled).
1229                          * On a NO_DATA error, keep trying, otherwise
1230                          * a wildcard entry of another type could keep us
1231                          * from finding this entry higher in the domain.
1232                          * If we get some other error (negative answer or
1233                          * server failure), then stop searching up,
1234                          * but try the input name below in case it's
1235                          * fully-qualified.
1236                          */
1237                         if (errno == ECONNREFUSED) {
1238                                 h_errno = TRY_AGAIN;
1239                                 return (-1);
1240                         }
1241
1242                         switch (h_errno) {
1243                         case NO_DATA:
1244                                 got_nodata++;
1245                                 /* FALLTHROUGH */
1246                         case HOST_NOT_FOUND:
1247                                 /* keep trying */
1248                                 break;
1249                         case TRY_AGAIN:
1250                                 if (hp->rcode == SERVFAIL) {
1251                                         /* try next search element, if any */
1252                                         got_servfail++;
1253                                         break;
1254                                 }
1255                                 /* FALLTHROUGH */
1256                         default:
1257                                 /* anything else implies that we're done */
1258                                 done++;
1259                         }
1260                         /*
1261                          * if we got here for some reason other than DNSRCH,
1262                          * we only wanted one iteration of the loop, so stop.
1263                          */
1264                         if (!(_res.options & RES_DNSRCH))
1265                                 done++;
1266                 }
1267         }
1268
1269         /*
1270          * if we have not already tried the name "as is", do that now.
1271          * note that we do this regardless of how many dots were in the
1272          * name or whether it ends with a dot.
1273          */
1274         if (!tried_as_is) {
1275                 ret = res_querydomain(name, NULL, class, type, answer, anslen);
1276                 if (ret > 0)
1277                         return (ret);
1278         }
1279
1280         /*
1281          * if we got here, we didn't satisfy the search.
1282          * if we did an initial full query, return that query's h_errno
1283          * (note that we wouldn't be here if that query had succeeded).
1284          * else if we ever got a nodata, send that back as the reason.
1285          * else send back meaningless h_errno, that being the one from
1286          * the last DNSRCH we did.
1287          */
1288         if (saved_herrno != -1)
1289                 h_errno = saved_herrno;
1290         else if (got_nodata)
1291                 h_errno = NO_DATA;
1292         else if (got_servfail)
1293                 h_errno = TRY_AGAIN;
1294         return (-1);
1295 }
1296
1297 /*
1298  * Perform a call on res_query on the concatenation of name and domain,
1299  * removing a trailing dot from name if domain is NULL.
1300  */
1301 int res_querydomain(name, domain, class, type, answer, anslen)
1302         const char *name, *domain;
1303         int class, type;        /* class and type of query */
1304         u_char *answer;         /* buffer to put answer */
1305         int anslen;             /* size of answer */
1306 {
1307         char nbuf[MAXDNAME];
1308         const char *longname = nbuf;
1309         size_t n, d;
1310
1311         if ((!name || !answer) || ((_res.options & RES_INIT) == 0 && res_init() == -1)) {
1312                 h_errno = NETDB_INTERNAL;
1313                 return (-1);
1314         }
1315
1316 #ifdef DEBUG
1317         if (_res.options & RES_DEBUG)
1318                 printf(";; res_querydomain(%s, %s, %d, %d)\n",
1319                         name, domain?domain:"<Nil>", class, type);
1320 #endif
1321         if (domain == NULL) {
1322                 /*
1323                  * Check for trailing '.';
1324                  * copy without '.' if present.
1325                  */
1326                 n = strlen(name);
1327                 if (n + 1 > sizeof(nbuf)) {
1328                         h_errno = NO_RECOVERY;
1329                         return (-1);
1330                 }
1331                 if (n > 0 && name[--n] == '.') {
1332                         strncpy(nbuf, name, n);
1333                         nbuf[n] = '\0';
1334                 } else
1335                         longname = name;
1336         } else {
1337                 n = strlen(name);
1338                 d = strlen(domain);
1339                 if (n + 1 + d + 1 > sizeof(nbuf)) {
1340                         h_errno = NO_RECOVERY;
1341                         return (-1);
1342                 }
1343                 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
1344         }
1345         return (res_query(longname, class, type, answer, anslen));
1346 }
1347
1348 /* res_mkquery */
1349 /* res_send */
1350 /* dn_comp */
1351 /* dn_expand */
1352 #endif
1353
1354 #ifdef L_gethostbyaddr
1355 struct hostent *gethostbyaddr (const void *addr, socklen_t len, int type)
1356 {
1357         static struct hostent h;
1358         static char buf[
1359 #ifndef __UCLIBC_HAS_IPV6__
1360                 sizeof(struct in_addr) + sizeof(struct in_addr *)*2 +
1361 #else
1362                 sizeof(struct in6_addr) + sizeof(struct in6_addr *)*2 +
1363 #endif /* __UCLIBC_HAS_IPV6__ */
1364                 sizeof(char *)*(ALIAS_DIM) + 256/*namebuffer*/ + 32/* margin */];
1365         struct hostent *hp;
1366
1367         gethostbyaddr_r(addr, len, type, &h, buf, sizeof(buf), &hp, &h_errno);
1368         
1369         return hp;
1370 }
1371 #endif
1372
1373
1374 #ifdef L_read_etc_hosts_r
1375
1376 void __open_etc_hosts(FILE **fp)
1377 {
1378         if ((*fp = fopen("/etc/hosts", "r")) == NULL) {
1379                 *fp = fopen("/etc/config/hosts", "r");
1380         }
1381         return;
1382 }
1383
1384 int __read_etc_hosts_r(FILE * fp, const char * name, int type,
1385                      enum etc_hosts_action action,
1386                      struct hostent * result_buf,
1387                      char * buf, size_t buflen,
1388                      struct hostent ** result,
1389                      int * h_errnop)
1390 {
1391         struct in_addr  *in=NULL;
1392         struct in_addr  **addr_list=NULL;
1393 #ifdef __UCLIBC_HAS_IPV6__
1394         struct in6_addr *in6=NULL;
1395         struct in6_addr **addr_list6=NULL;
1396 #endif /* __UCLIBC_HAS_IPV6__ */
1397         char                                    *cp;
1398         char                                    **alias;
1399         int                                             aliases, i;
1400         int             ret=HOST_NOT_FOUND;
1401
1402         if (buflen < sizeof(char *)*(ALIAS_DIM))
1403                 return ERANGE;
1404         alias=(char **)buf;
1405         buf+=sizeof(char **)*(ALIAS_DIM);
1406         buflen-=sizeof(char **)*(ALIAS_DIM);
1407
1408         if (action!=GETHOSTENT) {
1409 #ifdef __UCLIBC_HAS_IPV6__
1410                 char *p=buf;
1411                 size_t len=buflen;
1412 #endif /* __UCLIBC_HAS_IPV6__ */
1413                 *h_errnop=NETDB_INTERNAL;
1414                 if (buflen < sizeof(*in))
1415                         return ERANGE;
1416                 in=(struct in_addr*)buf;
1417                 buf+=sizeof(*in);
1418                 buflen-=sizeof(*in);
1419
1420                 if (buflen < sizeof(*addr_list)*2)
1421                         return ERANGE;
1422                 addr_list=(struct in_addr **)buf;
1423                 buf+=sizeof(*addr_list)*2;
1424                 buflen-=sizeof(*addr_list)*2;
1425
1426 #ifdef __UCLIBC_HAS_IPV6__
1427                 if (len < sizeof(*in6))
1428                         return ERANGE;
1429                 in6=(struct in6_addr*)p;
1430                 p+=sizeof(*in6);
1431                 len-=sizeof(*in6);
1432
1433                 if (len < sizeof(*addr_list6)*2)
1434                         return ERANGE;
1435                 addr_list6=(struct in6_addr**)p;
1436                 p+=sizeof(*addr_list6)*2;
1437                 len-=sizeof(*addr_list6)*2;
1438
1439                 if (len < buflen) {
1440                         buflen=len;
1441                         buf=p;
1442                 }
1443 #endif /* __UCLIBC_HAS_IPV6__ */
1444
1445                 if (buflen < 80)
1446                         return ERANGE;
1447
1448                 __open_etc_hosts(&fp);
1449                 if (fp == NULL) {
1450                         result=NULL;
1451                         return errno;
1452                 }
1453         }
1454
1455         *h_errnop=HOST_NOT_FOUND;
1456         while (fgets(buf, buflen, fp)) {
1457                 if ((cp = strchr(buf, '#')))
1458                         *cp = '\0';
1459                 DPRINTF("Looking at: %s\n", buf);
1460                 aliases = 0;
1461
1462                 cp = buf;
1463                 while (*cp) {
1464                         while (*cp && isspace(*cp))
1465                                 *cp++ = '\0';
1466                         if (!*cp)
1467                                 continue;
1468                         if (aliases < (2+MAX_ALIASES))
1469                                 alias[aliases++] = cp;
1470                         while (*cp && !isspace(*cp))
1471                                 cp++;
1472                 }
1473                 alias[aliases] = 0;
1474
1475                 if (aliases < 2)
1476                         continue; /* syntax error really */
1477                 
1478                 if (action==GETHOSTENT) {
1479                         /* Return whatever the next entry happens to be. */
1480                         break;
1481                 } else if (action==GET_HOSTS_BYADDR) {
1482                         if (strcmp(name, alias[0]) != 0)
1483                                 continue;
1484                 } else {
1485                         /* GET_HOSTS_BYNAME */
1486                         for (i = 1; i < aliases; i++)
1487                                 if (strcasecmp(name, alias[i]) == 0)
1488                                         break;
1489                         if (i >= aliases)
1490                                 continue;
1491                 }
1492
1493                 if (type == AF_INET && inet_pton(AF_INET, alias[0], in) > 0) {
1494                         DPRINTF("Found INET\n");
1495                         addr_list[0] = in;
1496                         addr_list[1] = 0;
1497                         result_buf->h_name = alias[1];
1498                         result_buf->h_addrtype = AF_INET;
1499                         result_buf->h_length = sizeof(*in);
1500                         result_buf->h_addr_list = (char**) addr_list;
1501                         result_buf->h_aliases = alias + 2;
1502                         *result=result_buf;
1503                         ret=NETDB_SUCCESS;
1504 #ifdef __UCLIBC_HAS_IPV6__
1505         } else if (type == AF_INET6 && inet_pton(AF_INET6, alias[0], in6) > 0) {
1506                         DPRINTF("Found INET6\n");
1507                         addr_list6[0] = in6;
1508                         addr_list6[1] = 0;
1509                         result_buf->h_name = alias[1];
1510                         result_buf->h_addrtype = AF_INET6;
1511                         result_buf->h_length = sizeof(*in6);
1512                         result_buf->h_addr_list = (char**) addr_list6;
1513                         result_buf->h_aliases = alias + 2;
1514                         *result=result_buf;
1515                         ret=NETDB_SUCCESS;
1516 #endif /* __UCLIBC_HAS_IPV6__ */
1517                 } else {
1518                         DPRINTF("Error\n");
1519                         ret=TRY_AGAIN;
1520                         break; /* bad ip address */
1521         }
1522         
1523                 if (action!=GETHOSTENT) {
1524                         fclose(fp);
1525                 }
1526                 return ret;
1527         }
1528         if (action!=GETHOSTENT) {
1529                 fclose(fp);
1530         }
1531         return ret;
1532 }
1533 #endif
1534
1535
1536 #ifdef L_gethostent
1537
1538 #ifdef __UCLIBC_HAS_THREADS__
1539 static pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
1540 # define LOCK   __pthread_mutex_lock(&mylock)
1541 # define UNLOCK __pthread_mutex_unlock(&mylock);
1542 #else
1543 # define LOCK
1544 # define UNLOCK
1545 #endif
1546
1547 static int __stay_open;
1548 static FILE * __gethostent_fp;
1549
1550 void endhostent (void)
1551 {
1552     LOCK;
1553     __stay_open = 0;
1554     if (__gethostent_fp) {
1555         fclose(__gethostent_fp);
1556     }
1557     UNLOCK;
1558 }
1559
1560 void sethostent (int stay_open)
1561 {
1562     LOCK;
1563     __stay_open = stay_open;
1564     UNLOCK;
1565 }
1566
1567
1568 struct hostent *gethostent (void)
1569 {
1570     static struct hostent h;
1571     static char buf[
1572 #ifndef __UCLIBC_HAS_IPV6__
1573             sizeof(struct in_addr) + sizeof(struct in_addr *)*2 +
1574 #else
1575             sizeof(struct in6_addr) + sizeof(struct in6_addr *)*2 +
1576 #endif /* __UCLIBC_HAS_IPV6__ */
1577                 sizeof(char *)*(ALIAS_DIM) +
1578             80/*namebuffer*/ + 2/* margin */];
1579     struct hostent *host;
1580
1581     LOCK;
1582     if (__gethostent_fp == NULL) {
1583         __open_etc_hosts(&__gethostent_fp);
1584         if (__gethostent_fp == NULL) {
1585             UNLOCK;
1586             return((struct hostent *)NULL);
1587         }
1588     }
1589
1590     __read_etc_hosts_r(__gethostent_fp, NULL, AF_INET, GETHOSTENT, 
1591                    &h, buf, sizeof(buf), &host, &h_errno);
1592     if (__stay_open==0) {
1593         fclose(__gethostent_fp);
1594     }
1595     UNLOCK;
1596     return(host);
1597 }
1598 #endif
1599
1600 #ifdef L_get_hosts_byname_r
1601
1602 int __get_hosts_byname_r(const char * name, int type,
1603                             struct hostent * result_buf,
1604                             char * buf, size_t buflen,
1605                             struct hostent ** result,
1606                             int * h_errnop)
1607 {
1608         return(__read_etc_hosts_r(NULL, name, type, GET_HOSTS_BYNAME, result_buf, buf, buflen, result, h_errnop));
1609 }
1610 #endif
1611
1612 #ifdef L_get_hosts_byaddr_r
1613
1614 int __get_hosts_byaddr_r(const char * addr, int len, int type,
1615                             struct hostent * result_buf,
1616                             char * buf, size_t buflen,
1617                             struct hostent ** result,
1618                             int * h_errnop)
1619 {
1620 #ifndef __UCLIBC_HAS_IPV6__
1621         char    ipaddr[INET_ADDRSTRLEN];
1622 #else
1623         char    ipaddr[INET6_ADDRSTRLEN];
1624 #endif /* __UCLIBC_HAS_IPV6__ */
1625
1626     switch (type) {
1627         case AF_INET:
1628                 if (len != sizeof(struct in_addr))
1629                         return 0;
1630                 break;
1631 #ifdef __UCLIBC_HAS_IPV6__
1632         case AF_INET6:
1633                 if (len != sizeof(struct in6_addr))
1634                         return 0;
1635                 break;
1636 #endif /* __UCLIBC_HAS_IPV6__ */
1637         default:
1638                 return 0;
1639         }
1640
1641         inet_ntop(type, addr, ipaddr, sizeof(ipaddr));
1642
1643         return(__read_etc_hosts_r(NULL, ipaddr, type, GET_HOSTS_BYADDR, 
1644                     result_buf, buf, buflen, result, h_errnop));
1645 }
1646 #endif
1647
1648 #ifdef L_getnameinfo
1649
1650 #ifndef min
1651 # define min(x,y) (((x) > (y)) ? (y) : (x))
1652 #endif /* min */
1653
1654 int getnameinfo (const struct sockaddr *sa, socklen_t addrlen, char *host,
1655              socklen_t hostlen, char *serv, socklen_t servlen,
1656              unsigned int flags)
1657 {
1658         int serrno = errno;
1659         int ok = 0;
1660         struct hostent *h = NULL;
1661     char domain[256];
1662     
1663         if (flags & ~(NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|NI_DGRAM))
1664                 return EAI_BADFLAGS;
1665
1666         if (sa == NULL || addrlen < sizeof (sa_family_t))
1667                 return EAI_FAMILY;
1668
1669         switch (sa->sa_family) {
1670         case AF_LOCAL:
1671                 break;
1672         case AF_INET:
1673                 if (addrlen < sizeof (struct sockaddr_in))
1674                         return EAI_FAMILY;
1675                 break;
1676 #ifdef __UCLIBC_HAS_IPV6__
1677         case AF_INET6:
1678                 if (addrlen < sizeof (struct sockaddr_in6))
1679                         return EAI_FAMILY;
1680                 break;
1681 #endif /* __UCLIBC_HAS_IPV6__ */
1682         default:
1683                 return EAI_FAMILY;
1684         }
1685
1686         if (host != NULL && hostlen > 0)
1687                 switch (sa->sa_family) {
1688                 case AF_INET:
1689 #ifdef __UCLIBC_HAS_IPV6__
1690                 case AF_INET6:
1691 #endif /* __UCLIBC_HAS_IPV6__ */
1692                         if (!(flags & NI_NUMERICHOST)) {
1693 #ifdef __UCLIBC_HAS_IPV6__
1694                                 if (sa->sa_family == AF_INET6)
1695                                         h = gethostbyaddr ((const void *) &(((const struct sockaddr_in6 *) sa)->sin6_addr),
1696                                                 sizeof(struct in6_addr), AF_INET6);
1697                                 else
1698 #endif /* __UCLIBC_HAS_IPV6__ */
1699                     h = gethostbyaddr ((const void *) &(((const struct sockaddr_in *)sa)->sin_addr),
1700                                           sizeof(struct in_addr), AF_INET);
1701
1702                                 if (h) {
1703                                         char *c;
1704                                         if ((flags & NI_NOFQDN)
1705                                             && (getdomainname (domain, sizeof(domain)) == 0)
1706                                             && (c = strstr (h->h_name, domain))
1707                                             && (c != h->h_name) && (*(--c) == '.')) {
1708                                                 strncpy (host, h->h_name,
1709                                                         min(hostlen, (size_t) (c - h->h_name)));
1710                                                 host[min(hostlen - 1, (size_t) (c - h->h_name))] = '\0';
1711                                                 ok = 1;
1712                                         } else {
1713                                                 strncpy (host, h->h_name, hostlen);
1714                                                 ok = 1;
1715                                         }
1716                                  }
1717                         }
1718
1719                         if (!ok) {
1720                                 if (flags & NI_NAMEREQD) {
1721                                         errno = serrno;
1722                                         return EAI_NONAME;
1723                                 } else {
1724                                         const char *c;
1725 #ifdef __UCLIBC_HAS_IPV6__
1726                                         if (sa->sa_family == AF_INET6) {
1727                                                 const struct sockaddr_in6 *sin6p;
1728
1729                                                 sin6p = (const struct sockaddr_in6 *) sa;
1730
1731                                                 c = inet_ntop (AF_INET6,
1732                                                         (const void *) &sin6p->sin6_addr, host, hostlen);
1733 #if 0
1734 /* Does scope id need to be supported? */
1735                                                 uint32_t scopeid;
1736                                                 scopeid = sin6p->sin6_scope_id;
1737                                                 if (scopeid != 0) {
1738                                                         /* Buffer is >= IFNAMSIZ+1.  */
1739                                                         char scopebuf[IFNAMSIZ + 1];
1740                                                         char *scopeptr;
1741                                                         int ni_numericscope = 0;
1742                                                         size_t real_hostlen = __strnlen (host, hostlen);
1743                                                         size_t scopelen = 0;
1744
1745                                                         scopebuf[0] = SCOPE_DELIMITER;
1746                                                         scopebuf[1] = '\0';
1747                                                         scopeptr = &scopebuf[1];
1748
1749                                                         if (IN6_IS_ADDR_LINKLOCAL (&sin6p->sin6_addr)
1750                                                             || IN6_IS_ADDR_MC_LINKLOCAL (&sin6p->sin6_addr)) {
1751                                                                 if (if_indextoname (scopeid, scopeptr) == NULL)
1752                                                                         ++ni_numericscope;
1753                                                                 else
1754                                                                         scopelen = strlen (scopebuf);
1755                                                         } else {
1756                                                                 ++ni_numericscope;
1757                             }
1758
1759                                                         if (ni_numericscope)
1760                                                                 scopelen = 1 + snprintf (scopeptr,
1761                                                                         (scopebuf
1762                                                                         + sizeof scopebuf
1763                                                                         - scopeptr),
1764                                                                         "%u", scopeid);
1765
1766                                                         if (real_hostlen + scopelen + 1 > hostlen)
1767                                                                 return EAI_SYSTEM;
1768                                                         memcpy (host + real_hostlen, scopebuf, scopelen + 1);
1769                                                 }
1770 #endif
1771                                         } else
1772 #endif /* __UCLIBC_HAS_IPV6__ */
1773                                                 c = inet_ntop (AF_INET,
1774                                                         (const void *) &(((const struct sockaddr_in *) sa)->sin_addr),
1775                                                         host, hostlen);
1776
1777                                         if (c == NULL) {
1778                                                 errno = serrno;
1779                                                 return EAI_SYSTEM;
1780                                         }
1781                                 }
1782                                 ok = 1;
1783                         }
1784                         break;
1785
1786                 case AF_LOCAL:
1787                         if (!(flags & NI_NUMERICHOST)) {
1788                                 struct utsname utsname;
1789
1790                                 if (!uname (&utsname)) {
1791                                         strncpy (host, utsname.nodename, hostlen);
1792                                         break;
1793                                 };
1794                         };
1795
1796                         if (flags & NI_NAMEREQD) {
1797                                 errno = serrno;
1798                                 return EAI_NONAME;
1799                         }
1800
1801                         strncpy (host, "localhost", hostlen);
1802                         break;
1803
1804                 default:
1805                         return EAI_FAMILY;
1806         }
1807
1808         if (serv && (servlen > 0)) {
1809                 switch (sa->sa_family) {
1810                 case AF_INET:
1811 #ifdef __UCLIBC_HAS_IPV6__
1812                 case AF_INET6:
1813 #endif /* __UCLIBC_HAS_IPV6__ */
1814                         if (!(flags & NI_NUMERICSERV)) {
1815                                 struct servent *s;
1816                                 s = getservbyport (((const struct sockaddr_in *) sa)->sin_port,
1817                                       ((flags & NI_DGRAM) ? "udp" : "tcp"));
1818                                 if (s) {
1819                                         strncpy (serv, s->s_name, servlen);
1820                                         break;
1821                                 }
1822                         }
1823                         snprintf (serv, servlen, "%d",
1824                                 ntohs (((const struct sockaddr_in *) sa)->sin_port));
1825                         break;
1826
1827                 case AF_LOCAL:
1828                         strncpy (serv, ((const struct sockaddr_un *) sa)->sun_path, servlen);
1829                         break;
1830                 }
1831         }
1832         if (host && (hostlen > 0))
1833                 host[hostlen-1] = 0;
1834         if (serv && (servlen > 0))
1835                 serv[servlen-1] = 0;
1836         errno = serrno;
1837         return 0;
1838 }
1839 #endif
1840
1841
1842 #ifdef L_gethostbyname_r
1843
1844 int gethostbyname_r(const char * name,
1845                             struct hostent * result_buf,
1846                             char * buf, size_t buflen,
1847                             struct hostent ** result,
1848                             int * h_errnop)
1849 {
1850         struct in_addr *in;
1851         struct in_addr **addr_list;
1852         char **alias;
1853         unsigned char *packet;
1854         struct resolv_answer a;
1855         int i;
1856         int nest = 0;
1857         int __nameserversXX;
1858         char ** __nameserverXX;
1859
1860         if (__open_nameservers()) {
1861                 return(-1);
1862         }
1863
1864         *result=NULL;
1865         if (!name)
1866                 return EINVAL;
1867
1868         /* do /etc/hosts first */
1869         {
1870                 int old_errno = errno;  /* Save the old errno and reset errno */
1871                 __set_errno(0);                 /* to check for missing /etc/hosts. */
1872
1873                 if ((i=__get_hosts_byname_r(name, AF_INET, result_buf,
1874                                                                         buf, buflen, result, h_errnop))==0)
1875                         return i;
1876                 switch (*h_errnop) {
1877                         case HOST_NOT_FOUND:
1878                         case NO_ADDRESS:
1879                                 break;
1880                         case NETDB_INTERNAL:
1881                                 if (errno == ENOENT) {
1882                                         break;
1883                                 }
1884                                 /* else fall through */
1885                         default:
1886                                 return i;
1887                 }
1888                 __set_errno(old_errno);
1889         }
1890
1891         DPRINTF("Nothing found in /etc/hosts\n");
1892
1893         *h_errnop = NETDB_INTERNAL;
1894         if (buflen < sizeof(*in))
1895                 return ERANGE;
1896         in=(struct in_addr*)buf;
1897         buf+=sizeof(*in);
1898         buflen-=sizeof(*in);
1899
1900         if (buflen < sizeof(*addr_list)*2)
1901                 return ERANGE;
1902         addr_list=(struct in_addr**)buf;
1903         buf+=sizeof(*addr_list)*2;
1904         buflen-=sizeof(*addr_list)*2;
1905
1906         addr_list[0] = in;
1907         addr_list[1] = 0;
1908
1909         if (buflen < sizeof(char *)*(ALIAS_DIM))
1910                 return ERANGE;
1911         alias=(char **)buf;
1912         buf+=sizeof(char **)*(ALIAS_DIM);
1913         buflen-=sizeof(char **)*(ALIAS_DIM);
1914
1915         if (buflen<256)
1916                 return ERANGE;
1917         strncpy(buf, name, buflen);
1918
1919         alias[0] = buf;
1920         alias[1] = NULL;
1921
1922         /* First check if this is already an address */
1923         if (inet_aton(name, in)) {
1924             result_buf->h_name = buf;
1925             result_buf->h_addrtype = AF_INET;
1926             result_buf->h_length = sizeof(*in);
1927             result_buf->h_addr_list = (char **) addr_list;
1928             result_buf->h_aliases = alias;
1929             *result=result_buf;
1930             *h_errnop = NETDB_SUCCESS;
1931             return NETDB_SUCCESS;
1932         }
1933
1934         for (;;) {
1935
1936         BIGLOCK;
1937         __nameserversXX=__nameservers;
1938         __nameserverXX=__nameserver;
1939         BIGUNLOCK;
1940                 i = __dns_lookup(buf, T_A, __nameserversXX, __nameserverXX, &packet, &a);
1941
1942                 if (i < 0) {
1943                         *h_errnop = HOST_NOT_FOUND;
1944                         DPRINTF("__dns_lookup\n");
1945                         return TRY_AGAIN;
1946                 }
1947
1948                 strncpy(buf, a.dotted, buflen);
1949                 free(a.dotted);
1950
1951                 if (a.atype == T_CNAME) {               /* CNAME */
1952                         DPRINTF("Got a CNAME in gethostbyname()\n");
1953                         i = __decode_dotted(packet, a.rdoffset, buf, buflen);
1954                         free(packet);
1955
1956                         if (i < 0) {
1957                                 *h_errnop = NO_RECOVERY;
1958                                 DPRINTF("__decode_dotted\n");
1959                                 return -1;
1960                         }
1961                         if (++nest > MAX_RECURSE) {
1962                                 *h_errnop = NO_RECOVERY;
1963                                 DPRINTF("recursion\n");
1964                                 return -1;
1965                         }
1966                         continue;
1967                 } else if (a.atype == T_A) {    /* ADDRESS */
1968                         memcpy(in, a.rdata, sizeof(*in));
1969                         result_buf->h_name = buf;
1970                         result_buf->h_addrtype = AF_INET;
1971                         result_buf->h_length = sizeof(*in);
1972                         result_buf->h_addr_list = (char **) addr_list;
1973 #ifdef __UCLIBC_MJN3_ONLY__
1974 #warning TODO -- generate the full list
1975 #endif
1976                         result_buf->h_aliases = alias; /* TODO: generate the full list */
1977                         free(packet);
1978                         break;
1979                 } else {
1980                         free(packet);
1981                         *h_errnop=HOST_NOT_FOUND;
1982                         return TRY_AGAIN;
1983                 }
1984         }
1985
1986         *result=result_buf;
1987         *h_errnop = NETDB_SUCCESS;
1988         return NETDB_SUCCESS;
1989 }
1990 #endif
1991
1992 #ifdef L_gethostbyname2_r
1993
1994 int gethostbyname2_r(const char *name, int family,
1995                             struct hostent * result_buf,
1996                             char * buf, size_t buflen,
1997                             struct hostent ** result,
1998                             int * h_errnop)
1999 {
2000 #ifndef __UCLIBC_HAS_IPV6__
2001         return family == AF_INET ? gethostbyname_r(name, result_buf, buf, buflen, result, h_errnop) : HOST_NOT_FOUND;
2002 #else /* __UCLIBC_HAS_IPV6__ */
2003         struct in6_addr *in;
2004         struct in6_addr **addr_list;
2005         unsigned char *packet;
2006         struct resolv_answer a;
2007         int i;
2008         int nest = 0;
2009         int __nameserversXX;
2010         char ** __nameserverXX;
2011
2012         if (family == AF_INET)
2013                 return gethostbyname_r(name, result_buf, buf, buflen, result, h_errnop);
2014                 
2015         if (family != AF_INET6)
2016                 return EINVAL;
2017                 
2018         if (__open_nameservers()) {
2019                 return(-1);
2020         }
2021
2022         *result=NULL;
2023         if (!name)
2024                 return EINVAL;
2025
2026         /* do /etc/hosts first */
2027         {
2028                 int old_errno = errno;  /* Save the old errno and reset errno */
2029                 __set_errno(0);                 /* to check for missing /etc/hosts. */
2030
2031                 if ((i=__get_hosts_byname_r(name, AF_INET, result_buf,
2032                                                                         buf, buflen, result, h_errnop))==0)
2033                         return i;
2034                 switch (*h_errnop) {
2035                         case HOST_NOT_FOUND:
2036                         case NO_ADDRESS:
2037                                 break;
2038                         case NETDB_INTERNAL:
2039                                 if (errno == ENOENT) {
2040                                         break;
2041                                 }
2042                                 /* else fall through */
2043                         default:
2044                                 return i;
2045                 }
2046                 __set_errno(old_errno);
2047         }
2048
2049         DPRINTF("Nothing found in /etc/hosts\n");
2050
2051         *h_errnop = NETDB_INTERNAL;
2052         if (buflen < sizeof(*in))
2053                 return ERANGE;
2054         in=(struct in6_addr*)buf;
2055         buf+=sizeof(*in);
2056         buflen-=sizeof(*in);
2057
2058         if (buflen < sizeof(*addr_list)*2)
2059                 return ERANGE;
2060         addr_list=(struct in6_addr**)buf;
2061         buf+=sizeof(*addr_list)*2;
2062         buflen-=sizeof(*addr_list)*2;
2063
2064         addr_list[0] = in;
2065         addr_list[1] = 0;
2066         
2067         if (buflen<256)
2068                 return ERANGE;
2069         strncpy(buf, name, buflen);
2070
2071         /* First check if this is already an address */
2072         if (inet_pton(AF_INET6, name, in)) {
2073             result_buf->h_name = buf;
2074             result_buf->h_addrtype = AF_INET6;
2075             result_buf->h_length = sizeof(*in);
2076             result_buf->h_addr_list = (char **) addr_list;
2077             *result=result_buf;
2078             *h_errnop = NETDB_SUCCESS;
2079             return NETDB_SUCCESS;
2080         }
2081
2082         for (;;) {
2083         BIGLOCK;
2084         __nameserversXX=__nameservers;
2085         __nameserverXX=__nameserver;
2086         BIGUNLOCK;
2087
2088                 i = __dns_lookup(buf, T_AAAA, __nameserversXX, __nameserverXX, &packet, &a);
2089
2090                 if (i < 0) {
2091                         *h_errnop = HOST_NOT_FOUND;
2092                         return TRY_AGAIN;
2093                 }
2094
2095                 strncpy(buf, a.dotted, buflen);
2096                 free(a.dotted);
2097
2098                 if (a.atype == T_CNAME) {               /* CNAME */
2099                         DPRINTF("Got a CNAME in gethostbyname()\n");
2100                         i = __decode_dotted(packet, a.rdoffset, buf, buflen);
2101                         free(packet);
2102
2103                         if (i < 0) {
2104                                 *h_errnop = NO_RECOVERY;
2105                                 return -1;
2106                         }
2107                         if (++nest > MAX_RECURSE) {
2108                                 *h_errnop = NO_RECOVERY;
2109                                 return -1;
2110                         }
2111                         continue;
2112                 } else if (a.atype == T_AAAA) { /* ADDRESS */
2113                         memcpy(in, a.rdata, sizeof(*in));
2114                         result_buf->h_name = buf;
2115                         result_buf->h_addrtype = AF_INET6;
2116                         result_buf->h_length = sizeof(*in);
2117                         result_buf->h_addr_list = (char **) addr_list;
2118                         free(packet);
2119                         break;
2120                 } else {
2121                         free(packet);
2122                         *h_errnop=HOST_NOT_FOUND;
2123                         return TRY_AGAIN;
2124                 }
2125         }
2126
2127         *result=result_buf;
2128         *h_errnop = NETDB_SUCCESS;
2129         return NETDB_SUCCESS;
2130 #endif /* __UCLIBC_HAS_IPV6__ */
2131 }
2132 #endif
2133
2134 #ifdef L_gethostbyaddr_r
2135 int gethostbyaddr_r (const void *addr, socklen_t len, int type,
2136                             struct hostent * result_buf,
2137                             char * buf, size_t buflen,
2138                             struct hostent ** result,
2139                             int * h_errnop)
2140
2141 {
2142         struct in_addr *in;
2143         struct in_addr **addr_list;
2144 #ifdef __UCLIBC_HAS_IPV6__
2145         char *qp;
2146         size_t plen;
2147         struct in6_addr *in6;
2148         struct in6_addr **addr_list6;
2149 #endif /* __UCLIBC_HAS_IPV6__ */
2150         unsigned char *packet;
2151         struct resolv_answer a;
2152         int i;
2153         int nest = 0;
2154         int __nameserversXX;
2155         char ** __nameserverXX;
2156
2157         *result=NULL;
2158         if (!addr)
2159                 return EINVAL;
2160         
2161         switch (type) {
2162                 case AF_INET:
2163                         if (len != sizeof(struct in_addr))
2164                                 return EINVAL;
2165                         break;
2166 #ifdef __UCLIBC_HAS_IPV6__
2167                 case AF_INET6:
2168                         if (len != sizeof(struct in6_addr))
2169                                 return EINVAL;
2170                         break;
2171 #endif /* __UCLIBC_HAS_IPV6__ */
2172                 default:
2173                         return EINVAL;
2174         }
2175
2176         /* do /etc/hosts first */
2177         if ((i=__get_hosts_byaddr_r(addr, len, type, result_buf,
2178                                   buf, buflen, result, h_errnop))==0)
2179                 return i;
2180         switch (*h_errnop) {
2181                 case HOST_NOT_FOUND:
2182                 case NO_ADDRESS:
2183                         break;
2184                 default:
2185                         return i;
2186         }
2187
2188         if (__open_nameservers()) {
2189                 return(-1);
2190         }
2191
2192 #ifdef __UCLIBC_HAS_IPV6__
2193         qp=buf;
2194         plen=buflen;
2195 #endif /* __UCLIBC_HAS_IPV6__ */
2196
2197         *h_errnop = NETDB_INTERNAL;
2198         if (buflen < sizeof(*in))
2199                 return ERANGE;
2200         in=(struct in_addr*)buf;
2201         buf+=sizeof(*in);
2202         buflen-=sizeof(*in);
2203
2204         if (buflen < sizeof(*addr_list)*2)
2205                 return ERANGE;
2206         addr_list=(struct in_addr**)buf;
2207         buf+=sizeof(*addr_list)*2;
2208         buflen-=sizeof(*addr_list)*2;
2209
2210 #ifdef __UCLIBC_HAS_IPV6__
2211         if (plen < sizeof(*in6))
2212                 return ERANGE;
2213         in6=(struct in6_addr*)qp;
2214         qp+=sizeof(*in6);
2215         plen-=sizeof(*in6);
2216
2217         if (plen < sizeof(*addr_list6)*2)
2218                 return ERANGE;
2219         addr_list6=(struct in6_addr**)qp;
2220         qp+=sizeof(*addr_list6)*2;
2221         plen-=sizeof(*addr_list6)*2;
2222
2223         if (plen < buflen) {
2224                 buflen=plen;
2225                 buf=qp;
2226         }
2227 #endif /* __UCLIBC_HAS_IPV6__ */
2228
2229         if (buflen<256)
2230                 return ERANGE;
2231
2232         if(type == AF_INET) {
2233                 unsigned char *tmp_addr = (unsigned char *)addr;
2234
2235                 memcpy(&in->s_addr, addr, len);
2236
2237                 addr_list[0] = in;
2238
2239                 sprintf(buf, "%u.%u.%u.%u.in-addr.arpa",
2240                         tmp_addr[3], tmp_addr[2], tmp_addr[1], tmp_addr[0]);
2241 #ifdef __UCLIBC_HAS_IPV6__
2242         } else {
2243                 memcpy(in6->s6_addr, addr, len);
2244
2245                 addr_list6[0] = in6;
2246                 qp = buf;
2247
2248                 for (i = len - 1; i >= 0; i--) {
2249                         qp += sprintf(qp, "%x.%x.", in6->s6_addr[i] & 0xf,
2250                                 (in6->s6_addr[i] >> 4) & 0xf);
2251         }
2252         strcpy(qp, "ip6.int");
2253 #endif /* __UCLIBC_HAS_IPV6__ */
2254         }
2255
2256         addr_list[1] = 0;
2257
2258         for (;;) {
2259
2260         BIGLOCK;
2261         __nameserversXX=__nameservers;
2262         __nameserverXX=__nameserver;
2263         BIGUNLOCK;
2264                 i = __dns_lookup(buf, T_PTR, __nameserversXX, __nameserverXX, &packet, &a);
2265
2266                 if (i < 0) {
2267                         *h_errnop = HOST_NOT_FOUND;
2268                         return TRY_AGAIN;
2269                 }
2270
2271                 strncpy(buf, a.dotted, buflen);
2272                 free(a.dotted);
2273
2274                 if (a.atype == T_CNAME) {               /* CNAME */
2275                         DPRINTF("Got a CNAME in gethostbyaddr()\n");
2276                         i = __decode_dotted(packet, a.rdoffset, buf, buflen);
2277                         free(packet);
2278
2279                         if (i < 0) {
2280                                 *h_errnop = NO_RECOVERY;
2281                                 return -1;
2282                         }
2283                         if (++nest > MAX_RECURSE) {
2284                                 *h_errnop = NO_RECOVERY;
2285                                 return -1;
2286                         }
2287                         continue;
2288                 } else if (a.atype == T_PTR) {  /* ADDRESS */
2289                         i = __decode_dotted(packet, a.rdoffset, buf, buflen);
2290                         free(packet);
2291
2292                         result_buf->h_name = buf;
2293                         result_buf->h_addrtype = type;
2294
2295                         if(type == AF_INET) {
2296                                 result_buf->h_length = sizeof(*in);
2297 #ifdef __UCLIBC_HAS_IPV6__
2298                         } else {
2299                                 result_buf->h_length = sizeof(*in6);
2300 #endif /* __UCLIBC_HAS_IPV6__ */
2301                 }
2302
2303                         result_buf->h_addr_list = (char **) addr_list;
2304                         break;
2305                 } else {
2306                         free(packet);
2307                         *h_errnop = NO_ADDRESS;
2308                         return TRY_AGAIN;
2309                 }
2310         }
2311
2312         *result=result_buf;
2313         *h_errnop = NETDB_SUCCESS;
2314         return NETDB_SUCCESS;
2315 }
2316 #endif
2317
2318 #ifdef L_res_comp
2319 /*
2320  * Expand compressed domain name 'comp_dn' to full domain name.
2321  * 'msg' is a pointer to the begining of the message,
2322  * 'eomorig' points to the first location after the message,
2323  * 'exp_dn' is a pointer to a buffer of size 'length' for the result.
2324  * Return size of compressed name or -1 if there was an error.
2325  */
2326 int __dn_expand(const u_char *msg, const u_char *eom, const u_char *src,
2327           char *dst, int dstsiz)
2328 {
2329         int n = ns_name_uncompress(msg, eom, src, dst, (size_t)dstsiz);
2330
2331         if (n > 0 && dst[0] == '.')
2332                 dst[0] = '\0';
2333         return (n);
2334 }
2335 #endif /* L_res_comp */
2336
2337 #ifdef L_ns_name
2338 /*
2339  * printable(ch)
2340  *      Thinking in noninternationalized USASCII (per the DNS spec),
2341  *      is this character visible and not a space when printed ?
2342  * return:
2343  *      boolean.
2344  */
2345 static int printable(int ch) 
2346 {
2347         return (ch > 0x20 && ch < 0x7f);
2348 }
2349
2350 /*
2351  * special(ch)
2352  *      Thinking in noninternationalized USASCII (per the DNS spec),
2353  *      is this characted special ("in need of quoting") ?
2354  * return:
2355  *      boolean.
2356  */
2357 static int special(int ch) 
2358 {
2359         switch (ch) {
2360         case 0x22: /* '"' */
2361         case 0x2E: /* '.' */
2362         case 0x3B: /* ';' */
2363         case 0x5C: /* '\\' */
2364         /* Special modifiers in zone files. */
2365         case 0x40: /* '@' */
2366         case 0x24: /* '$' */
2367                 return (1);
2368         default:
2369                 return (0);
2370         }
2371 }
2372
2373 /*
2374  * ns_name_uncompress(msg, eom, src, dst, dstsiz)
2375  *      Expand compressed domain name to presentation format.
2376  * return:
2377  *      Number of bytes read out of `src', or -1 (with errno set).
2378  * note:
2379  *      Root domain returns as "." not "".
2380  */
2381 int __ns_name_uncompress(const u_char *msg, const u_char *eom, 
2382                 const u_char *src, char *dst, size_t dstsiz)
2383 {
2384         u_char tmp[NS_MAXCDNAME];
2385         int n;
2386
2387         if ((n = ns_name_unpack(msg, eom, src, tmp, sizeof tmp)) == -1)
2388                 return (-1);
2389         if (ns_name_ntop(tmp, dst, dstsiz) == -1)
2390                 return (-1);
2391         return (n);
2392 }
2393
2394
2395 /*
2396  * ns_name_ntop(src, dst, dstsiz)
2397  *      Convert an encoded domain name to printable ascii as per RFC1035.
2398  * return:
2399  *      Number of bytes written to buffer, or -1 (with errno set)
2400  * notes:
2401  *      The root is returned as "."
2402  *      All other domains are returned in non absolute form
2403  */
2404 int __ns_name_ntop(const u_char *src, char *dst, size_t dstsiz) {
2405         const u_char *cp;
2406         char *dn, *eom;
2407         u_char c;
2408         u_int n;
2409         const char digits[] = "0123456789";
2410
2411         cp = src;
2412         dn = dst;
2413         eom = dst + dstsiz;
2414
2415         while ((n = *cp++) != 0) {
2416                 if ((n & NS_CMPRSFLGS) != 0) {
2417                         /* Some kind of compression pointer. */
2418                         __set_errno (EMSGSIZE);
2419                         return (-1);
2420                 }
2421                 if (dn != dst) {
2422                         if (dn >= eom) {
2423                                 __set_errno (EMSGSIZE);
2424                                 return (-1);
2425                         }
2426                         *dn++ = '.';
2427                 }
2428                 if (dn + n >= eom) {
2429                         __set_errno (EMSGSIZE);
2430                         return (-1);
2431                 }
2432                 for ((void)NULL; n > 0; n--) {
2433                         c = *cp++;
2434                         if (special(c)) {
2435                                 if (dn + 1 >= eom) {
2436                                         __set_errno (EMSGSIZE);
2437                                         return (-1);
2438                                 }
2439                                 *dn++ = '\\';
2440                                 *dn++ = (char)c;
2441                         } else if (!printable(c)) {
2442                                 if (dn + 3 >= eom) {
2443                                         __set_errno (EMSGSIZE);
2444                                         return (-1);
2445                                 }
2446                                 *dn++ = '\\';
2447                                 *dn++ = digits[c / 100];
2448                                 *dn++ = digits[(c % 100) / 10];
2449                                 *dn++ = digits[c % 10];
2450                         } else {
2451                                 if (dn >= eom) {
2452                                         __set_errno (EMSGSIZE);
2453                                         return (-1);
2454                                 }
2455                                 *dn++ = (char)c;
2456                         }
2457                 }
2458         }
2459         if (dn == dst) {
2460                 if (dn >= eom) {
2461                         __set_errno (EMSGSIZE);
2462                         return (-1);
2463                 }
2464                 *dn++ = '.';
2465         }
2466         if (dn >= eom) {
2467                 __set_errno (EMSGSIZE);
2468                 return (-1);
2469         }
2470         *dn++ = '\0';
2471         return (dn - dst);
2472 }
2473
2474 /*
2475  * ns_name_unpack(msg, eom, src, dst, dstsiz)
2476  *      Unpack a domain name from a message, source may be compressed.
2477  * return:
2478  *      -1 if it fails, or consumed octets if it succeeds.
2479  */
2480 int __ns_name_unpack(const u_char *msg, const u_char *eom, const u_char *src,
2481                u_char *dst, size_t dstsiz)
2482 {
2483         const u_char *srcp, *dstlim;
2484         u_char *dstp;
2485         int n, len, checked;
2486
2487         len = -1;
2488         checked = 0;
2489         dstp = dst;
2490         srcp = src;
2491         dstlim = dst + dstsiz;
2492         if (srcp < msg || srcp >= eom) {
2493                 __set_errno (EMSGSIZE);
2494                 return (-1);
2495         }
2496         /* Fetch next label in domain name. */
2497         while ((n = *srcp++) != 0) {
2498                 /* Check for indirection. */
2499                 switch (n & NS_CMPRSFLGS) {
2500                 case 0:
2501                         /* Limit checks. */
2502                         if (dstp + n + 1 >= dstlim || srcp + n >= eom) {
2503                                 __set_errno (EMSGSIZE);
2504                                 return (-1);
2505                         }
2506                         checked += n + 1;
2507                         *dstp++ = n;
2508                         memcpy(dstp, srcp, n);
2509                         dstp += n;
2510                         srcp += n;
2511                         break;
2512
2513                 case NS_CMPRSFLGS:
2514                         if (srcp >= eom) {
2515                                 __set_errno (EMSGSIZE);
2516                                 return (-1);
2517                         }
2518                         if (len < 0)
2519                                 len = srcp - src + 1;
2520                         srcp = msg + (((n & 0x3f) << 8) | (*srcp & 0xff));
2521                         if (srcp < msg || srcp >= eom) {  /* Out of range. */
2522                                 __set_errno (EMSGSIZE);
2523                                 return (-1);
2524                         }
2525                         checked += 2;
2526                         /*
2527                          * Check for loops in the compressed name;
2528                          * if we've looked at the whole message,
2529                          * there must be a loop.
2530                          */
2531                         if (checked >= eom - msg) {
2532                                 __set_errno (EMSGSIZE);
2533                                 return (-1);
2534                         }
2535                         break;
2536
2537                 default:
2538                         __set_errno (EMSGSIZE);
2539                         return (-1);                    /* flag error */
2540                 }
2541         }
2542         *dstp = '\0';
2543         if (len < 0)
2544                 len = srcp - src;
2545         return (len);
2546 }
2547 #endif /* L_ns_name */