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