OSDN Git Service

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