OSDN Git Service

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