OSDN Git Service

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