OSDN Git Service

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