1 /* resolv.c: DNS Resolver
3 * Copyright (C) 1998 Kenneth Albanowski <kjahds@kjahds.com>,
4 * The Silver Hammer Group, Ltd.
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.
13 * Portions Copyright (c) 1985, 1993
14 * The Regents of the University of California. All rights reserved.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
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.
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
42 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
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.
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
62 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
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.
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
80 * 5-Oct-2000 W. Greathouse wgreathouse@smva.com
81 * Fix memory leak and memory corruption.
82 * -- Every name resolution resulted in
83 * a new parse of resolv.conf and new
84 * copy of nameservers allocated by
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.
91 * Limit nameservers read from resolv.conf
93 * Add "search" domains from resolv.conf
95 * Some systems will return a security
96 * signature along with query answer for
97 * dynamic DNS entries.
98 * -- skip/ignore this answer
100 * Include arpa/nameser.h for defines.
104 * 20-Jun-2001 Michal Moskal <malekith@pld.org.pl>
105 * partial IPv6 support (i.e. gethostbyname2() and resolve_address2()
106 * functions added), IPv6 nameservers are also supported.
108 * 6-Oct-2001 Jari Korva <jari.korva@iki.fi>
109 * more IPv6 support (IPv6 support for gethostbyaddr();
110 * address family parameter and improved IPv6 support for get_hosts_byname
111 * and read_etc_hosts; getnameinfo() port from glibc; defined
112 * defined ip6addr_any and in6addr_loopback)
114 * 2-Feb-2002 Erik Andersen <andersen@codepoet.org>
115 * Added gethostent(), sethostent(), and endhostent()
117 * 17-Aug-2002 Manuel Novoa III <mjn3@codepoet.org>
118 * Fixed __read_etc_hosts_r to return alias list, and modified buffer
119 * allocation accordingly. See MAX_ALIASES and ALIAS_DIM below.
120 * This fixes the segfault in the Python 2.2.1 socket test.
122 * 04-Jan-2003 Jay Kulpinski <jskulpin@berkshire.rr.com>
123 * Fixed __decode_dotted to count the terminating null character
126 * 02-Oct-2003 Tony J. White <tjw@tjw.org>
127 * Lifted dn_expand() and dependent ns_name_uncompress(), ns_name_unpack(),
128 * and ns_name_ntop() from glibc 2.3.2 for compatibility with ipsec-tools
131 * 7-Sep-2004 Erik Andersen <andersen@codepoet.org>
132 * Added gethostent_r()
136 #define __FORCE_GLIBC
137 #include <features.h>
143 #include <sys/socket.h>
144 #include <sys/types.h>
145 #include <sys/time.h>
146 #include <netinet/in.h>
147 #include <arpa/inet.h>
154 #include <arpa/nameser.h>
155 #include <sys/utsname.h>
157 #include <bits/uClibc_mutex.h>
159 __UCLIBC_MUTEX_EXTERN(__resolv_lock);
161 libc_hidden_proto(memcpy)
162 libc_hidden_proto(memset)
163 libc_hidden_proto(memmove)
164 libc_hidden_proto(strchr)
165 libc_hidden_proto(strcmp)
166 libc_hidden_proto(strcpy)
167 libc_hidden_proto(strdup)
168 libc_hidden_proto(strlen)
169 libc_hidden_proto(strncat)
170 libc_hidden_proto(strncpy)
171 /* libc_hidden_proto(strnlen) */
172 libc_hidden_proto(strstr)
173 libc_hidden_proto(strcasecmp)
174 libc_hidden_proto(socket)
175 libc_hidden_proto(close)
176 libc_hidden_proto(fopen)
177 libc_hidden_proto(fclose)
178 libc_hidden_proto(random)
179 libc_hidden_proto(getservbyport)
180 libc_hidden_proto(getdomainname)
181 libc_hidden_proto(uname)
182 libc_hidden_proto(inet_addr)
183 libc_hidden_proto(inet_aton)
184 libc_hidden_proto(inet_pton)
185 libc_hidden_proto(inet_ntop)
186 libc_hidden_proto(connect)
187 libc_hidden_proto(select)
188 libc_hidden_proto(recv)
189 libc_hidden_proto(send)
190 libc_hidden_proto(printf)
191 libc_hidden_proto(sprintf)
192 libc_hidden_proto(snprintf)
193 libc_hidden_proto(fgets)
194 libc_hidden_proto(gethostbyname)
195 libc_hidden_proto(gethostbyname_r)
196 libc_hidden_proto(gethostbyname2_r)
197 libc_hidden_proto(gethostbyaddr)
198 libc_hidden_proto(gethostbyaddr_r)
199 libc_hidden_proto(ns_name_uncompress)
200 libc_hidden_proto(ns_name_unpack)
201 libc_hidden_proto(ns_name_ntop)
202 libc_hidden_proto(res_init)
203 libc_hidden_proto(res_query)
204 libc_hidden_proto(res_querydomain)
205 libc_hidden_proto(gethostent_r)
206 libc_hidden_proto(fprintf)
207 libc_hidden_proto(__h_errno_location)
208 #ifdef __UCLIBC_HAS_XLOCALE__
209 libc_hidden_proto(__ctype_b_loc)
210 #elif __UCLIBC_HAS_CTYPE_TABLES__
211 libc_hidden_proto(__ctype_b)
216 #define MAX_RECURSE 5
217 #define REPLY_TIMEOUT 10
218 #define MAX_RETRIES 3
219 #define MAX_SERVERS 3
222 #define MAX_ALIASES 5
224 /* 1:ip + 1:full + MAX_ALIASES:aliases + 1:NULL */
225 #define ALIAS_DIM (2 + MAX_ALIASES + 1)
231 #define DPRINTF(X,args...) fprintf(stderr, X, ##args)
233 #define DPRINTF(X,args...)
237 /* Global stuff (stuff needing to be locked to be thread safe)... */
238 extern int __nameservers attribute_hidden;
239 extern char * __nameserver[MAX_SERVERS] attribute_hidden;
240 extern int __searchdomains attribute_hidden;
241 extern char * __searchdomain[MAX_SEARCH] attribute_hidden;
248 struct resolv_header {
250 int qr,opcode,aa,tc,rd,ra,rcode;
257 struct resolv_question {
263 struct resolv_answer {
269 const unsigned char * rdata;
276 enum etc_hosts_action {
277 GET_HOSTS_BYNAME = 0,
282 /* function prototypes */
283 extern int __get_hosts_byname_r(const char * name, int type,
284 struct hostent * result_buf,
285 char * buf, size_t buflen,
286 struct hostent ** result,
287 int * h_errnop) attribute_hidden;
288 extern int __get_hosts_byaddr_r(const char * addr, int len, int type,
289 struct hostent * result_buf,
290 char * buf, size_t buflen,
291 struct hostent ** result,
292 int * h_errnop) attribute_hidden;
293 extern void __open_etc_hosts(FILE **fp) attribute_hidden;
294 extern int __read_etc_hosts_r(FILE *fp, const char * name, int type,
295 enum etc_hosts_action action,
296 struct hostent * result_buf,
297 char * buf, size_t buflen,
298 struct hostent ** result,
299 int * h_errnop) attribute_hidden;
300 extern int __dns_lookup(const char * name, int type, int nscount,
301 char ** nsip, unsigned char ** outpacket, struct resolv_answer * a) attribute_hidden;
303 extern int __encode_dotted(const char * dotted, unsigned char * dest, int maxlen) attribute_hidden;
304 extern int __decode_dotted(const unsigned char * const message, int offset,
305 char * dest, int maxlen) attribute_hidden;
306 extern int __length_dotted(const unsigned char * const message, int offset) attribute_hidden;
307 extern int __encode_header(struct resolv_header * h, unsigned char * dest, int maxlen) attribute_hidden;
308 extern int __decode_header(unsigned char * data, struct resolv_header * h) attribute_hidden;
309 extern int __encode_question(const struct resolv_question * const q,
310 unsigned char * dest, int maxlen) attribute_hidden;
311 extern int __decode_question(const unsigned char * const message, int offset,
312 struct resolv_question * q) attribute_hidden;
313 extern int __encode_answer(struct resolv_answer * a,
314 unsigned char * dest, int maxlen) attribute_hidden;
315 extern int __decode_answer(const unsigned char * message, int offset,
316 struct resolv_answer * a) attribute_hidden;
317 extern int __length_question(const unsigned char * const message, int offset) attribute_hidden;
318 extern void __open_nameservers(void) attribute_hidden;
319 extern void __close_nameservers(void) attribute_hidden;
320 extern int __dn_expand(const u_char *, const u_char *, const u_char *,
324 int attribute_hidden __encode_header(struct resolv_header *h, unsigned char *dest, int maxlen)
326 if (maxlen < HFIXEDSZ)
329 dest[0] = (h->id & 0xff00) >> 8;
330 dest[1] = (h->id & 0x00ff) >> 0;
331 dest[2] = (h->qr ? 0x80 : 0) |
332 ((h->opcode & 0x0f) << 3) |
336 dest[3] = (h->ra ? 0x80 : 0) | (h->rcode & 0x0f);
337 dest[4] = (h->qdcount & 0xff00) >> 8;
338 dest[5] = (h->qdcount & 0x00ff) >> 0;
339 dest[6] = (h->ancount & 0xff00) >> 8;
340 dest[7] = (h->ancount & 0x00ff) >> 0;
341 dest[8] = (h->nscount & 0xff00) >> 8;
342 dest[9] = (h->nscount & 0x00ff) >> 0;
343 dest[10] = (h->arcount & 0xff00) >> 8;
344 dest[11] = (h->arcount & 0x00ff) >> 0;
351 int attribute_hidden __decode_header(unsigned char *data, struct resolv_header *h)
353 h->id = (data[0] << 8) | data[1];
354 h->qr = (data[2] & 0x80) ? 1 : 0;
355 h->opcode = (data[2] >> 3) & 0x0f;
356 h->aa = (data[2] & 0x04) ? 1 : 0;
357 h->tc = (data[2] & 0x02) ? 1 : 0;
358 h->rd = (data[2] & 0x01) ? 1 : 0;
359 h->ra = (data[3] & 0x80) ? 1 : 0;
360 h->rcode = data[3] & 0x0f;
361 h->qdcount = (data[4] << 8) | data[5];
362 h->ancount = (data[6] << 8) | data[7];
363 h->nscount = (data[8] << 8) | data[9];
364 h->arcount = (data[10] << 8) | data[11];
371 /* Encode a dotted string into nameserver transport-level encoding.
372 This routine is fairly dumb, and doesn't attempt to compress
375 int attribute_hidden __encode_dotted(const char *dotted, unsigned char *dest, int maxlen)
379 while (dotted && *dotted) {
380 char *c = strchr(dotted, '.');
381 int l = c ? c - dotted : strlen(dotted);
383 if (l >= (maxlen - used - 1))
387 memcpy(dest + used, dotted, l);
406 /* Decode a dotted string from nameserver transport-level encoding.
407 This routine understands compressed data. */
409 int attribute_hidden __decode_dotted(const unsigned char * const data, int offset,
410 char *dest, int maxlen)
420 while ((l=data[offset++])) {
423 if ((l & 0xc0) == (0xc0)) {
426 /* compressed item, redirect */
427 offset = ((l & 0x3f) << 8) | data[offset];
432 if ((used + l + 1) >= maxlen)
435 memcpy(dest + used, data + offset, l);
441 if (data[offset] != 0)
447 /* The null byte must be counted too */
452 DPRINTF("Total decode len = %d\n", total);
459 int attribute_hidden __length_dotted(const unsigned char * const data, int offset)
461 int orig_offset = offset;
467 while ((l = data[offset++])) {
469 if ((l & 0xc0) == (0xc0)) {
477 return offset - orig_offset;
482 int attribute_hidden __encode_question(const struct resolv_question * const q,
483 unsigned char *dest, int maxlen)
487 i = __encode_dotted(q->dotted, dest, maxlen);
497 dest[0] = (q->qtype & 0xff00) >> 8;
498 dest[1] = (q->qtype & 0x00ff) >> 0;
499 dest[2] = (q->qclass & 0xff00) >> 8;
500 dest[3] = (q->qclass & 0x00ff) >> 0;
507 int attribute_hidden __decode_question(const unsigned char * const message, int offset,
508 struct resolv_question *q)
513 i = __decode_dotted(message, offset, temp, sizeof(temp));
519 q->dotted = strdup(temp);
520 q->qtype = (message[offset + 0] << 8) | message[offset + 1];
521 q->qclass = (message[offset + 2] << 8) | message[offset + 3];
528 int attribute_hidden __length_question(const unsigned char * const message, int offset)
532 i = __length_dotted(message, offset);
541 int attribute_hidden __encode_answer(struct resolv_answer *a, unsigned char *dest, int maxlen)
545 i = __encode_dotted(a->dotted, dest, maxlen);
552 if (maxlen < (RRFIXEDSZ+a->rdlength))
555 *dest++ = (a->atype & 0xff00) >> 8;
556 *dest++ = (a->atype & 0x00ff) >> 0;
557 *dest++ = (a->aclass & 0xff00) >> 8;
558 *dest++ = (a->aclass & 0x00ff) >> 0;
559 *dest++ = (a->ttl & 0xff000000) >> 24;
560 *dest++ = (a->ttl & 0x00ff0000) >> 16;
561 *dest++ = (a->ttl & 0x0000ff00) >> 8;
562 *dest++ = (a->ttl & 0x000000ff) >> 0;
563 *dest++ = (a->rdlength & 0xff00) >> 8;
564 *dest++ = (a->rdlength & 0x00ff) >> 0;
565 memcpy(dest, a->rdata, a->rdlength);
567 return i + RRFIXEDSZ + a->rdlength;
572 int attribute_hidden __decode_answer(const unsigned char *message, int offset,
573 struct resolv_answer *a)
578 i = __decode_dotted(message, offset, temp, sizeof(temp));
582 message += offset + i;
584 a->dotted = strdup(temp);
585 a->atype = (message[0] << 8) | message[1];
587 a->aclass = (message[0] << 8) | message[1];
589 a->ttl = (message[0] << 24) |
590 (message[1] << 16) | (message[2] << 8) | (message[3] << 0);
592 a->rdlength = (message[0] << 8) | message[1];
595 a->rdoffset = offset + i + RRFIXEDSZ;
597 DPRINTF("i=%d,rdlength=%d\n", i, a->rdlength);
599 return i + RRFIXEDSZ + a->rdlength;
604 int __encode_packet(struct resolv_header *h,
605 struct resolv_question **q,
606 struct resolv_answer **an,
607 struct resolv_answer **ns,
608 struct resolv_answer **ar,
609 unsigned char *dest, int maxlen) attribute_hidden;
610 int __encode_packet(struct resolv_header *h,
611 struct resolv_question **q,
612 struct resolv_answer **an,
613 struct resolv_answer **ns,
614 struct resolv_answer **ar,
615 unsigned char *dest, int maxlen)
620 i = __encode_header(h, dest, maxlen);
628 for (j = 0; j < h->qdcount; j++) {
629 i = __encode_question(q[j], dest, maxlen);
637 for (j = 0; j < h->ancount; j++) {
638 i = __encode_answer(an[j], dest, maxlen);
645 for (j = 0; j < h->nscount; j++) {
646 i = __encode_answer(ns[j], dest, maxlen);
653 for (j = 0; j < h->arcount; j++) {
654 i = __encode_answer(ar[j], dest, maxlen);
667 int __decode_packet(unsigned char *data, struct resolv_header *h) attribute_hidden;
668 int __decode_packet(unsigned char *data, struct resolv_header *h)
670 return __decode_header(data, h);
675 int __form_query(int id, const char *name, int type, unsigned char *packet, int maxlen);
676 int __form_query(int id, const char *name, int type, unsigned char *packet,
679 struct resolv_header h;
680 struct resolv_question q;
683 memset(&h, 0, sizeof(h));
687 q.dotted = (char *) name;
689 q.qclass = C_IN; /* CLASS_IN */
691 i = __encode_header(&h, packet, maxlen);
695 j = __encode_question(&q, packet + i, maxlen - i);
704 __UCLIBC_MUTEX_STATIC(mylock, PTHREAD_MUTEX_INITIALIZER);
706 /* Just for the record, having to lock __dns_lookup() just for these two globals
707 * is pretty lame. I think these two variables can probably be de-global-ized,
708 * which should eliminate the need for doing locking here... Needs a closer
710 static int ns=0, id=1;
712 int attribute_hidden __dns_lookup(const char *name, int type, int nscount, char **nsip,
713 unsigned char **outpacket, struct resolv_answer *a)
715 int i, j, len, fd, pos, rc;
718 struct resolv_header h;
719 struct resolv_question q;
720 struct resolv_answer ma;
721 bool first_answer = 1;
722 unsigned retries = 0;
723 unsigned char * packet = malloc(PACKETSZ);
724 char *dns, *lookup = malloc(MAXDNAME);
726 struct sockaddr_in sa;
727 int local_ns = -1, local_id = -1;
728 #ifdef __UCLIBC_HAS_IPV6__
730 struct sockaddr_in6 sa6;
735 if (!packet || !lookup || !nscount)
738 DPRINTF("Looking up type %d answer for '%s'\n", type, name);
740 /* Mess with globals while under lock */
741 __UCLIBC_MUTEX_LOCK(mylock);
742 local_ns = ns % nscount;
744 __UCLIBC_MUTEX_UNLOCK(mylock);
746 while (retries < MAX_RETRIES) {
750 memset(packet, 0, PACKETSZ);
752 memset(&h, 0, sizeof(h));
757 __UCLIBC_MUTEX_LOCK(__resolv_lock);
758 /* this is really __nameserver[] which is a global that
759 needs to hold __resolv_lock before access!! */
760 dns = nsip[local_ns];
761 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
766 DPRINTF("encoding header\n", h.rd);
768 i = __encode_header(&h, packet, PACKETSZ);
772 strncpy(lookup,name,MAXDNAME);
774 __UCLIBC_MUTEX_LOCK(__resolv_lock);
775 if (variant < __searchdomains) {
776 strncat(lookup,".", MAXDNAME);
777 strncat(lookup,__searchdomain[variant], MAXDNAME);
779 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
781 DPRINTF("lookup name: %s\n", lookup);
782 q.dotted = (char *)lookup;
784 q.qclass = C_IN; /* CLASS_IN */
786 j = __encode_question(&q, packet+i, PACKETSZ-i);
792 DPRINTF("On try %d, sending query to port %d of machine %s\n",
793 retries+1, NAMESERVER_PORT, dns);
795 #ifdef __UCLIBC_HAS_IPV6__
796 __UCLIBC_MUTEX_LOCK(__resolv_lock);
797 /* 'dns' is really __nameserver[] which is a global that
798 needs to hold __resolv_lock before access!! */
799 v6 = inet_pton(AF_INET6, dns, &sa6.sin6_addr) > 0;
800 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
801 fd = socket(v6 ? AF_INET6 : AF_INET, SOCK_DGRAM, IPPROTO_UDP);
803 fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
810 /* Connect to the UDP socket so that asyncronous errors are returned */
811 #ifdef __UCLIBC_HAS_IPV6__
813 sa6.sin6_family = AF_INET6;
814 sa6.sin6_port = htons(NAMESERVER_PORT);
815 /* sa6.sin6_addr is already here */
816 rc = connect(fd, (struct sockaddr *) &sa6, sizeof(sa6));
819 sa.sin_family = AF_INET;
820 sa.sin_port = htons(NAMESERVER_PORT);
821 __UCLIBC_MUTEX_LOCK(__resolv_lock);
822 /* 'dns' is really __nameserver[] which is a global that
823 needs to hold __resolv_lock before access!! */
824 sa.sin_addr.s_addr = inet_addr(dns);
825 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
826 rc = connect(fd, (struct sockaddr *) &sa, sizeof(sa));
827 #ifdef __UCLIBC_HAS_IPV6__
831 if (errno == ENETUNREACH) {
832 /* routing error, presume not transient */
840 DPRINTF("Transmitting packet of length %d, id=%d, qr=%d\n",
843 send(fd, packet, len, 0);
847 tv.tv_sec = REPLY_TIMEOUT;
849 if (select(fd + 1, &fds, NULL, NULL, &tv) <= 0) {
850 DPRINTF("Timeout\n");
852 /* timed out, so retry send and receive,
853 * to next nameserver on queue */
857 len = recv(fd, packet, 512, 0);
858 if (len < HFIXEDSZ) {
863 __decode_header(packet, &h);
865 DPRINTF("id = %d, qr = %d\n", h.id, h.qr);
867 if ((h.id != local_id) || (!h.qr)) {
873 DPRINTF("Got response %s\n", "(i think)!");
874 DPRINTF("qrcount=%d,ancount=%d,nscount=%d,arcount=%d\n",
875 h.qdcount, h.ancount, h.nscount, h.arcount);
876 DPRINTF("opcode=%d,aa=%d,tc=%d,rd=%d,ra=%d,rcode=%d\n",
877 h.opcode, h.aa, h.tc, h.rd, h.ra, h.rcode);
879 if ((h.rcode) || (h.ancount < 1)) {
880 /* negative result, not present */
886 for (j = 0; j < h.qdcount; j++) {
887 DPRINTF("Skipping question %d at %d\n", j, pos);
888 i = __length_question(packet, pos);
889 DPRINTF("Length of question %d is %d\n", j, i);
894 DPRINTF("Decoding answer at pos %d\n", pos);
897 for (j=0;j<h.ancount;j++,pos += i)
899 i = __decode_answer(packet, pos, &ma);
902 DPRINTF("failed decode %d\n", i);
909 ma.buflen = a->buflen;
910 ma.add_count = a->add_count;
911 memcpy(a, &ma, sizeof(ma));
912 if (a->atype != T_SIG && (0 == a->buf || (type != T_A && type != T_AAAA)))
916 if (a->atype != type)
921 a->add_count = h.ancount - j - 1;
922 if ((a->rdlength + sizeof(struct in_addr*)) * a->add_count > a->buflen)
932 if (ma.atype != type)
936 if (a->rdlength != ma.rdlength)
939 DPRINTF("Answer address len(%u) differs from original(%u)\n",
940 ma.rdlength, a->rdlength);
943 memcpy(a->buf + (a->add_count * ma.rdlength), ma.rdata, ma.rdlength);
948 DPRINTF("Answer name = |%s|\n", a->dotted);
949 DPRINTF("Answer type = |%d|\n", a->atype);
959 /* Mess with globals while under lock */
960 __UCLIBC_MUTEX_LOCK(mylock);
963 __UCLIBC_MUTEX_UNLOCK(mylock);
965 return (len); /* success! */
968 /* if there are other nameservers, give them a go,
969 otherwise return with error */
972 local_ns = (local_ns + 1) % nscount;
980 /* if there are searchdomains, try them or fallback as passed */
983 __UCLIBC_MUTEX_LOCK(__resolv_lock);
984 sdomains=__searchdomains;
985 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
987 if (variant < sdomains - 1) {
991 /* next server, first search */
992 local_ns = (local_ns + 1) % nscount;
1008 h_errno = NETDB_INTERNAL;
1009 /* Mess with globals while under lock */
1010 if (local_ns != -1) {
1011 __UCLIBC_MUTEX_LOCK(mylock);
1014 __UCLIBC_MUTEX_UNLOCK(mylock);
1020 #ifdef L_opennameservers
1022 /* We use __resolv_lock to guard access to the
1023 * '__nameservers' and __searchdomains globals */
1025 char * __nameserver[MAX_SERVERS];
1026 int __searchdomains;
1027 char * __searchdomain[MAX_SEARCH];
1029 __UCLIBC_MUTEX_INIT(__resolv_lock, PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP);
1032 * we currently read formats not quite the same as that on normal
1033 * unix systems, we can have a list of nameservers after the keyword.
1036 void attribute_hidden __open_nameservers()
1040 #define RESOLV_ARGS 5
1041 char szBuffer[128], *p, *argv[RESOLV_ARGS];
1045 __UCLIBC_MUTEX_LOCK(__resolv_lock);
1046 if (__nameservers > 0) {
1050 if ((fp = fopen("/etc/resolv.conf", "r")) ||
1051 (fp = fopen("/etc/config/resolv.conf", "r")))
1054 while (fgets(szBuffer, sizeof(szBuffer), fp) != NULL) {
1056 for (p = szBuffer; *p && isspace(*p); p++)
1057 /* skip white space */;
1058 if (*p == '\0' || *p == '\n' || *p == '#') /* skip comments etc */
1061 while (*p && argc < RESOLV_ARGS) {
1063 while (*p && !isspace(*p) && *p != '\n')
1065 while (*p && (isspace(*p) || *p == '\n')) /* remove spaces */
1069 if (strcmp(argv[0], "nameserver") == 0) {
1070 for (i = 1; i < argc && __nameservers < MAX_SERVERS; i++) {
1071 __nameserver[__nameservers++] = strdup(argv[i]);
1072 DPRINTF("adding nameserver %s\n", argv[i]);
1076 /* domain and search are mutually exclusive, the last one wins */
1077 if (strcmp(argv[0],"domain")==0 || strcmp(argv[0],"search")==0) {
1078 while (__searchdomains > 0) {
1079 free(__searchdomain[--__searchdomains]);
1080 __searchdomain[__searchdomains] = NULL;
1082 for (i=1; i < argc && __searchdomains < MAX_SEARCH; i++) {
1083 __searchdomain[__searchdomains++] = strdup(argv[i]);
1084 DPRINTF("adding search %s\n", argv[i]);
1089 DPRINTF("nameservers = %d\n", __nameservers);
1092 DPRINTF("failed to open %s\n", "resolv.conf");
1093 h_errno = NO_RECOVERY;
1098 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
1104 #ifdef L_closenameservers
1106 void attribute_hidden __close_nameservers(void)
1108 __UCLIBC_MUTEX_LOCK(__resolv_lock);
1109 while (__nameservers > 0) {
1110 free(__nameserver[--__nameservers]);
1111 __nameserver[__nameservers] = NULL;
1113 while (__searchdomains > 0) {
1114 free(__searchdomain[--__searchdomains]);
1115 __searchdomain[__searchdomains] = NULL;
1117 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
1121 #ifdef L_gethostbyname
1123 struct hostent *gethostbyname(const char *name)
1125 static struct hostent h;
1126 static char buf[sizeof(struct in_addr) +
1127 sizeof(struct in_addr *)*2 +
1128 sizeof(char *)*(ALIAS_DIM) + 384/*namebuffer*/ + 32/* margin */];
1131 gethostbyname_r(name, &h, buf, sizeof(buf), &hp, &h_errno);
1135 libc_hidden_def(gethostbyname)
1138 #ifdef L_gethostbyname2
1140 struct hostent *gethostbyname2(const char *name, int family)
1142 #ifndef __UCLIBC_HAS_IPV6__
1143 return family == AF_INET ? gethostbyname(name) : (struct hostent*)0;
1144 #else /* __UCLIBC_HAS_IPV6__ */
1145 static struct hostent h;
1146 static char buf[sizeof(struct in6_addr) +
1147 sizeof(struct in6_addr *)*2 +
1148 sizeof(char *)*(ALIAS_DIM) + 384/*namebuffer*/ + 32/* margin */];
1151 gethostbyname2_r(name, family, &h, buf, sizeof(buf), &hp, &h_errno);
1154 #endif /* __UCLIBC_HAS_IPV6__ */
1161 /* We use __resolv_lock to guard access to global '_res' */
1162 struct __res_state _res;
1166 struct __res_state *rp = &(_res);
1168 __UCLIBC_MUTEX_LOCK(__resolv_lock); /* must be a recursive lock! */
1169 __close_nameservers();
1170 __open_nameservers();
1171 rp->retrans = RES_TIMEOUT;
1173 rp->options = RES_INIT;
1174 rp->id = (u_int) random();
1175 rp->nsaddr.sin_addr.s_addr = INADDR_ANY;
1176 rp->nsaddr.sin_family = AF_INET;
1177 rp->nsaddr.sin_port = htons(NAMESERVER_PORT);
1179 /** rp->pfcode = 0; **/
1181 /** rp->_flags = 0; **/
1182 /** rp->qhook = NULL; **/
1183 /** rp->rhook = NULL; **/
1184 /** rp->_u._ext.nsinit = 0; **/
1186 if(__searchdomains) {
1188 for(i=0; i<__searchdomains; i++) {
1189 rp->dnsrch[i] = __searchdomain[i];
1196 for(i=0; i<__nameservers; i++) {
1197 if (inet_aton(__nameserver[i], &a)) {
1198 rp->nsaddr_list[i].sin_addr = a;
1199 rp->nsaddr_list[i].sin_family = AF_INET;
1200 rp->nsaddr_list[i].sin_port = htons(NAMESERVER_PORT);
1204 rp->nscount = __nameservers;
1205 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
1209 libc_hidden_def(res_init)
1211 #ifdef __UCLIBC_HAS_BSD_RES_CLOSE__
1212 void res_close( void )
1214 __close_nameservers();
1215 memset(&_res, 0, sizeof(_res));
1225 #define MIN(x, y) ((x) < (y) ? (x) : (y))
1228 int res_query(const char *dname, int class, int type,
1229 unsigned char *answer, int anslen)
1232 unsigned char * packet = 0;
1233 struct resolv_answer a;
1234 int __nameserversXX;
1235 char ** __nameserverXX;
1237 __open_nameservers();
1238 if (!dname || class != 1 /* CLASS_IN */) {
1239 h_errno = NO_RECOVERY;
1243 memset((char *) &a, '\0', sizeof(a));
1245 __UCLIBC_MUTEX_LOCK(__resolv_lock);
1246 __nameserversXX=__nameservers;
1247 __nameserverXX=__nameserver;
1248 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
1249 i = __dns_lookup(dname, type, __nameserversXX, __nameserverXX, &packet, &a);
1252 h_errno = TRY_AGAIN;
1258 if (a.atype == type) { /* CNAME*/
1259 int len = MIN(anslen, i);
1260 memcpy(answer, packet, len);
1269 libc_hidden_def(res_query)
1272 * Formulate a normal query, send, and retrieve answer in supplied buffer.
1273 * Return the size of the response on success, -1 on error.
1274 * If enabled, implement search rules until answer or unrecoverable failure
1275 * is detected. Error code, if any, is left in h_errno.
1277 #define __TRAILING_DOT (1<<0)
1278 #define __GOT_NODATA (1<<1)
1279 #define __GOT_SERVFAIL (1<<2)
1280 #define __TRIED_AS_IS (1<<3)
1281 int res_search(name, class, type, answer, anslen)
1282 const char *name; /* domain name */
1283 int class, type; /* class and type of query */
1284 u_char *answer; /* buffer to put answer */
1285 int anslen; /* size of answer */
1287 const char *cp, * const *domain;
1288 HEADER *hp = (HEADER *)(void *)answer;
1290 unsigned _state = 0;
1291 int ret, saved_herrno;
1292 u_long _res_options;
1293 unsigned _res_ndots;
1296 __UCLIBC_MUTEX_LOCK(__resolv_lock);
1297 _res_options = _res.options;
1298 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
1299 if ((!name || !answer) || ((_res_options & RES_INIT) == 0 && res_init() == -1)) {
1300 h_errno = NETDB_INTERNAL;
1305 h_errno = HOST_NOT_FOUND; /* default, if we never query */
1307 for (cp = name; *cp; cp++)
1308 dots += (*cp == '.');
1310 if (cp > name && *--cp == '.')
1311 _state |= __TRAILING_DOT;
1314 * If there are dots in the name already, let's just give it a try
1315 * 'as is'. The threshold can be set with the "ndots" option.
1318 __UCLIBC_MUTEX_LOCK(__resolv_lock);
1319 _res_ndots = _res.ndots;
1320 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
1321 if (dots >= _res_ndots) {
1322 ret = res_querydomain(name, NULL, class, type, answer, anslen);
1325 saved_herrno = h_errno;
1326 _state |= __TRIED_AS_IS;
1330 * We do at least one level of search if
1331 * - there is no dot and RES_DEFNAME is set, or
1332 * - there is at least one dot, there is no trailing dot,
1333 * and RES_DNSRCH is set.
1335 __UCLIBC_MUTEX_LOCK(__resolv_lock);
1336 _res_options = _res.options;
1337 _res_dnsrch = _res.dnsrch;
1338 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
1339 if ((!dots && (_res_options & RES_DEFNAMES)) ||
1340 (dots && !(_state & __TRAILING_DOT) && (_res_options & RES_DNSRCH))) {
1343 for (domain = (const char * const *)_res_dnsrch;
1347 ret = res_querydomain(name, *domain, class, type,
1353 * If no server present, give up.
1354 * If name isn't found in this domain,
1355 * keep trying higher domains in the search list
1356 * (if that's enabled).
1357 * On a NO_DATA error, keep trying, otherwise
1358 * a wildcard entry of another type could keep us
1359 * from finding this entry higher in the domain.
1360 * If we get some other error (negative answer or
1361 * server failure), then stop searching up,
1362 * but try the input name below in case it's
1365 if (errno == ECONNREFUSED) {
1366 h_errno = TRY_AGAIN;
1372 _state |= __GOT_NODATA;
1374 case HOST_NOT_FOUND:
1378 if (hp->rcode == SERVFAIL) {
1379 /* try next search element, if any */
1380 _state |= __GOT_SERVFAIL;
1385 /* anything else implies that we're done */
1389 * if we got here for some reason other than DNSRCH,
1390 * we only wanted one iteration of the loop, so stop.
1392 __UCLIBC_MUTEX_LOCK(__resolv_lock);
1393 _res_options = _res.options;
1394 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
1395 if (!(_res_options & RES_DNSRCH))
1401 * if we have not already tried the name "as is", do that now.
1402 * note that we do this regardless of how many dots were in the
1403 * name or whether it ends with a dot.
1405 if (!(_state & __TRIED_AS_IS)) {
1406 ret = res_querydomain(name, NULL, class, type, answer, anslen);
1412 * if we got here, we didn't satisfy the search.
1413 * if we did an initial full query, return that query's h_errno
1414 * (note that we wouldn't be here if that query had succeeded).
1415 * else if we ever got a nodata, send that back as the reason.
1416 * else send back meaningless h_errno, that being the one from
1417 * the last DNSRCH we did.
1419 if (saved_herrno != -1)
1420 h_errno = saved_herrno;
1421 else if (_state & __GOT_NODATA)
1423 else if (_state & __GOT_SERVFAIL)
1424 h_errno = TRY_AGAIN;
1427 #undef __TRAILING_DOT
1429 #undef __GOT_SERVFAIL
1430 #undef __TRIED_AS_IS
1432 * Perform a call on res_query on the concatenation of name and domain,
1433 * removing a trailing dot from name if domain is NULL.
1435 int res_querydomain(name, domain, class, type, answer, anslen)
1436 const char *name, *domain;
1437 int class, type; /* class and type of query */
1438 u_char *answer; /* buffer to put answer */
1439 int anslen; /* size of answer */
1441 char nbuf[MAXDNAME];
1442 const char *longname = nbuf;
1444 u_long _res_options;
1446 __UCLIBC_MUTEX_LOCK(__resolv_lock);
1447 _res_options = _res.options;
1448 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
1449 if ((!name || !answer) || ((_res_options & RES_INIT) == 0 && res_init() == -1)) {
1450 h_errno = NETDB_INTERNAL;
1455 __UCLIBC_MUTEX_LOCK(__resolv_lock);
1456 _res_options = _res.options;
1457 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
1458 if (_res_options & RES_DEBUG)
1459 printf(";; res_querydomain(%s, %s, %d, %d)\n",
1460 name, domain?domain:"<Nil>", class, type);
1462 if (domain == NULL) {
1464 * Check for trailing '.';
1465 * copy without '.' if present.
1468 if (n + 1 > sizeof(nbuf)) {
1469 h_errno = NO_RECOVERY;
1472 if (n > 0 && name[--n] == '.') {
1473 strncpy(nbuf, name, n);
1480 if (n + 1 + d + 1 > sizeof(nbuf)) {
1481 h_errno = NO_RECOVERY;
1484 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
1486 return (res_query(longname, class, type, answer, anslen));
1488 libc_hidden_def(res_querydomain)
1496 #ifdef L_gethostbyaddr
1497 struct hostent *gethostbyaddr (const void *addr, socklen_t len, int type)
1499 static struct hostent h;
1501 #ifndef __UCLIBC_HAS_IPV6__
1502 sizeof(struct in_addr) + sizeof(struct in_addr *)*2 +
1504 sizeof(struct in6_addr) + sizeof(struct in6_addr *)*2 +
1505 #endif /* __UCLIBC_HAS_IPV6__ */
1506 sizeof(char *)*(ALIAS_DIM) + 384/*namebuffer*/ + 32/* margin */];
1509 gethostbyaddr_r(addr, len, type, &h, buf, sizeof(buf), &hp, &h_errno);
1513 libc_hidden_def(gethostbyaddr)
1517 #ifdef L_read_etc_hosts_r
1519 void attribute_hidden __open_etc_hosts(FILE **fp)
1521 if ((*fp = fopen("/etc/hosts", "r")) == NULL) {
1522 *fp = fopen("/etc/config/hosts", "r");
1527 int attribute_hidden __read_etc_hosts_r(FILE * fp, const char * name, int type,
1528 enum etc_hosts_action action,
1529 struct hostent * result_buf,
1530 char * buf, size_t buflen,
1531 struct hostent ** result,
1534 struct in_addr *in=NULL;
1535 struct in_addr **addr_list=NULL;
1536 #ifdef __UCLIBC_HAS_IPV6__
1537 struct in6_addr *in6=NULL;
1538 struct in6_addr **addr_list6=NULL;
1539 #endif /* __UCLIBC_HAS_IPV6__ */
1541 int aliases, i, ret=HOST_NOT_FOUND;
1543 if (buflen < sizeof(char *)*(ALIAS_DIM))
1546 buf+=sizeof(char **)*(ALIAS_DIM);
1547 buflen-=sizeof(char **)*(ALIAS_DIM);
1549 if (action!=GETHOSTENT) {
1550 #ifdef __UCLIBC_HAS_IPV6__
1553 #endif /* __UCLIBC_HAS_IPV6__ */
1554 *h_errnop=NETDB_INTERNAL;
1555 if (buflen < sizeof(*in))
1557 in=(struct in_addr*)buf;
1559 buflen-=sizeof(*in);
1561 if (buflen < sizeof(*addr_list)*2)
1563 addr_list=(struct in_addr **)buf;
1564 buf+=sizeof(*addr_list)*2;
1565 buflen-=sizeof(*addr_list)*2;
1567 #ifdef __UCLIBC_HAS_IPV6__
1568 if (len < sizeof(*in6))
1570 in6=(struct in6_addr*)p;
1574 if (len < sizeof(*addr_list6)*2)
1576 addr_list6=(struct in6_addr**)p;
1577 p+=sizeof(*addr_list6)*2;
1578 len-=sizeof(*addr_list6)*2;
1584 #endif /* __UCLIBC_HAS_IPV6__ */
1589 __open_etc_hosts(&fp);
1596 *h_errnop=HOST_NOT_FOUND;
1597 while (fgets(buf, buflen, fp)) {
1598 if ((cp = strchr(buf, '#')))
1600 DPRINTF("Looking at: %s\n", buf);
1605 while (*cp && isspace(*cp))
1609 if (aliases < (2+MAX_ALIASES))
1610 alias[aliases++] = cp;
1611 while (*cp && !isspace(*cp))
1617 continue; /* syntax error really */
1619 if (action==GETHOSTENT) {
1620 /* Return whatever the next entry happens to be. */
1622 } else if (action==GET_HOSTS_BYADDR) {
1623 if (strcmp(name, alias[0]) != 0)
1626 /* GET_HOSTS_BYNAME */
1627 for (i = 1; i < aliases; i++)
1628 if (strcasecmp(name, alias[i]) == 0)
1634 if (type == AF_INET && inet_pton(AF_INET, alias[0], in) > 0) {
1635 DPRINTF("Found INET\n");
1638 result_buf->h_name = alias[1];
1639 result_buf->h_addrtype = AF_INET;
1640 result_buf->h_length = sizeof(*in);
1641 result_buf->h_addr_list = (char**) addr_list;
1642 result_buf->h_aliases = alias + 2;
1645 #ifdef __UCLIBC_HAS_IPV6__
1646 } else if (type == AF_INET6 && inet_pton(AF_INET6, alias[0], in6) > 0) {
1647 DPRINTF("Found INET6\n");
1648 addr_list6[0] = in6;
1650 result_buf->h_name = alias[1];
1651 result_buf->h_addrtype = AF_INET6;
1652 result_buf->h_length = sizeof(*in6);
1653 result_buf->h_addr_list = (char**) addr_list6;
1654 result_buf->h_aliases = alias + 2;
1657 #endif /* __UCLIBC_HAS_IPV6__ */
1661 break; /* bad ip address */
1664 if (action!=GETHOSTENT) {
1669 if (action!=GETHOSTENT) {
1678 __UCLIBC_MUTEX_STATIC(mylock, PTHREAD_MUTEX_INITIALIZER);
1680 static int __stay_open;
1681 static FILE * __gethostent_fp;
1683 void endhostent (void)
1685 __UCLIBC_MUTEX_LOCK(mylock);
1687 if (__gethostent_fp) {
1688 fclose(__gethostent_fp);
1690 __UCLIBC_MUTEX_UNLOCK(mylock);
1693 void sethostent (int stay_open)
1695 __UCLIBC_MUTEX_LOCK(mylock);
1696 __stay_open = stay_open;
1697 __UCLIBC_MUTEX_UNLOCK(mylock);
1700 int gethostent_r(struct hostent *result_buf, char *buf, size_t buflen,
1701 struct hostent **result, int *h_errnop)
1705 __UCLIBC_MUTEX_LOCK(mylock);
1706 if (__gethostent_fp == NULL) {
1707 __open_etc_hosts(&__gethostent_fp);
1708 if (__gethostent_fp == NULL) {
1715 ret = __read_etc_hosts_r(__gethostent_fp, NULL, AF_INET, GETHOSTENT,
1716 result_buf, buf, buflen, result, h_errnop);
1717 if (__stay_open == 0) {
1718 fclose(__gethostent_fp);
1721 __UCLIBC_MUTEX_UNLOCK(mylock);
1724 libc_hidden_def(gethostent_r)
1726 struct hostent *gethostent (void)
1728 static struct hostent h;
1730 #ifndef __UCLIBC_HAS_IPV6__
1731 sizeof(struct in_addr) + sizeof(struct in_addr *)*2 +
1733 sizeof(struct in6_addr) + sizeof(struct in6_addr *)*2 +
1734 #endif /* __UCLIBC_HAS_IPV6__ */
1735 sizeof(char *)*(ALIAS_DIM) +
1736 80/*namebuffer*/ + 2/* margin */];
1737 struct hostent *host;
1739 __UCLIBC_MUTEX_LOCK(mylock);
1740 gethostent_r(&h, buf, sizeof(buf), &host, &h_errno);
1741 __UCLIBC_MUTEX_UNLOCK(mylock);
1746 #ifdef L_get_hosts_byname_r
1748 int attribute_hidden __get_hosts_byname_r(const char * name, int type,
1749 struct hostent * result_buf,
1750 char * buf, size_t buflen,
1751 struct hostent ** result,
1754 return(__read_etc_hosts_r(NULL, name, type, GET_HOSTS_BYNAME,
1755 result_buf, buf, buflen, result, h_errnop));
1759 #ifdef L_get_hosts_byaddr_r
1761 int attribute_hidden __get_hosts_byaddr_r(const char * addr, int len, int type,
1762 struct hostent * result_buf,
1763 char * buf, size_t buflen,
1764 struct hostent ** result,
1767 #ifndef __UCLIBC_HAS_IPV6__
1768 char ipaddr[INET_ADDRSTRLEN];
1770 char ipaddr[INET6_ADDRSTRLEN];
1771 #endif /* __UCLIBC_HAS_IPV6__ */
1775 if (len != sizeof(struct in_addr))
1778 #ifdef __UCLIBC_HAS_IPV6__
1780 if (len != sizeof(struct in6_addr))
1783 #endif /* __UCLIBC_HAS_IPV6__ */
1788 inet_ntop(type, addr, ipaddr, sizeof(ipaddr));
1790 return(__read_etc_hosts_r(NULL, ipaddr, type, GET_HOSTS_BYADDR,
1791 result_buf, buf, buflen, result, h_errnop));
1795 #ifdef L_getnameinfo
1798 # define min(x,y) (((x) > (y)) ? (y) : (x))
1801 libc_hidden_proto(getnameinfo)
1802 int getnameinfo (const struct sockaddr *sa, socklen_t addrlen, char *host,
1803 socklen_t hostlen, char *serv, socklen_t servlen,
1808 struct hostent *h = NULL;
1811 if (flags & ~(NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|NI_DGRAM))
1812 return EAI_BADFLAGS;
1814 if (sa == NULL || addrlen < sizeof (sa_family_t))
1818 if (ok == AF_LOCAL) /* valid */;
1819 else if (ok == AF_INET) {
1820 if (addrlen < sizeof (struct sockaddr_in))
1822 #ifdef __UCLIBC_HAS_IPV6__
1823 } else if (ok == AF_INET6) {
1824 if (addrlen < sizeof (struct sockaddr_in6))
1826 #endif /* __UCLIBC_HAS_IPV6__ */
1832 if (host != NULL && hostlen > 0)
1833 switch (sa->sa_family) {
1835 #ifdef __UCLIBC_HAS_IPV6__
1837 #endif /* __UCLIBC_HAS_IPV6__ */
1838 if (!(flags & NI_NUMERICHOST)) {
1839 #ifdef __UCLIBC_HAS_IPV6__
1840 if (sa->sa_family == AF_INET6)
1841 h = gethostbyaddr ((const void *)
1842 &(((const struct sockaddr_in6 *) sa)->sin6_addr),
1843 sizeof(struct in6_addr), AF_INET6);
1845 #endif /* __UCLIBC_HAS_IPV6__ */
1846 h = gethostbyaddr ((const void *) &(((const struct sockaddr_in *)sa)->sin_addr),
1847 sizeof(struct in_addr), AF_INET);
1851 if ((flags & NI_NOFQDN)
1852 && (getdomainname (domain, sizeof(domain)) == 0)
1853 && (c = strstr (h->h_name, domain))
1854 && (c != h->h_name) && (*(--c) == '.')) {
1855 strncpy (host, h->h_name,
1856 min(hostlen, (size_t) (c - h->h_name)));
1857 host[min(hostlen - 1, (size_t) (c - h->h_name))] = '\0';
1860 strncpy (host, h->h_name, hostlen);
1867 if (flags & NI_NAMEREQD) {
1872 #ifdef __UCLIBC_HAS_IPV6__
1873 if (sa->sa_family == AF_INET6) {
1874 const struct sockaddr_in6 *sin6p;
1876 sin6p = (const struct sockaddr_in6 *) sa;
1878 c = inet_ntop (AF_INET6,
1879 (const void *) &sin6p->sin6_addr, host, hostlen);
1881 /* Does scope id need to be supported? */
1883 scopeid = sin6p->sin6_scope_id;
1885 /* Buffer is >= IFNAMSIZ+1. */
1886 char scopebuf[IFNAMSIZ + 1];
1888 int ni_numericscope = 0;
1889 size_t real_hostlen = strnlen (host, hostlen);
1890 size_t scopelen = 0;
1892 scopebuf[0] = SCOPE_DELIMITER;
1894 scopeptr = &scopebuf[1];
1896 if (IN6_IS_ADDR_LINKLOCAL (&sin6p->sin6_addr)
1897 || IN6_IS_ADDR_MC_LINKLOCAL (&sin6p->sin6_addr)) {
1898 if (if_indextoname (scopeid, scopeptr) == NULL)
1901 scopelen = strlen (scopebuf);
1906 if (ni_numericscope)
1907 scopelen = 1 + snprintf (scopeptr,
1913 if (real_hostlen + scopelen + 1 > hostlen)
1915 memcpy (host + real_hostlen, scopebuf, scopelen + 1);
1919 #endif /* __UCLIBC_HAS_IPV6__ */
1920 c = inet_ntop (AF_INET, (const void *)
1921 &(((const struct sockaddr_in *) sa)->sin_addr),
1934 if (!(flags & NI_NUMERICHOST)) {
1935 struct utsname utsname;
1937 if (!uname (&utsname)) {
1938 strncpy (host, utsname.nodename, hostlen);
1943 if (flags & NI_NAMEREQD) {
1948 strncpy (host, "localhost", hostlen);
1951 /*Already checked above default:
1956 if (serv && (servlen > 0)) {
1957 if (sa->sa_family == AF_LOCAL) {
1958 strncpy (serv, ((const struct sockaddr_un *) sa)->sun_path, servlen);
1959 } else { /* AF_INET || AF_INET6 */
1960 if (!(flags & NI_NUMERICSERV)) {
1962 s = getservbyport (((const struct sockaddr_in *) sa)->sin_port,
1963 ((flags & NI_DGRAM) ? "udp" : "tcp"));
1965 strncpy (serv, s->s_name, servlen);
1969 snprintf (serv, servlen, "%d",
1970 ntohs (((const struct sockaddr_in *) sa)->sin_port));
1974 if (host && (hostlen > 0))
1975 host[hostlen-1] = 0;
1976 if (serv && (servlen > 0))
1977 serv[servlen-1] = 0;
1981 libc_hidden_def(getnameinfo)
1985 #ifdef L_gethostbyname_r
1987 int gethostbyname_r(const char * name,
1988 struct hostent * result_buf,
1989 char * buf, size_t buflen,
1990 struct hostent ** result,
1994 struct in_addr **addr_list;
1996 unsigned char *packet;
1997 struct resolv_answer a;
1999 int __nameserversXX;
2000 char ** __nameserverXX;
2002 __open_nameservers();
2007 /* do /etc/hosts first */
2009 int old_errno = errno; /* Save the old errno and reset errno */
2010 __set_errno(0); /* to check for missing /etc/hosts. */
2012 if ((i=__get_hosts_byname_r(name, AF_INET, result_buf,
2013 buf, buflen, result, h_errnop))==0)
2015 switch (*h_errnop) {
2016 case HOST_NOT_FOUND:
2019 case NETDB_INTERNAL:
2020 if (errno == ENOENT) {
2023 /* else fall through */
2027 __set_errno(old_errno);
2030 DPRINTF("Nothing found in /etc/hosts\n");
2032 *h_errnop = NETDB_INTERNAL;
2033 if (buflen < sizeof(*in))
2035 in=(struct in_addr*)buf;
2037 buflen-=sizeof(*in);
2039 if (buflen < sizeof(*addr_list)*2)
2041 addr_list=(struct in_addr**)buf;
2042 buf+=sizeof(*addr_list)*2;
2043 buflen-=sizeof(*addr_list)*2;
2048 if (buflen < sizeof(char *)*(ALIAS_DIM))
2051 buf+=sizeof(char **)*(ALIAS_DIM);
2052 buflen-=sizeof(char **)*(ALIAS_DIM);
2056 strncpy(buf, name, buflen);
2061 /* First check if this is already an address */
2062 if (inet_aton(name, in)) {
2063 result_buf->h_name = buf;
2064 result_buf->h_addrtype = AF_INET;
2065 result_buf->h_length = sizeof(*in);
2066 result_buf->h_addr_list = (char **) addr_list;
2067 result_buf->h_aliases = alias;
2069 *h_errnop = NETDB_SUCCESS;
2070 return NETDB_SUCCESS;
2075 __UCLIBC_MUTEX_LOCK(__resolv_lock);
2076 __nameserversXX=__nameservers;
2077 __nameserverXX=__nameserver;
2078 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
2082 i = __dns_lookup(name, T_A, __nameserversXX, __nameserverXX, &packet, &a);
2085 *h_errnop = HOST_NOT_FOUND;
2086 DPRINTF("__dns_lookup\n");
2090 if ((a.rdlength + sizeof(struct in_addr*)) * a.add_count + 256 > buflen)
2094 *h_errnop = NETDB_INTERNAL;
2095 DPRINTF("buffer too small for all addresses\n");
2098 else if(a.add_count > 0)
2100 memmove(buf - sizeof(struct in_addr*)*2, buf, a.add_count * a.rdlength);
2101 addr_list = (struct in_addr**)(buf + a.add_count * a.rdlength);
2103 for (i = a.add_count-1; i>=0; --i)
2104 addr_list[i+1] = (struct in_addr*)(buf - sizeof(struct in_addr*)*2 + a.rdlength * i);
2105 addr_list[a.add_count + 1] = 0;
2106 buflen -= (((char*)&(addr_list[a.add_count + 2])) - buf);
2107 buf = (char*)&addr_list[a.add_count + 2];
2110 strncpy(buf, a.dotted, buflen);
2113 if (a.atype == T_A) { /* ADDRESS */
2114 memcpy(in, a.rdata, sizeof(*in));
2115 result_buf->h_name = buf;
2116 result_buf->h_addrtype = AF_INET;
2117 result_buf->h_length = sizeof(*in);
2118 result_buf->h_addr_list = (char **) addr_list;
2119 #ifdef __UCLIBC_MJN3_ONLY__
2120 #warning TODO -- generate the full list
2122 result_buf->h_aliases = alias; /* TODO: generate the full list */
2127 *h_errnop=HOST_NOT_FOUND;
2133 *h_errnop = NETDB_SUCCESS;
2134 return NETDB_SUCCESS;
2136 libc_hidden_def(gethostbyname_r)
2139 #ifdef L_gethostbyname2_r
2141 int gethostbyname2_r(const char *name, int family,
2142 struct hostent * result_buf,
2143 char * buf, size_t buflen,
2144 struct hostent ** result,
2147 #ifndef __UCLIBC_HAS_IPV6__
2148 return family == (AF_INET)? gethostbyname_r(name, result_buf,
2149 buf, buflen, result, h_errnop) : HOST_NOT_FOUND;
2150 #else /* __UCLIBC_HAS_IPV6__ */
2151 struct in6_addr *in;
2152 struct in6_addr **addr_list;
2153 unsigned char *packet;
2154 struct resolv_answer a;
2157 int __nameserversXX;
2158 char ** __nameserverXX;
2160 if (family == AF_INET)
2161 return gethostbyname_r(name, result_buf, buf, buflen, result, h_errnop);
2163 if (family != AF_INET6)
2166 __open_nameservers();
2171 /* do /etc/hosts first */
2173 int old_errno = errno; /* Save the old errno and reset errno */
2174 __set_errno(0); /* to check for missing /etc/hosts. */
2176 if ((i=__get_hosts_byname_r(name, family, result_buf,
2177 buf, buflen, result, h_errnop))==0)
2179 switch (*h_errnop) {
2180 case HOST_NOT_FOUND:
2183 case NETDB_INTERNAL:
2184 if (errno == ENOENT) {
2187 /* else fall through */
2191 __set_errno(old_errno);
2194 DPRINTF("Nothing found in /etc/hosts\n");
2196 *h_errnop = NETDB_INTERNAL;
2197 if (buflen < sizeof(*in))
2199 in=(struct in6_addr*)buf;
2201 buflen-=sizeof(*in);
2203 if (buflen < sizeof(*addr_list)*2)
2205 addr_list=(struct in6_addr**)buf;
2206 buf+=sizeof(*addr_list)*2;
2207 buflen-=sizeof(*addr_list)*2;
2214 strncpy(buf, name, buflen);
2216 /* First check if this is already an address */
2217 if (inet_pton(AF_INET6, name, in)) {
2218 result_buf->h_name = buf;
2219 result_buf->h_addrtype = AF_INET6;
2220 result_buf->h_length = sizeof(*in);
2221 result_buf->h_addr_list = (char **) addr_list;
2223 *h_errnop = NETDB_SUCCESS;
2224 return NETDB_SUCCESS;
2227 memset((char *) &a, '\0', sizeof(a));
2230 __UCLIBC_MUTEX_LOCK(__resolv_lock);
2231 __nameserversXX=__nameservers;
2232 __nameserverXX=__nameserver;
2233 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
2235 i = __dns_lookup(buf, T_AAAA, __nameserversXX, __nameserverXX, &packet, &a);
2238 *h_errnop = HOST_NOT_FOUND;
2242 strncpy(buf, a.dotted, buflen);
2245 if (a.atype == T_CNAME) { /* CNAME */
2246 DPRINTF("Got a CNAME in gethostbyname()\n");
2247 i = __decode_dotted(packet, a.rdoffset, buf, buflen);
2251 *h_errnop = NO_RECOVERY;
2254 if (++nest > MAX_RECURSE) {
2255 *h_errnop = NO_RECOVERY;
2259 } else if (a.atype == T_AAAA) { /* ADDRESS */
2260 memcpy(in, a.rdata, sizeof(*in));
2261 result_buf->h_name = buf;
2262 result_buf->h_addrtype = AF_INET6;
2263 result_buf->h_length = sizeof(*in);
2264 result_buf->h_addr_list = (char **) addr_list;
2269 *h_errnop=HOST_NOT_FOUND;
2275 *h_errnop = NETDB_SUCCESS;
2276 return NETDB_SUCCESS;
2277 #endif /* __UCLIBC_HAS_IPV6__ */
2279 libc_hidden_def(gethostbyname2_r)
2282 #ifdef L_gethostbyaddr_r
2283 int gethostbyaddr_r (const void *addr, socklen_t len, int type,
2284 struct hostent * result_buf,
2285 char * buf, size_t buflen,
2286 struct hostent ** result,
2291 struct in_addr **addr_list;
2292 #ifdef __UCLIBC_HAS_IPV6__
2295 struct in6_addr *in6;
2296 struct in6_addr **addr_list6;
2297 #endif /* __UCLIBC_HAS_IPV6__ */
2299 unsigned char *packet;
2300 struct resolv_answer a;
2303 int __nameserversXX;
2304 char ** __nameserverXX;
2310 memset((char *) &a, '\0', sizeof(a));
2314 if (len != sizeof(struct in_addr))
2317 #ifdef __UCLIBC_HAS_IPV6__
2319 if (len != sizeof(struct in6_addr))
2322 #endif /* __UCLIBC_HAS_IPV6__ */
2327 /* do /etc/hosts first */
2328 if ((i=__get_hosts_byaddr_r(addr, len, type, result_buf,
2329 buf, buflen, result, h_errnop))==0)
2331 switch (*h_errnop) {
2332 case HOST_NOT_FOUND:
2339 __open_nameservers();
2341 #ifdef __UCLIBC_HAS_IPV6__
2344 #endif /* __UCLIBC_HAS_IPV6__ */
2346 *h_errnop = NETDB_INTERNAL;
2347 if (buflen < sizeof(*in))
2349 in=(struct in_addr*)buf;
2351 buflen-=sizeof(*in);
2353 if (buflen < sizeof(*addr_list)*2)
2355 addr_list=(struct in_addr**)buf;
2356 buf+=sizeof(*addr_list)*2;
2357 buflen-=sizeof(*addr_list)*2;
2359 if (buflen < sizeof(char *)*(ALIAS_DIM))
2362 buf+=sizeof(*alias)*(ALIAS_DIM);
2363 buflen-=sizeof(*alias)*(ALIAS_DIM);
2365 #ifdef __UCLIBC_HAS_IPV6__
2366 if (plen < sizeof(*in6))
2368 in6=(struct in6_addr*)qp;
2372 if (plen < sizeof(*addr_list6)*2)
2374 addr_list6=(struct in6_addr**)qp;
2375 qp+=sizeof(*addr_list6)*2;
2376 plen-=sizeof(*addr_list6)*2;
2378 if (plen < buflen) {
2382 #endif /* __UCLIBC_HAS_IPV6__ */
2387 if(type == AF_INET) {
2388 unsigned char *tmp_addr = (unsigned char *)addr;
2390 memcpy(&in->s_addr, addr, len);
2394 sprintf(buf, "%u.%u.%u.%u.in-addr.arpa",
2395 tmp_addr[3], tmp_addr[2], tmp_addr[1], tmp_addr[0]);
2396 #ifdef __UCLIBC_HAS_IPV6__
2398 memcpy(in6->s6_addr, addr, len);
2400 addr_list6[0] = in6;
2403 for (i = len - 1; i >= 0; i--) {
2404 qp += sprintf(qp, "%x.%x.", in6->s6_addr[i] & 0xf,
2405 (in6->s6_addr[i] >> 4) & 0xf);
2407 strcpy(qp, "ip6.int");
2408 #endif /* __UCLIBC_HAS_IPV6__ */
2418 __UCLIBC_MUTEX_LOCK(__resolv_lock);
2419 __nameserversXX=__nameservers;
2420 __nameserverXX=__nameserver;
2421 __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
2422 i = __dns_lookup(buf, T_PTR, __nameserversXX, __nameserverXX, &packet, &a);
2425 *h_errnop = HOST_NOT_FOUND;
2429 strncpy(buf, a.dotted, buflen);
2432 if (a.atype == T_CNAME) { /* CNAME */
2433 DPRINTF("Got a CNAME in gethostbyaddr()\n");
2434 i = __decode_dotted(packet, a.rdoffset, buf, buflen);
2438 *h_errnop = NO_RECOVERY;
2441 if (++nest > MAX_RECURSE) {
2442 *h_errnop = NO_RECOVERY;
2446 } else if (a.atype == T_PTR) { /* ADDRESS */
2447 i = __decode_dotted(packet, a.rdoffset, buf, buflen);
2450 result_buf->h_name = buf;
2451 result_buf->h_addrtype = type;
2453 if(type == AF_INET) {
2454 result_buf->h_length = sizeof(*in);
2455 #ifdef __UCLIBC_HAS_IPV6__
2457 result_buf->h_length = sizeof(*in6);
2458 #endif /* __UCLIBC_HAS_IPV6__ */
2461 result_buf->h_addr_list = (char **) addr_list;
2462 result_buf->h_aliases = alias;
2466 *h_errnop = NO_ADDRESS;
2472 *h_errnop = NETDB_SUCCESS;
2473 return NETDB_SUCCESS;
2475 libc_hidden_def(gethostbyaddr_r)
2480 * Expand compressed domain name 'comp_dn' to full domain name.
2481 * 'msg' is a pointer to the begining of the message,
2482 * 'eomorig' points to the first location after the message,
2483 * 'exp_dn' is a pointer to a buffer of size 'length' for the result.
2484 * Return size of compressed name or -1 if there was an error.
2486 int __dn_expand(const u_char *msg, const u_char *eom, const u_char *src,
2487 char *dst, int dstsiz)
2489 int n = ns_name_uncompress(msg, eom, src, dst, (size_t)dstsiz);
2491 if (n > 0 && dst[0] == '.')
2495 #endif /* L_res_comp */
2500 * Thinking in noninternationalized USASCII (per the DNS spec),
2501 * is this character visible and not a space when printed ?
2505 static int printable(int ch)
2507 return (ch > 0x20 && ch < 0x7f);
2512 * Thinking in noninternationalized USASCII (per the DNS spec),
2513 * is this characted special ("in need of quoting") ?
2517 static int special(int ch)
2520 case 0x22: /* '"' */
2521 case 0x2E: /* '.' */
2522 case 0x3B: /* ';' */
2523 case 0x5C: /* '\\' */
2524 /* Special modifiers in zone files. */
2525 case 0x40: /* '@' */
2526 case 0x24: /* '$' */
2534 * ns_name_uncompress(msg, eom, src, dst, dstsiz)
2535 * Expand compressed domain name to presentation format.
2537 * Number of bytes read out of `src', or -1 (with errno set).
2539 * Root domain returns as "." not "".
2541 int ns_name_uncompress(const u_char *msg, const u_char *eom,
2542 const u_char *src, char *dst, size_t dstsiz)
2544 u_char tmp[NS_MAXCDNAME];
2547 if ((n = ns_name_unpack(msg, eom, src, tmp, sizeof tmp)) == -1)
2549 if (ns_name_ntop(tmp, dst, dstsiz) == -1)
2553 libc_hidden_def(ns_name_uncompress)
2557 * ns_name_ntop(src, dst, dstsiz)
2558 * Convert an encoded domain name to printable ascii as per RFC1035.
2560 * Number of bytes written to buffer, or -1 (with errno set)
2562 * The root is returned as "."
2563 * All other domains are returned in non absolute form
2565 int ns_name_ntop(const u_char *src, char *dst, size_t dstsiz) {
2570 const char digits[] = "0123456789";
2576 while ((n = *cp++) != 0) {
2577 if ((n & NS_CMPRSFLGS) != 0) {
2578 /* Some kind of compression pointer. */
2579 __set_errno (EMSGSIZE);
2584 __set_errno (EMSGSIZE);
2589 if (dn + n >= eom) {
2590 __set_errno (EMSGSIZE);
2593 for ((void)NULL; n > 0; n--) {
2596 if (dn + 1 >= eom) {
2597 __set_errno (EMSGSIZE);
2602 } else if (!printable(c)) {
2603 if (dn + 3 >= eom) {
2604 __set_errno (EMSGSIZE);
2608 *dn++ = digits[c / 100];
2609 *dn++ = digits[(c % 100) / 10];
2610 *dn++ = digits[c % 10];
2613 __set_errno (EMSGSIZE);
2622 __set_errno (EMSGSIZE);
2628 __set_errno (EMSGSIZE);
2634 libc_hidden_def(ns_name_ntop)
2637 * ns_name_unpack(msg, eom, src, dst, dstsiz)
2638 * Unpack a domain name from a message, source may be compressed.
2640 * -1 if it fails, or consumed octets if it succeeds.
2642 int ns_name_unpack(const u_char *msg, const u_char *eom, const u_char *src,
2643 u_char *dst, size_t dstsiz)
2645 const u_char *srcp, *dstlim;
2647 int n, len, checked;
2653 dstlim = dst + dstsiz;
2654 if (srcp < msg || srcp >= eom) {
2655 __set_errno (EMSGSIZE);
2658 /* Fetch next label in domain name. */
2659 while ((n = *srcp++) != 0) {
2660 /* Check for indirection. */
2661 switch (n & NS_CMPRSFLGS) {
2664 if (dstp + n + 1 >= dstlim || srcp + n >= eom) {
2665 __set_errno (EMSGSIZE);
2670 memcpy(dstp, srcp, n);
2677 __set_errno (EMSGSIZE);
2681 len = srcp - src + 1;
2682 srcp = msg + (((n & 0x3f) << 8) | (*srcp & 0xff));
2683 if (srcp < msg || srcp >= eom) { /* Out of range. */
2684 __set_errno (EMSGSIZE);
2689 * Check for loops in the compressed name;
2690 * if we've looked at the whole message,
2691 * there must be a loop.
2693 if (checked >= eom - msg) {
2694 __set_errno (EMSGSIZE);
2700 __set_errno (EMSGSIZE);
2701 return (-1); /* flag error */
2709 libc_hidden_def(ns_name_unpack)
2710 #endif /* L_ns_name */