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