OSDN Git Service

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