OSDN Git Service

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