OSDN Git Service

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