OSDN Git Service

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