Add nsswitch support.
[dragonfly.git] / lib / libc / net / name6.c
1 /*      $FreeBSD: src/lib/libc/net/name6.c,v 1.6.2.9 2002/11/02 18:54:57 ume Exp $      */
2 /*      $KAME: name6.c,v 1.25 2000/06/26 16:44:40 itojun Exp $  */
3
4 /*
5  * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 /*
33  * ++Copyright++ 1985, 1988, 1993
34  * -
35  * Copyright (c) 1985, 1988, 1993
36  *    The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  * -
62  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
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, and that
67  * the name of Digital Equipment Corporation not be used in advertising or
68  * publicity pertaining to distribution of the document or software without
69  * specific, written prior permission.
70  *
71  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
72  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
73  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
74  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
75  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
76  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
77  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
78  * SOFTWARE.
79  * -
80  * --Copyright--
81  */
82
83 /*
84  *      Atsushi Onoe <onoe@sm.sony.co.jp>
85  */
86
87 /*
88  * TODO for thread safe
89  *      use mutex for _hostconf, _hostconf_init.
90  *      rewrite resolvers to be thread safe
91  */
92
93 #include "namespace.h"
94 #include <sys/param.h>
95 #include <sys/socket.h>
96 #include <sys/time.h>
97 #include <sys/queue.h>
98 #include <netinet/in.h>
99
100 #include <arpa/inet.h>
101 #include <arpa/nameser.h>
102
103 #include <errno.h>
104 #include <netdb.h>
105 #include <resolv.h>
106 #include <stdio.h>
107 #include <stdlib.h>
108 #include <string.h>
109 #include <stdarg.h>
110 #include <nsswitch.h>
111 #include <unistd.h>
112 #include "un-namespace.h"
113 #ifdef NS_CACHING
114 #include "nscache.h"
115 #endif
116
117 #ifndef _PATH_HOSTS
118 #define _PATH_HOSTS     "/etc/hosts"
119 #endif
120
121 #ifndef MAXALIASES
122 #define MAXALIASES      10
123 #endif
124 #ifndef MAXADDRS
125 #define MAXADDRS        20
126 #endif
127 #ifndef MAXDNAME
128 #define MAXDNAME        1025
129 #endif
130
131 #ifdef INET6
132 #define ADDRLEN(af)     ((af) == AF_INET6 ? sizeof(struct in6_addr) : \
133                                             sizeof(struct in_addr))
134 #else
135 #define ADDRLEN(af)     sizeof(struct in_addr)
136 #endif
137
138 #define MAPADDR(ab, ina) \
139 do {                                                                    \
140         memcpy(&(ab)->map_inaddr, ina, sizeof(struct in_addr));         \
141         memset((ab)->map_zero, 0, sizeof((ab)->map_zero));              \
142         memset((ab)->map_one, 0xff, sizeof((ab)->map_one));             \
143 } while (0)
144 #define MAPADDRENABLED(flags) \
145         (((flags) & AI_V4MAPPED) || \
146          (((flags) & AI_V4MAPPED_CFG) && _mapped_addr_enabled()))
147
148 union inx_addr {
149         struct in_addr  in_addr;
150 #ifdef INET6
151         struct in6_addr in6_addr;
152 #endif
153         struct {
154                 u_char  mau_zero[10];
155                 u_char  mau_one[2];
156                 struct in_addr mau_inaddr;
157         }               map_addr_un;
158 #define map_zero        map_addr_un.mau_zero
159 #define map_one         map_addr_un.mau_one
160 #define map_inaddr      map_addr_un.mau_inaddr
161 };
162
163 static struct    hostent *_hpcopy(struct hostent *hp, int *errp);
164 static struct    hostent *_hpaddr(int af, const char *name, void *addr, int *errp);
165 static struct    hostent *_hpmerge(struct hostent *hp1, struct hostent *hp2, int *errp);
166 #ifdef INET6
167 static struct    hostent *_hpmapv6(struct hostent *hp, int *errp);
168 #endif
169 static struct    hostent *_hpsort(struct hostent *hp);
170 static struct    hostent *_ghbyname(const char *name, int af, int flags, int *errp);
171 static char     *_hgetword(char **pp);
172 static int       _mapped_addr_enabled(void);
173
174 static FILE     *_files_open(int *errp);
175 static int       _files_ghbyname(void *, void *, va_list);
176 static int       _files_ghbyaddr(void *, void *, va_list);
177 #ifdef YP
178 static int       _nis_ghbyname(void *, void *, va_list);
179 static int       _nis_ghbyaddr(void *, void *, va_list);
180 #endif
181 static int       _dns_ghbyname(void *, void *, va_list);
182 static int       _dns_ghbyaddr(void *, void *, va_list);
183 #ifdef ICMPNL
184 static int       _icmp_ghbyaddr(void *, void *, va_list);
185 #endif /* ICMPNL */
186 #ifdef NS_CACHING
187 static int ipnode_id_func(char *, size_t *, va_list, void *);
188 static int ipnode_marshal_func(char *, size_t *, void *, va_list, void *);
189 static int ipnode_unmarshal_func(char *, size_t, void *, va_list, void *);
190 #endif
191
192 /* Make getipnodeby*() thread-safe in libc for use with kernel threads. */
193 #include "libc_private.h"
194 #include "spinlock.h"
195 /*
196  * XXX: Our res_*() is not thread-safe.  So, we share lock between
197  * getaddrinfo() and getipnodeby*().  Still, we cannot use
198  * getaddrinfo() and getipnodeby*() in conjunction with other
199  * functions which call res_*().
200  */
201 extern spinlock_t __getaddrinfo_thread_lock;
202 #define THREAD_LOCK() \
203         if (__isthreaded) _SPINLOCK(&__getaddrinfo_thread_lock);
204 #define THREAD_UNLOCK() \
205         if (__isthreaded) _SPINUNLOCK(&__getaddrinfo_thread_lock);
206
207 /* Host lookup order if nsswitch.conf is broken or nonexistant */
208 static const ns_src default_src[] = {
209         { NSSRC_FILES, NS_SUCCESS },
210         { NSSRC_DNS, NS_SUCCESS },
211 #ifdef ICMPNL
212 #define NSSRC_ICMP "icmp"
213         { NSSRC_ICMP, NS_SUCCESS },
214 #endif
215         { 0 }
216 };
217
218 /*
219  * Check if kernel supports mapped address.
220  *      implementation dependent
221  */
222 #ifdef __KAME__
223 #include <sys/sysctl.h>
224 #endif /* __KAME__ */
225
226 static int
227 _mapped_addr_enabled(void)
228 {
229         /* implementation dependent check */
230 #if defined(__KAME__) && defined(IPV6CTL_MAPPED_ADDR)
231         int mib[4];
232         size_t len;
233         int val;
234
235         mib[0] = CTL_NET;
236         mib[1] = PF_INET6;
237         mib[2] = IPPROTO_IPV6;
238         mib[3] = IPV6CTL_MAPPED_ADDR;
239         len = sizeof(val);
240         if (sysctl(mib, 4, &val, &len, 0, 0) == 0 && val != 0)
241                 return 1;
242 #endif /* __KAME__ && IPV6CTL_MAPPED_ADDR */
243         return 0;
244 }
245
246 #ifdef NS_CACHING
247 static int
248 ipnode_id_func(char *buffer, size_t *buffer_size, va_list ap,
249     void *cache_mdata)
250 {
251         res_state statp;
252         u_long res_options;
253
254         const int op_id = 2;
255         char *name;
256         int af;
257         size_t len;
258         void *src;
259
260         char *p;
261         size_t desired_size, size;
262         enum nss_lookup_type lookup_type;
263         int res = NS_UNAVAIL;
264
265         statp = __res_state();
266         res_options = statp->options & (RES_RECURSE | RES_DEFNAMES |
267             RES_DNSRCH | RES_NOALIASES | RES_USE_INET6);
268
269         lookup_type = (enum nss_lookup_type)cache_mdata;
270         switch (lookup_type) {
271         case nss_lt_name:
272                 name = va_arg(ap, char *);
273                 af = va_arg(ap, int);
274
275                 size = strlen(name);
276                 desired_size = sizeof(res_options) + sizeof(int) +
277                     sizeof(enum nss_lookup_type) + sizeof(int) + size + 1;
278
279                 if (desired_size > *buffer_size) {
280                         res = NS_RETURN;
281                         goto fin;
282                 }
283
284                 p = buffer;
285                 memcpy(p, &res_options, sizeof(res_options));
286                 p += sizeof(res_options);
287
288                 memcpy(p, &op_id, sizeof(int));
289                 p += sizeof(int);
290
291                 memcpy(p, &lookup_type, sizeof(enum nss_lookup_type));
292                 p += sizeof(enum nss_lookup_type);
293
294                 memcpy(p, &af, sizeof(int));
295                 p += sizeof(int);
296
297                 memcpy(p, name, size + 1);
298
299                 res = NS_SUCCESS;
300                 break;
301         case nss_lt_id:
302                 src = va_arg(ap, void *);
303                 len = va_arg(ap, size_t);
304                 af = va_arg(ap, int);
305
306                 desired_size = sizeof(res_options) + sizeof(int) +
307                     sizeof(enum nss_lookup_type) + sizeof(int) +
308                     sizeof(size_t) + len;
309
310                 if (desired_size > *buffer_size) {
311                         res = NS_RETURN;
312                         goto fin;
313                 }
314
315                 p = buffer;
316                 memcpy(p, &res_options, sizeof(res_options));
317                 p += sizeof(res_options);
318
319                 memcpy(p, &op_id, sizeof(int));
320                 p += sizeof(int);
321
322                 memcpy(p, &lookup_type, sizeof(enum nss_lookup_type));
323                 p += sizeof(enum nss_lookup_type);
324
325                 memcpy(p, &af, sizeof(int));
326                 p += sizeof(int);
327
328                 memcpy(p, &len, sizeof(size_t));
329                 p += sizeof(size_t);
330
331                 memcpy(p, src, len);
332
333                 res = NS_SUCCESS;
334                 break;
335         default:
336                 /* should be unreachable */
337                 return (NS_UNAVAIL);
338         }
339
340 fin:
341         *buffer_size = desired_size;
342         return (res);
343 }
344
345 static int
346 ipnode_marshal_func(char *buffer, size_t *buffer_size, void *retval,
347     va_list ap, void *cache_mdata)
348 {
349         struct hostent *ht;
350
351         struct hostent new_ht;
352         size_t desired_size, aliases_size, addr_size, size;
353         char *p, **iter;
354
355         ht = *((struct hostent **)retval);
356
357         desired_size = _ALIGNBYTES + sizeof(struct hostent) + sizeof(char *);
358         if (ht->h_name != NULL)
359                 desired_size += strlen(ht->h_name) + 1;
360
361         if (ht->h_aliases != NULL) {
362                 aliases_size = 0;
363                 for (iter = ht->h_aliases; *iter; ++iter) {
364                         desired_size += strlen(*iter) + 1;
365                         ++aliases_size;
366                 }
367
368                 desired_size += _ALIGNBYTES +
369                     (aliases_size + 1) * sizeof(char *);
370         }
371
372         if (ht->h_addr_list != NULL) {
373                 addr_size = 0;
374                 for (iter = ht->h_addr_list; *iter; ++iter)
375                         ++addr_size;
376
377                 desired_size += addr_size * _ALIGN(ht->h_length);
378                 desired_size += _ALIGNBYTES + (addr_size + 1) * sizeof(char *);
379         }
380
381         if (desired_size > *buffer_size) {
382                 /* this assignment is here for future use */
383                 *buffer_size = desired_size;
384                 return (NS_RETURN);
385         }
386
387         memcpy(&new_ht, ht, sizeof(struct hostent));
388         memset(buffer, 0, desired_size);
389
390         *buffer_size = desired_size;
391         p = buffer + sizeof(struct hostent) + sizeof(char *);
392         memcpy(buffer + sizeof(struct hostent), &p, sizeof(char *));
393         p = (char *)_ALIGN(p);
394
395         if (new_ht.h_name != NULL) {
396                 size = strlen(new_ht.h_name);
397                 memcpy(p, new_ht.h_name, size);
398                 new_ht.h_name = p;
399                 p += size + 1;
400         }
401
402         if (new_ht.h_aliases != NULL) {
403                 p = (char *)_ALIGN(p);
404                 memcpy(p, new_ht.h_aliases, sizeof(char *) * aliases_size);
405                 new_ht.h_aliases = (char **)p;
406                 p += sizeof(char *) * (aliases_size + 1);
407
408                 for (iter = new_ht.h_aliases; *iter; ++iter) {
409                         size = strlen(*iter);
410                         memcpy(p, *iter, size);
411                         *iter = p;
412                         p += size + 1;
413                 }
414         }
415
416         if (new_ht.h_addr_list != NULL) {
417                 p = (char *)_ALIGN(p);
418                 memcpy(p, new_ht.h_addr_list, sizeof(char *) * addr_size);
419                 new_ht.h_addr_list = (char **)p;
420                 p += sizeof(char *) * (addr_size + 1);
421
422                 size = _ALIGN(new_ht.h_length);
423                 for (iter = new_ht.h_addr_list; *iter; ++iter) {
424                         memcpy(p, *iter, size);
425                         *iter = p;
426                         p += size + 1;
427                 }
428         }
429         memcpy(buffer, &new_ht, sizeof(struct hostent));
430         return (NS_SUCCESS);
431 }
432
433 static int
434 ipnode_unmarshal_func(char *buffer, size_t buffer_size, void *retval,
435     va_list ap, void *cache_mdata)
436 {
437         struct hostent new_ht;
438         struct hostent *ht;
439
440         char *p;
441         char **iter;
442         char *orig_buf;
443         int err;
444
445         ht = &new_ht;
446
447         memcpy(ht, buffer, sizeof(struct hostent));
448         memcpy(&p, buffer + sizeof(struct hostent), sizeof(char *));
449
450         orig_buf = buffer + sizeof(struct hostent) + sizeof(char *) +
451             _ALIGN(p) - (size_t)p;
452         p = (char *)_ALIGN(p);
453
454
455         NS_APPLY_OFFSET(ht->h_name, orig_buf, p, char *);
456         if (ht->h_aliases != NULL) {
457                 NS_APPLY_OFFSET(ht->h_aliases, orig_buf, p, char **);
458
459                 for (iter = ht->h_aliases; *iter; ++iter)
460                         NS_APPLY_OFFSET(*iter, orig_buf, p, char *);
461         }
462
463         if (ht->h_addr_list != NULL) {
464                 NS_APPLY_OFFSET(ht->h_addr_list, orig_buf, p, char **);
465
466                 for (iter = ht->h_addr_list; *iter; ++iter)
467                         NS_APPLY_OFFSET(*iter, orig_buf, p, char *);
468         }
469
470         ht = _hpcopy(ht, &err);
471         if (ht == NULL)
472                 return (NS_UNAVAIL);
473
474         *((struct hostent **)retval) = ht;
475         return (NS_SUCCESS);
476 }
477 #endif
478
479 /*
480  * Functions defined in RFC2553
481  *      getipnodebyname, getipnodebyaddr, freehostent
482  */
483
484 static struct hostent *
485 _ghbyname(const char *name, int af, int flags, int *errp)
486 {
487         struct hostent *hp;
488         int i, rval;
489
490 #ifdef NS_CACHING
491         static const nss_cache_info cache_info =
492         NS_COMMON_CACHE_INFO_INITIALIZER(
493                 hosts, (void *)nss_lt_name,
494                 ipnode_id_func, ipnode_marshal_func, ipnode_unmarshal_func);
495 #endif
496
497         static const ns_dtab dtab[] = {
498                 NS_FILES_CB(_files_ghbyname, NULL)
499                 { NSSRC_DNS, _dns_ghbyname, NULL },
500                 NS_NIS_CB(_nis_ghbyname, NULL)
501 #ifdef NS_CACHING
502                 NS_CACHE_CB(&cache_info)
503 #endif
504                 { 0 }
505         };
506
507         if (flags & AI_ADDRCONFIG) {
508                 int s;
509
510                 /*
511                  * TODO:
512                  * Note that implementation dependent test for address
513                  * configuration should be done everytime called
514                  * (or apropriate interval),
515                  * because addresses will be dynamically assigned or deleted.
516                  */
517                 if (af == AF_UNSPEC) {
518                         if ((s = _socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
519                                 af = AF_INET;
520                         else {
521                                 _close(s);
522                                 if ((s = _socket(AF_INET, SOCK_DGRAM, 0)) < 0)
523                                         af = AF_INET6;
524                                 else
525                                 _close(s);
526                         }
527
528                 }
529                 if (af != AF_UNSPEC) {
530                         if ((s = _socket(af, SOCK_DGRAM, 0)) < 0)
531                                 return NULL;
532                         _close(s);
533                 }
534         }
535
536         rval = nsdispatch(&hp, dtab, NSDB_HOSTS, "ghbyname", default_src,
537                           name, af, errp);
538         return (rval == NS_SUCCESS) ? hp : NULL;
539 }
540
541 /* getipnodebyname() internal routine for multiple query(PF_UNSPEC) support. */
542 static struct hostent *
543 _getipnodebyname_multi(const char *name, int af, int flags, int *errp)
544 {
545         struct hostent *hp;
546         union inx_addr addrbuf;
547
548         /* XXX: PF_UNSPEC is only supposed to be passed from getaddrinfo() */
549         if (af != AF_INET
550 #ifdef INET6
551             && af != AF_INET6
552 #endif
553             && af != PF_UNSPEC
554                 )
555         {
556                 *errp = NO_RECOVERY;
557                 return NULL;
558         }
559
560 #ifdef INET6
561         /* special case for literal address */
562         if (inet_pton(AF_INET6, name, &addrbuf) == 1) {
563                 if (af != AF_INET6) {
564                         *errp = HOST_NOT_FOUND;
565                         return NULL;
566                 }
567                 return _hpaddr(af, name, &addrbuf, errp);
568         }
569 #endif
570         if (inet_aton(name, (struct in_addr *)&addrbuf) == 1) {
571                 if (af != AF_INET) {
572                         if (MAPADDRENABLED(flags)) {
573                                 MAPADDR(&addrbuf, &addrbuf.in_addr);
574                         } else {
575                                 *errp = HOST_NOT_FOUND;
576                                 return NULL;
577                         }
578                 }
579                 return _hpaddr(af, name, &addrbuf, errp);
580         }
581
582         *errp = HOST_NOT_FOUND;
583         hp = _ghbyname(name, af, flags, errp);
584
585 #ifdef INET6
586         if (af == AF_INET6
587         &&  ((flags & AI_ALL) || hp == NULL)
588         &&  (MAPADDRENABLED(flags))) {
589                 struct hostent *hp2 = _ghbyname(name, AF_INET, flags, errp);
590                 if (hp == NULL)
591                         hp = _hpmapv6(hp2, errp);
592                 else {
593                         if (hp2 && strcmp(hp->h_name, hp2->h_name) != 0) {
594                                 freehostent(hp2);
595                                 hp2 = NULL;
596                         }
597                         hp = _hpmerge(hp, hp2, errp);
598                 }
599         }
600 #endif
601         return _hpsort(hp);
602 }
603
604 struct hostent *
605 getipnodebyname(const char *name, int af, int flags, int *errp)
606 {
607         if (af != AF_INET
608 #ifdef INET6
609             && af != AF_INET6
610 #endif
611                 )
612         {
613                 *errp = NO_RECOVERY;
614                 return NULL;
615         }
616         return(_getipnodebyname_multi(name, af ,flags, errp));
617 }
618
619 struct hostent *
620 getipnodebyaddr(const void *src, size_t len, int af, int *errp)
621 {
622         struct hostent *hp;
623         int i, rval;
624 #ifdef INET6
625         struct in6_addr addrbuf;
626 #else
627         struct in_addr addrbuf;
628 #endif
629
630 #ifdef NS_CACHING
631         static const nss_cache_info cache_info =
632         NS_COMMON_CACHE_INFO_INITIALIZER(
633                 hosts, (void *)nss_lt_id,
634                 ipnode_id_func, ipnode_marshal_func, ipnode_unmarshal_func);
635 #endif
636         static const ns_dtab dtab[] = {
637                 NS_FILES_CB(_files_ghbyaddr, NULL)
638                 { NSSRC_DNS, _dns_ghbyaddr, NULL },
639                 NS_NIS_CB(_nis_ghbyaddr, NULL)
640 #ifdef ICMPNL
641                 { NSSRC_ICMP, _icmp_ghbyaddr, NULL },
642 #endif
643 #ifdef NS_CACHING
644                 NS_CACHE_CB(&cache_info)
645 #endif
646                 { 0 }
647         };
648
649         *errp = HOST_NOT_FOUND;
650
651         switch (af) {
652         case AF_INET:
653                 if (len != sizeof(struct in_addr)) {
654                         *errp = NO_RECOVERY;
655                         return NULL;
656                 }
657                 if ((long)src & ~(sizeof(struct in_addr) - 1)) {
658                         memcpy(&addrbuf, src, len);
659                         src = &addrbuf;
660                 }
661                 if (((const struct in_addr *)src)->s_addr == 0)
662                         return NULL;
663                 break;
664 #ifdef INET6
665         case AF_INET6:
666                 if (len != sizeof(struct in6_addr)) {
667                         *errp = NO_RECOVERY;
668                         return NULL;
669                 }
670                 if ((long)src & ~(sizeof(struct in6_addr) / 2 - 1)) {   /*XXX*/
671                         memcpy(&addrbuf, src, len);
672                         src = &addrbuf;
673                 }
674                 if (IN6_IS_ADDR_UNSPECIFIED((const struct in6_addr *)src))
675                         return NULL;
676                 if (IN6_IS_ADDR_V4MAPPED((const struct in6_addr *)src)
677                 ||  IN6_IS_ADDR_V4COMPAT((const struct in6_addr *)src)) {
678                         src = (const char *)src +
679                             (sizeof(struct in6_addr) - sizeof(struct in_addr));
680                         af = AF_INET;
681                         len = sizeof(struct in_addr);
682                 }
683                 break;
684 #endif
685         default:
686                 *errp = NO_RECOVERY;
687                 return NULL;
688         }
689
690         rval = nsdispatch(&hp, dtab, NSDB_HOSTS, "ghbyaddr", default_src,
691                           src, len, af, errp);
692         return (rval == NS_SUCCESS) ? hp : NULL;
693 }
694
695 void
696 freehostent(struct hostent *ptr)
697 {
698         free(ptr);
699 }
700
701 #if 0
702
703 /* XXX: should be deprecated */
704 struct hostent *
705 getnodebyname(const char *name, int af, int flags)
706 {
707         return getipnodebyname(name, af, flags, &h_errno);
708 }
709
710 #ifdef __warn_references
711 __warn_references(getnodebyname,
712         "warning: getnodebyname() deprecated, "
713         "should use getaddrinfo() or getipnodebyname()");
714 #endif
715
716 struct hostent *
717 getnodebyaddr(const void *src, size_t len, int af)
718 {
719         return getipnodebyaddr(src, len, af, &h_errno);
720 }
721
722 #ifdef __warn_references
723 __warn_references(getnodebyaddr,
724         "warning: getnodebyaddr() deprecated, "
725         "should use getnameinfo() or getipnodebyaddr()");
726 #endif
727
728 #endif
729
730 /*
731  * Private utility functions
732  */
733
734 /*
735  * _hpcopy: allocate and copy hostent structure
736  */
737 static struct hostent *
738 _hpcopy(struct hostent *hp, int *errp)
739 {
740         struct hostent *nhp;
741         char *cp, **pp;
742         int size, addrsize;
743         int nalias = 0, naddr = 0;
744         int al_off;
745         int i;
746
747         if (hp == NULL)
748                 return hp;
749
750         /* count size to be allocated */
751         size = sizeof(struct hostent);
752         if (hp->h_name != NULL)
753                 size += strlen(hp->h_name) + 1;
754         if ((pp = hp->h_aliases) != NULL) {
755                 for (i = 0; *pp != NULL; i++, pp++) {
756                         if (**pp != '\0') {
757                                 size += strlen(*pp) + 1;
758                                 nalias++;
759                         }
760                 }
761         }
762         /* adjust alignment */
763         size = ALIGN(size);
764         al_off = size;
765         size += sizeof(char *) * (nalias + 1);
766         addrsize = ALIGN(hp->h_length);
767         if ((pp = hp->h_addr_list) != NULL) {
768                 while (*pp++ != NULL)
769                         naddr++;
770         }
771         size += addrsize * naddr;
772         size += sizeof(char *) * (naddr + 1);
773
774         /* copy */
775         if ((nhp = (struct hostent *)malloc(size)) == NULL) {
776                 *errp = TRY_AGAIN;
777                 return NULL;
778         }
779         cp = (char *)&nhp[1];
780         if (hp->h_name != NULL) {
781                 nhp->h_name = cp;
782                 strcpy(cp, hp->h_name);
783                 cp += strlen(cp) + 1;
784         } else
785                 nhp->h_name = NULL;
786         nhp->h_aliases = (char **)((char *)nhp + al_off);
787         if ((pp = hp->h_aliases) != NULL) {
788                 for (i = 0; *pp != NULL; pp++) {
789                         if (**pp != '\0') {
790                                 nhp->h_aliases[i++] = cp;
791                                 strcpy(cp, *pp);
792                                 cp += strlen(cp) + 1;
793                         }
794                 }
795         }
796         nhp->h_aliases[nalias] = NULL;
797         cp = (char *)&nhp->h_aliases[nalias + 1];
798         nhp->h_addrtype = hp->h_addrtype;
799         nhp->h_length = hp->h_length;
800         nhp->h_addr_list = (char **)cp;
801         if ((pp = hp->h_addr_list) != NULL) {
802                 cp = (char *)&nhp->h_addr_list[naddr + 1];
803                 for (i = 0; *pp != NULL; pp++) {
804                         nhp->h_addr_list[i++] = cp;
805                         memcpy(cp, *pp, hp->h_length);
806                         cp += addrsize;
807                 }
808         }
809         nhp->h_addr_list[naddr] = NULL;
810         return nhp;
811 }
812
813 /*
814  * _hpaddr: construct hostent structure with one address
815  */
816 static struct hostent *
817 _hpaddr(int af, const char *name, void *addr, int *errp)
818 {
819         struct hostent *hp, hpbuf;
820         char *addrs[2];
821
822         hp = &hpbuf;
823         hp->h_name = name;
824         hp->h_aliases = NULL;
825         hp->h_addrtype = af;
826         hp->h_length = ADDRLEN(af);
827         hp->h_addr_list = addrs;
828         addrs[0] = addr;
829         addrs[1] = NULL;
830         return _hpcopy(hp, errp);
831 }
832
833 /*
834  * _hpmerge: merge 2 hostent structure, arguments will be freed
835  */
836 static struct hostent *
837 _hpmerge(struct hostent *hp1, struct hostent *hp2, int *errp)
838 {
839         int i, j;
840         int naddr, nalias;
841         char **pp;
842         struct hostent *hp, hpbuf;
843         char *aliases[MAXALIASES + 1], *addrs[MAXADDRS + 1];
844         union inx_addr addrbuf[MAXADDRS];
845
846         if (hp1 == NULL)
847                 return hp2;
848         if (hp2 == NULL)
849                 return hp1;
850
851 #define HP(i)   (i == 1 ? hp1 : hp2)
852         hp = &hpbuf;
853         hp->h_name = (hp1->h_name != NULL ? hp1->h_name : hp2->h_name);
854         hp->h_aliases = aliases;
855         nalias = 0;
856         for (i = 1; i <= 2; i++) {
857                 if ((pp = HP(i)->h_aliases) == NULL)
858                         continue;
859                 for (; nalias < MAXALIASES && *pp != NULL; pp++) {
860                         /* check duplicates */
861                         for (j = 0; j < nalias; j++)
862                                 if (strcasecmp(*pp, aliases[j]) == 0)
863                                         break;
864                         if (j == nalias)
865                                 aliases[nalias++] = *pp;
866                 }
867         }
868         aliases[nalias] = NULL;
869 #ifdef INET6
870         if (hp1->h_length != hp2->h_length) {
871                 hp->h_addrtype = AF_INET6;
872                 hp->h_length = sizeof(struct in6_addr);
873         } else {
874 #endif
875                 hp->h_addrtype = hp1->h_addrtype;
876                 hp->h_length = hp1->h_length;
877 #ifdef INET6
878         }
879 #endif
880         hp->h_addr_list = addrs;
881         naddr = 0;
882         for (i = 1; i <= 2; i++) {
883                 if ((pp = HP(i)->h_addr_list) == NULL)
884                         continue;
885                 if (HP(i)->h_length == hp->h_length) {
886                         while (naddr < MAXADDRS && *pp != NULL)
887                                 addrs[naddr++] = *pp++;
888                 } else {
889                         /* copy IPv4 addr as mapped IPv6 addr */
890                         while (naddr < MAXADDRS && *pp != NULL) {
891                                 MAPADDR(&addrbuf[naddr], *pp++);
892                                 addrs[naddr] = (char *)&addrbuf[naddr];
893                                 naddr++;
894                         }
895                 }
896         }
897         addrs[naddr] = NULL;
898         hp = _hpcopy(hp, errp);
899         freehostent(hp1);
900         freehostent(hp2);
901         return hp;
902 }
903
904 /*
905  * _hpmapv6: convert IPv4 hostent into IPv4-mapped IPv6 addresses
906  */
907 #ifdef INET6
908 static struct hostent *
909 _hpmapv6(struct hostent *hp, int *errp)
910 {
911         struct hostent *hp6;
912
913         if (hp == NULL)
914                 return NULL;
915         if (hp->h_addrtype == AF_INET6)
916                 return hp;
917
918         /* make dummy hostent to convert IPv6 address */
919         if ((hp6 = (struct hostent *)malloc(sizeof(struct hostent))) == NULL) {
920                 *errp = TRY_AGAIN;
921                 return NULL;
922         }
923         hp6->h_name = NULL;
924         hp6->h_aliases = NULL;
925         hp6->h_addrtype = AF_INET6;
926         hp6->h_length = sizeof(struct in6_addr);
927         hp6->h_addr_list = NULL;
928         return _hpmerge(hp6, hp, errp);
929 }
930 #endif
931
932 /*
933  * _hpsort: sort address by sortlist
934  */
935 static struct hostent *
936 _hpsort(struct hostent *hp)
937 {
938         int i, j, n;
939         u_char *ap, *sp, *mp, **pp;
940         char t;
941         char order[MAXADDRS];
942         int nsort = _res.nsort;
943
944         if (hp == NULL || hp->h_addr_list[1] == NULL || nsort == 0)
945                 return hp;
946         for (i = 0; (ap = (u_char *)hp->h_addr_list[i]); i++) {
947                 for (j = 0; j < nsort; j++) {
948 #ifdef INET6
949                         if (_res_ext.sort_list[j].af != hp->h_addrtype)
950                                 continue;
951                         sp = (u_char *)&_res_ext.sort_list[j].addr;
952                         mp = (u_char *)&_res_ext.sort_list[j].mask;
953 #else
954                         sp = (u_char *)&_res.sort_list[j].addr;
955                         mp = (u_char *)&_res.sort_list[j].mask;
956 #endif
957                         for (n = 0; n < hp->h_length; n++) {
958                                 if ((ap[n] & mp[n]) != sp[n])
959                                         break;
960                         }
961                         if (n == hp->h_length)
962                                 break;
963                 }
964                 order[i] = j;
965         }
966         n = i;
967         pp = (u_char **)hp->h_addr_list;
968         for (i = 0; i < n - 1; i++) {
969                 for (j = i + 1; j < n; j++) {
970                         if (order[i] > order[j]) {
971                                 ap = pp[i];
972                                 pp[i] = pp[j];
973                                 pp[j] = ap;
974                                 t = order[i];
975                                 order[i] = order[j];
976                                 order[j] = t;
977                         }
978                 }
979         }
980         return hp;
981 }
982
983 static char *
984 _hgetword(char **pp)
985 {
986         char c, *p, *ret;
987         const char *sp;
988         static const char sep[] = "# \t\n";
989
990         ret = NULL;
991         for (p = *pp; (c = *p) != '\0'; p++) {
992                 for (sp = sep; *sp != '\0'; sp++) {
993                         if (c == *sp)
994                                 break;
995                 }
996                 if (c == '#')
997                         p[1] = '\0';    /* ignore rest of line */
998                 if (ret == NULL) {
999                         if (*sp == '\0')
1000                                 ret = p;
1001                 } else {
1002                         if (*sp != '\0') {
1003                                 *p++ = '\0';
1004                                 break;
1005                         }
1006                 }
1007         }
1008         *pp = p;
1009         if (ret == NULL || *ret == '\0')
1010                 return NULL;
1011         return ret;
1012 }
1013
1014 /*
1015  * FILES (/etc/hosts)
1016  */
1017
1018 static FILE *
1019 _files_open(int *errp)
1020 {
1021         FILE *fp;
1022         fp = fopen(_PATH_HOSTS, "r");
1023         if (fp == NULL)
1024                 *errp = NO_RECOVERY;
1025         return fp;
1026 }
1027
1028 static int
1029 _files_ghbyname(void *rval, void *cb_data, va_list ap)
1030 {
1031         const char *name;
1032         int af;
1033         int *errp;
1034         int match, nalias;
1035         char *p, *line, *addrstr, *cname;
1036         FILE *fp;
1037         struct hostent *rethp, *hp, hpbuf;
1038         char *aliases[MAXALIASES + 1], *addrs[2];
1039         union inx_addr addrbuf;
1040         char buf[BUFSIZ];
1041         int af0 = af;
1042
1043         name = va_arg(ap, const char *);
1044         af = va_arg(ap, int);
1045         errp = va_arg(ap, int *);
1046
1047         *(struct hostent **)rval = NULL;
1048
1049         if ((fp = _files_open(errp)) == NULL)
1050                 return NS_UNAVAIL;
1051         rethp = hp = NULL;
1052
1053         while (fgets(buf, sizeof(buf), fp)) {
1054                 line = buf;
1055                 if ((addrstr = _hgetword(&line)) == NULL
1056                 ||  (cname = _hgetword(&line)) == NULL)
1057                         continue;
1058                 match = (strcasecmp(cname, name) == 0);
1059                 nalias = 0;
1060                 while ((p = _hgetword(&line)) != NULL) {
1061                         if (!match)
1062                                 match = (strcasecmp(p, name) == 0);
1063                         if (nalias < MAXALIASES)
1064                                 aliases[nalias++] = p;
1065                 }
1066                 if (!match)
1067                         continue;
1068                 switch (af0) {
1069                 case AF_INET:
1070                         if (inet_aton(addrstr, (struct in_addr *)&addrbuf)
1071                             != 1) {
1072                                 *errp = NO_DATA;        /* name found */
1073                                 continue;
1074                         }
1075                         af = af0;
1076                         break;
1077 #ifdef INET6
1078                 case AF_INET6:
1079                         if (inet_pton(af, addrstr, &addrbuf) != 1) {
1080                                 *errp = NO_DATA;        /* name found */
1081                                 continue;
1082                         }
1083                         af = af0;
1084                         break;
1085 #endif
1086                 case AF_UNSPEC:
1087                         if (inet_aton(addrstr, (struct in_addr *)&addrbuf)
1088                             == 1) {
1089                                 af = AF_INET;
1090                                 break;
1091                         }
1092 #ifdef INET6
1093                         if (inet_pton(AF_INET6, addrstr, &addrbuf) == 1) {
1094                                 af = AF_INET6;
1095                                 break; 
1096                         }
1097 #endif
1098                         *errp = NO_DATA;        /* name found */
1099                         continue;
1100                         /* NOTREACHED */
1101                 }
1102                 hp = &hpbuf;
1103                 hp->h_name = cname;
1104                 hp->h_aliases = aliases;
1105                 aliases[nalias] = NULL;
1106                 hp->h_addrtype = af;
1107                 hp->h_length = ADDRLEN(af);
1108                 hp->h_addr_list = addrs;
1109                 addrs[0] = (char *)&addrbuf;
1110                 addrs[1] = NULL;
1111                 hp = _hpcopy(hp, errp);
1112                 rethp = _hpmerge(rethp, hp, errp);
1113         }
1114         fclose(fp);
1115         *(struct hostent **)rval = rethp;
1116         return (rethp != NULL) ? NS_SUCCESS : NS_NOTFOUND;
1117 }
1118
1119 static int
1120 _files_ghbyaddr(void *rval, void *cb_data, va_list ap)
1121 {
1122         const void *addr;
1123         int addrlen;
1124         int af;
1125         int *errp;
1126         int nalias;
1127         char *p, *line;
1128         FILE *fp;
1129         struct hostent *hp, hpbuf;
1130         char *aliases[MAXALIASES + 1], *addrs[2];
1131         union inx_addr addrbuf;
1132         char buf[BUFSIZ];
1133
1134         addr = va_arg(ap, const void *);
1135         addrlen = va_arg(ap, int);
1136         af = va_arg(ap, int);
1137         errp = va_arg(ap, int *);
1138
1139         *(struct hostent**)rval = NULL;
1140
1141         if ((fp = _files_open(errp)) == NULL)
1142                 return NS_UNAVAIL;
1143         hp = NULL;
1144         while (fgets(buf, sizeof(buf), fp)) {
1145                 line = buf;
1146                 if ((p = _hgetword(&line)) == NULL
1147                 ||  (af == AF_INET
1148                      ? inet_aton(p, (struct in_addr *)&addrbuf)
1149                      : inet_pton(af, p, &addrbuf)) != 1
1150                 ||  memcmp(addr, &addrbuf, addrlen) != 0
1151                 ||  (p = _hgetword(&line)) == NULL)
1152                         continue;
1153                 hp = &hpbuf;
1154                 hp->h_name = p;
1155                 hp->h_aliases = aliases;
1156                 nalias = 0;
1157                 while ((p = _hgetword(&line)) != NULL) {
1158                         if (nalias < MAXALIASES)
1159                                 aliases[nalias++] = p;
1160                 }
1161                 aliases[nalias] = NULL;
1162                 hp->h_addrtype = af;
1163                 hp->h_length = addrlen;
1164                 hp->h_addr_list = addrs;
1165                 addrs[0] = (char *)&addrbuf;
1166                 addrs[1] = NULL;
1167                 hp = _hpcopy(hp, errp);
1168                 break;
1169         }
1170         fclose(fp);
1171         *(struct hostent **)rval = hp;
1172         return (hp != NULL) ? NS_SUCCESS : NS_NOTFOUND;
1173 }
1174
1175 #ifdef YP
1176 /*
1177  * NIS
1178  *
1179  * XXX actually a hack, these are INET4 specific.
1180  */
1181 static int
1182 _nis_ghbyname(void *rval, void *cb_data, va_list ap)
1183 {
1184         const char *name;
1185         int af;
1186         int *errp;
1187         struct hostent *hp = NULL;
1188
1189         name = va_arg(ap, const char *);
1190         af = va_arg(ap, int);
1191         errp = va_arg(ap, int *);
1192
1193         if (af == AF_UNSPEC)
1194                 af = AF_INET;
1195         if (af == AF_INET) {
1196                 hp = _gethostbynisname(name, af);
1197                 if (hp != NULL)
1198                         hp = _hpcopy(hp, errp);
1199         }
1200
1201         *(struct hostent **)rval = hp;
1202         return (hp != NULL) ? NS_SUCCESS : NS_NOTFOUND;
1203 }
1204
1205 static int
1206 _nis_ghbyaddr(void *rval, void *cb_data, va_list ap)
1207 {
1208         const void *addr;
1209         int addrlen;
1210         int af;
1211         int *errp;
1212         struct hostent *hp = NULL;
1213
1214         addr = va_arg(ap, const void *);
1215         addrlen = va_arg(ap, int);
1216         af = va_arg(ap, int);
1217
1218         if (af == AF_INET) {
1219                 hp = _gethostbynisaddr(addr, addrlen, af);
1220                 if (hp != NULL)
1221                         hp = _hpcopy(hp, errp);
1222         }
1223         *(struct hostent **)rval = hp;
1224         return (hp != NULL) ? NS_SUCCESS : NS_NOTFOUND;
1225 }
1226 #endif
1227
1228 struct __res_type_list {
1229         SLIST_ENTRY(__res_type_list) rtl_entry;
1230         int     rtl_type;
1231 };
1232
1233 #define MAXPACKET       (64*1024)
1234
1235 typedef union {
1236         HEADER hdr;
1237         u_char buf[MAXPACKET];
1238 } querybuf;
1239
1240 static struct hostent *getanswer (const querybuf *, int, const char *,
1241         int, struct hostent *, int *);
1242
1243 /*
1244  * we don't need to take care about sorting, nor IPv4 mapped address here.
1245  */
1246 static struct hostent *
1247 getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1248           struct hostent *template, int *errp)
1249 {
1250         const HEADER *hp;
1251         const u_char *cp;
1252         int n;
1253         const u_char *eom, *erdata;
1254         char *bp, **ap, **hap, *obp;
1255         int type, class, buflen, ancount, qdcount;
1256         int haveanswer, had_error;
1257         char tbuf[MAXDNAME];
1258         const char *tname;
1259         int (*name_ok) (const char *);
1260         static char *h_addr_ptrs[MAXADDRS + 1];
1261         static char *host_aliases[MAXALIASES];
1262         static char hostbuf[8*1024];
1263
1264 #define BOUNDED_INCR(x) \
1265         do { \
1266                 cp += x; \
1267                 if (cp > eom) { \
1268                         *errp = NO_RECOVERY; \
1269                         return (NULL); \
1270                 } \
1271         } while (0)
1272
1273 #define BOUNDS_CHECK(ptr, count) \
1274         do { \
1275                 if ((ptr) + (count) > eom) { \
1276                         *errp = NO_RECOVERY; \
1277                         return (NULL); \
1278                 } \
1279         } while (0)
1280
1281 /* XXX do {} while (0) cannot be put here */
1282 #define DNS_ASSERT(x) \
1283         {                               \
1284                 if (!(x)) {             \
1285                         cp += n;        \
1286                         continue;       \
1287                 }                       \
1288         }
1289
1290 /* XXX do {} while (0) cannot be put here */
1291 #define DNS_FATAL(x) \
1292         {                               \
1293                 if (!(x)) {             \
1294                         had_error++;    \
1295                         continue;       \
1296                 }                       \
1297         }
1298
1299         tname = qname;
1300         template->h_name = NULL;
1301         eom = answer->buf + anslen;
1302         switch (qtype) {
1303         case T_A:
1304         case T_AAAA:
1305                 name_ok = res_hnok;
1306                 break;
1307         case T_PTR:
1308                 name_ok = res_dnok;
1309                 break;
1310         default:
1311                 return (NULL);  /* XXX should be abort(); */
1312         }
1313         /*
1314          * find first satisfactory answer
1315          */
1316         hp = &answer->hdr;
1317         ancount = ntohs(hp->ancount);
1318         qdcount = ntohs(hp->qdcount);
1319         bp = hostbuf;
1320         buflen = sizeof hostbuf;
1321         cp = answer->buf;
1322         BOUNDED_INCR(HFIXEDSZ);
1323         if (qdcount != 1) {
1324                 *errp = NO_RECOVERY;
1325                 return (NULL);
1326         }
1327         n = dn_expand(answer->buf, eom, cp, bp, buflen);
1328         if ((n < 0) || !(*name_ok)(bp)) {
1329                 *errp = NO_RECOVERY;
1330                 return (NULL);
1331         }
1332         BOUNDED_INCR(n + QFIXEDSZ);
1333         if (qtype == T_A || qtype == T_AAAA) {
1334                 /* res_send() has already verified that the query name is the
1335                  * same as the one we sent; this just gets the expanded name
1336                  * (i.e., with the succeeding search-domain tacked on).
1337                  */
1338                 n = strlen(bp) + 1;             /* for the \0 */
1339                 if (n >= MAXHOSTNAMELEN) {
1340                         *errp = NO_RECOVERY;
1341                         return (NULL);
1342                 }
1343                 template->h_name = bp;
1344                 bp += n;
1345                 buflen -= n;
1346                 /* The qname can be abbreviated, but h_name is now absolute. */
1347                 qname = template->h_name;
1348         }
1349         ap = host_aliases;
1350         *ap = NULL;
1351         template->h_aliases = host_aliases;
1352         hap = h_addr_ptrs;
1353         *hap = NULL;
1354         template->h_addr_list = h_addr_ptrs;
1355         haveanswer = 0;
1356         had_error = 0;
1357         while (ancount-- > 0 && cp < eom && !had_error) {
1358                 n = dn_expand(answer->buf, eom, cp, bp, buflen);
1359                 DNS_FATAL(n >= 0);
1360                 DNS_FATAL((*name_ok)(bp));
1361                 cp += n;                        /* name */
1362                 BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
1363                 NS_GET16(type, cp);             /* type */
1364                 NS_GET16(class, cp);            /* class */
1365                 cp += INT32SZ;                  /* skip TTL */
1366                 NS_GET16(n, cp);                /* len */
1367                 BOUNDS_CHECK(cp, n);
1368                 erdata = cp + n;
1369                 DNS_ASSERT(class == C_IN);
1370                 if ((qtype == T_A || qtype == T_AAAA) && type == T_CNAME) {
1371                         if (ap >= &host_aliases[MAXALIASES-1])
1372                                 continue;
1373                         n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1374                         DNS_FATAL(n >= 0);
1375                         DNS_FATAL((*name_ok)(tbuf));
1376                         cp += n;
1377                         if (cp != erdata) {
1378                                 *errp = NO_RECOVERY;
1379                                 return (NULL);
1380                         }
1381                         /* Store alias. */
1382                         *ap++ = bp;
1383                         n = strlen(bp) + 1;     /* for the \0 */
1384                         DNS_FATAL(n < MAXHOSTNAMELEN);
1385                         bp += n;
1386                         buflen -= n;
1387                         /* Get canonical name. */
1388                         n = strlen(tbuf) + 1;   /* for the \0 */
1389                         DNS_FATAL(n <= buflen);
1390                         DNS_FATAL(n < MAXHOSTNAMELEN);
1391                         strcpy(bp, tbuf);
1392                         template->h_name = bp;
1393                         bp += n;
1394                         buflen -= n;
1395                         continue;
1396                 }
1397                 if (qtype == T_PTR && type == T_CNAME) {
1398                         n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1399                         if (n < 0 || !res_dnok(tbuf)) {
1400                                 had_error++;
1401                                 continue;
1402                         }
1403                         cp += n;
1404                         if (cp != erdata) {
1405                                 *errp = NO_RECOVERY;
1406                                 return (NULL);
1407                         }
1408                         /* Get canonical name. */
1409                         n = strlen(tbuf) + 1;   /* for the \0 */
1410                         if (n > buflen || n >= MAXHOSTNAMELEN) {
1411                                 had_error++;
1412                                 continue;
1413                         }
1414                         strcpy(bp, tbuf);
1415                         tname = bp;
1416                         bp += n;
1417                         buflen -= n;
1418                         continue;
1419                 }
1420                 DNS_ASSERT(type == qtype);
1421                 switch (type) {
1422                 case T_PTR:
1423                         DNS_ASSERT(strcasecmp(tname, bp) == 0);
1424                         n = dn_expand(answer->buf, eom, cp, bp, buflen);
1425                         DNS_FATAL(n >= 0);
1426                         DNS_FATAL(res_hnok(bp));
1427 #if MULTI_PTRS_ARE_ALIASES
1428                         cp += n;
1429                         if (cp != erdata) {
1430                                 *errp = NO_RECOVERY;
1431                                 return (NULL);
1432                         }
1433                         if (!haveanswer)
1434                                 template->h_name = bp;
1435                         else if (ap < &host_aliases[MAXALIASES-1])
1436                                 *ap++ = bp;
1437                         else
1438                                 n = -1;
1439                         if (n != -1) {
1440                                 n = strlen(bp) + 1;     /* for the \0 */
1441                                 if (n >= MAXHOSTNAMELEN) {
1442                                         had_error++;
1443                                         break;
1444                                 }
1445                                 bp += n;
1446                                 buflen -= n;
1447                         }
1448                         break;
1449 #else
1450                         template->h_name = bp;
1451                         *errp = NETDB_SUCCESS;
1452                         return (template);
1453 #endif
1454                 case T_A:
1455                 case T_AAAA:
1456                         DNS_ASSERT(strcasecmp(template->h_name, bp) == 0);
1457                         DNS_ASSERT(n == template->h_length);
1458                         if (!haveanswer) {
1459                                 int nn;
1460
1461                                 template->h_name = bp;
1462                                 nn = strlen(bp) + 1;    /* for the \0 */
1463                                 bp += nn;
1464                                 buflen -= nn;
1465                         }
1466                         obp = bp; /* ALIGN rounds up */
1467                         bp = (char *)ALIGN(bp);
1468                         buflen -= (bp - obp);
1469
1470                         DNS_FATAL(bp + n < &hostbuf[sizeof hostbuf]);
1471                         DNS_ASSERT(hap < &h_addr_ptrs[MAXADDRS-1]);
1472 #ifdef FILTER_V4MAPPED
1473                         if (type == T_AAAA) {
1474                                 struct in6_addr in6;
1475                                 memcpy(&in6, cp, sizeof(in6));
1476                                 DNS_ASSERT(IN6_IS_ADDR_V4MAPPED(&in6) == 0);
1477                         }
1478 #endif
1479                         bcopy(cp, *hap++ = bp, n);
1480                         bp += n;
1481                         buflen -= n;
1482                         cp += n;
1483                         if (cp != erdata) {
1484                                 *errp = NO_RECOVERY;
1485                                 return (NULL);
1486                         }
1487                         break;
1488                 default:
1489                         abort();
1490                 }
1491                 if (!had_error)
1492                         haveanswer++;
1493         }
1494         if (haveanswer) {
1495                 *ap = NULL;
1496                 *hap = NULL;
1497                 if (!template->h_name) {
1498                         n = strlen(qname) + 1;  /* for the \0 */
1499                         if (n > buflen || n >= MAXHOSTNAMELEN)
1500                                 goto no_recovery;
1501                         strcpy(bp, qname);
1502                         template->h_name = bp;
1503                         bp += n;
1504                         buflen -= n;
1505                 }
1506                 *errp = NETDB_SUCCESS;
1507                 return (template);
1508         }
1509  no_recovery:
1510         *errp = NO_RECOVERY;
1511         return (NULL);
1512
1513 #undef BOUNDED_INCR
1514 #undef BOUNDS_CHECK
1515 #undef DNS_ASSERT
1516 #undef DNS_FATAL
1517 }
1518
1519 /* res_search() variant with multiple query support. */
1520 static struct hostent *
1521 _res_search_multi(const char *name, struct __res_type_list *rtl, int *errp)
1522 {
1523         const char *cp, * const *domain;
1524         struct hostent *hp0 = NULL, *hp;
1525         struct hostent hpbuf;
1526         u_int dots;
1527         int trailing_dot, ret, saved_herrno;
1528         int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
1529         struct __res_type_list *rtl0 = rtl;
1530         querybuf *buf;
1531
1532         if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1533                 *errp = NETDB_INTERNAL;
1534                 return (NULL);
1535         }
1536         dots = 0;
1537         for (cp = name; *cp; cp++)
1538                 dots += (*cp == '.');
1539         trailing_dot = 0;
1540         if (cp > name && *--cp == '.')
1541                 trailing_dot++;
1542
1543         buf = malloc(sizeof(*buf));
1544         if (buf == NULL) {
1545                 *errp = NETDB_INTERNAL;
1546                 return NULL;
1547         }
1548
1549         /* If there aren't any dots, it could be a user-level alias */
1550         if (!dots && (cp = hostalias(name)) != NULL) {
1551                 for(rtl = rtl0; rtl != NULL;
1552                     rtl = SLIST_NEXT(rtl, rtl_entry)) {
1553                         ret = res_query(cp, C_IN, rtl->rtl_type, buf->buf,
1554                                              sizeof(buf->buf));
1555                         if (ret > 0 && (size_t)ret < sizeof(buf->buf)) {
1556                                 hpbuf.h_addrtype = (rtl->rtl_type == T_AAAA)
1557                                     ? AF_INET6 : AF_INET;
1558                                 hpbuf.h_length = ADDRLEN(hpbuf.h_addrtype);
1559                                 hp = getanswer(buf, ret, name, rtl->rtl_type,
1560                                                     &hpbuf, errp);
1561                                 if (!hp)
1562                                         continue;
1563                                 hp = _hpcopy(&hpbuf, errp);
1564                                 hp0 = _hpmerge(hp0, hp, errp);
1565                         } else
1566                                 *errp = h_errno;
1567                 }
1568                 free(buf);
1569                 return (hp0);
1570         }
1571
1572         /*
1573          * If there are dots in the name already, let's just give it a try
1574          * 'as is'.  The threshold can be set with the "ndots" option.
1575          */
1576         saved_herrno = -1;
1577         if (dots >= _res.ndots) {
1578                 for(rtl = rtl0; rtl != NULL;
1579                     rtl = SLIST_NEXT(rtl, rtl_entry)) {
1580                         ret = res_querydomain(name, NULL, C_IN, rtl->rtl_type,
1581                                               buf->buf, sizeof(buf->buf));
1582                         if (ret > 0 && (size_t)ret < sizeof(buf->buf)) {
1583                                 hpbuf.h_addrtype = (rtl->rtl_type == T_AAAA)
1584                                     ? AF_INET6 : AF_INET;
1585                                 hpbuf.h_length = ADDRLEN(hpbuf.h_addrtype);
1586                                 hp = getanswer(buf, ret, name, rtl->rtl_type,
1587                                                     &hpbuf, errp);
1588                                 if (!hp)
1589                                         continue;
1590                                 hp = _hpcopy(&hpbuf, errp);
1591                                 hp0 = _hpmerge(hp0, hp, errp);
1592                         } else
1593                                 *errp = h_errno;
1594                 }
1595                 if (hp0 != NULL) {
1596                         free(buf);
1597                         return (hp0);
1598                 }
1599                 saved_herrno = *errp;
1600                 tried_as_is++;
1601         }
1602
1603         /*
1604          * We do at least one level of search if
1605          *      - there is no dot and RES_DEFNAME is set, or
1606          *      - there is at least one dot, there is no trailing dot,
1607          *        and RES_DNSRCH is set.
1608          */
1609         if ((!dots && (_res.options & RES_DEFNAMES)) ||
1610             (dots && !trailing_dot && (_res.options & RES_DNSRCH))) {
1611                 int done = 0;
1612
1613                 for (domain = (const char * const *)_res.dnsrch;
1614                      *domain && !done;
1615                      domain++) {
1616
1617                         for(rtl = rtl0; rtl != NULL;
1618                             rtl = SLIST_NEXT(rtl, rtl_entry)) {
1619                                 ret = res_querydomain(name, *domain, C_IN,
1620                                                       rtl->rtl_type,
1621                                                       buf->buf, sizeof(buf->buf));
1622                                 if (ret > 0 && (size_t)ret < sizeof(buf->buf)) {
1623                                         hpbuf.h_addrtype = (rtl->rtl_type == T_AAAA)
1624                                             ? AF_INET6 : AF_INET;
1625                                         hpbuf.h_length = ADDRLEN(hpbuf.h_addrtype);
1626                                         hp = getanswer(buf, ret, name,
1627                                             rtl->rtl_type, &hpbuf, errp);
1628                                         if (!hp)
1629                                                 continue;
1630                                         hp = _hpcopy(&hpbuf, errp);
1631                                         hp0 = _hpmerge(hp0, hp, errp);
1632                                 } else
1633                                         *errp = h_errno;
1634                         }
1635                         if (hp0 != NULL) {
1636                                 free(buf);
1637                                 return (hp0);
1638                         }
1639
1640                         /*
1641                          * If no server present, give up.
1642                          * If name isn't found in this domain,
1643                          * keep trying higher domains in the search list
1644                          * (if that's enabled).
1645                          * On a NO_DATA error, keep trying, otherwise
1646                          * a wildcard entry of another type could keep us
1647                          * from finding this entry higher in the domain.
1648                          * If we get some other error (negative answer or
1649                          * server failure), then stop searching up,
1650                          * but try the input name below in case it's
1651                          * fully-qualified.
1652                          */
1653                         if (errno == ECONNREFUSED) {
1654                                 free(buf);
1655                                 *errp = TRY_AGAIN;
1656                                 return (NULL);
1657                         }
1658
1659                         switch (*errp) {
1660                         case NO_DATA:
1661                                 got_nodata++;
1662                                 /* FALLTHROUGH */
1663                         case HOST_NOT_FOUND:
1664                                 /* keep trying */
1665                                 break;
1666                         case TRY_AGAIN:
1667                                 if (buf->hdr.rcode == SERVFAIL) {
1668                                         /* try next search element, if any */
1669                                         got_servfail++;
1670                                         break;
1671                                 }
1672                                 /* FALLTHROUGH */
1673                         default:
1674                                 /* anything else implies that we're done */
1675                                 done++;
1676                         }
1677
1678                         /* if we got here for some reason other than DNSRCH,
1679                          * we only wanted one iteration of the loop, so stop.
1680                          */
1681                         if (!(_res.options & RES_DNSRCH))
1682                                 done++;
1683                 }
1684         }
1685
1686         /*
1687          * If we have not already tried the name "as is", do that now.
1688          * note that we do this regardless of how many dots were in the
1689          * name or whether it ends with a dot unless NOTLDQUERY is set.
1690          */
1691         if (!tried_as_is && (dots || !(_res.options & RES_NOTLDQUERY))) {
1692                 for(rtl = rtl0; rtl != NULL;
1693                     rtl = SLIST_NEXT(rtl, rtl_entry)) {
1694                         ret = res_querydomain(name, NULL, C_IN, rtl->rtl_type,
1695                                               buf->buf, sizeof(buf->buf));
1696                         if (ret > 0 && (size_t)ret < sizeof(buf->buf)) {
1697                                 hpbuf.h_addrtype = (rtl->rtl_type == T_AAAA)
1698                                     ? AF_INET6 : AF_INET;
1699                                 hpbuf.h_length = ADDRLEN(hpbuf.h_addrtype);
1700                                 hp = getanswer(buf, ret, name, rtl->rtl_type,
1701                                     &hpbuf, errp);
1702                                 if (!hp)
1703                                         continue;
1704                                 hp = _hpcopy(&hpbuf, errp);
1705                                 hp0 = _hpmerge(hp0, hp, errp);
1706                         } else
1707                                 *errp = h_errno;
1708                 }
1709                 if (hp0 != NULL) {
1710                         free(buf);
1711                         return (hp0);
1712                 }
1713         }
1714
1715         free(buf);
1716
1717         /* if we got here, we didn't satisfy the search.
1718          * if we did an initial full query, return that query's h_errno
1719          * (note that we wouldn't be here if that query had succeeded).
1720          * else if we ever got a nodata, send that back as the reason.
1721          * else send back meaningless h_errno, that being the one from
1722          * the last DNSRCH we did.
1723          */
1724         if (saved_herrno != -1)
1725                 *errp = saved_herrno;
1726         else if (got_nodata)
1727                 *errp = NO_DATA;
1728         else if (got_servfail)
1729                 *errp = TRY_AGAIN;
1730         return (NULL);
1731 }
1732
1733 static int
1734 _dns_ghbyname(void *rval, void *cb_data, va_list ap)
1735 {
1736         const char *name;
1737         int af;
1738         int *errp;
1739         struct __res_type_list *rtl, rtl4;
1740 #ifdef INET6
1741         struct __res_type_list rtl6;
1742 #endif
1743
1744         name = va_arg(ap, const char *);
1745         af = va_arg(ap, int);
1746         errp = va_arg(ap, int *);
1747
1748 #ifdef INET6
1749         switch (af) {
1750         case AF_UNSPEC:
1751                 SLIST_NEXT(&rtl4, rtl_entry) = NULL; rtl4.rtl_type = T_A;
1752                 SLIST_NEXT(&rtl6, rtl_entry) = &rtl4; rtl6.rtl_type = T_AAAA;
1753                 rtl = &rtl6;
1754                 break;
1755         case AF_INET6:
1756                 SLIST_NEXT(&rtl6, rtl_entry) = NULL; rtl6.rtl_type = T_AAAA;
1757                 rtl = &rtl6;
1758                 break;
1759         case AF_INET:
1760                 SLIST_NEXT(&rtl4, rtl_entry) = NULL; rtl4.rtl_type = T_A;
1761                 rtl = &rtl4;
1762                 break;
1763         default:
1764                 return(NULL);
1765         }
1766 #else
1767         SLIST_NEXT(&rtl4, rtl_entry) = NULL; rtl4.rtl_type = T_A;
1768         rtl = &rtl4;
1769 #endif
1770         *(struct hostent **)rval = _res_search_multi(name, rtl, errp);
1771         if (*(struct hostent **)rval != NULL)
1772                 return NS_SUCCESS;
1773         else if (*errp == TRY_AGAIN)
1774                 return NS_TRYAGAIN;
1775         else
1776                 return NS_NOTFOUND;
1777 }
1778
1779 static int
1780 _dns_ghbyaddr(void *rval, void *cb_data, va_list ap)
1781 {
1782         const void *addr;
1783         int addrlen;
1784         int af;
1785         int *errp;
1786         int n;
1787         struct hostent *hp;
1788         u_char c;
1789         const u_char *cp;
1790         char *bp;
1791         struct hostent hbuf;
1792         int na;
1793 #ifdef INET6
1794         static const char hex[] = "0123456789abcdef";
1795 #endif
1796         querybuf *buf;
1797         char qbuf[MAXDNAME+1];
1798         char *hlist[2];
1799         const char *tld6[] = { "ip6.arpa", "ip6.int", NULL };
1800         const char *tld4[] = { "in-addr.arpa", NULL };
1801         const char **tld;
1802
1803         addr = va_arg(ap, const void *);
1804         addrlen = va_arg(ap, int);
1805         af = va_arg(ap, int);
1806         errp = va_arg(ap, int *);
1807
1808         *(struct hostent **)rval = NULL;
1809
1810 #ifdef INET6
1811         /* XXX */
1812         if (af == AF_INET6 && IN6_IS_ADDR_LINKLOCAL((const struct in6_addr *)addr))
1813                 return NS_NOTFOUND;
1814 #endif
1815
1816         switch (af) {
1817 #ifdef INET6
1818         case AF_INET6:
1819                 tld = tld6;
1820                 break;
1821 #endif
1822         case AF_INET:
1823                 tld = tld4;
1824                 break;
1825         default:
1826                 return NULL;
1827         }
1828
1829         if ((_res.options & RES_INIT) == 0) {
1830                 if (res_init() < 0) {
1831                         *errp = h_errno;
1832                         return NS_UNAVAIL;
1833                 }
1834         }
1835         memset(&hbuf, 0, sizeof(hbuf));
1836         hbuf.h_name = NULL;
1837         hbuf.h_addrtype = af;
1838         hbuf.h_length = addrlen;
1839         na = 0;
1840
1841         buf = malloc(sizeof(*buf));
1842         if (buf == NULL) {
1843                 *errp = NETDB_INTERNAL;
1844                 return NULL;
1845         }
1846         for (/* nothing */; *tld; tld++) {
1847                 /*
1848                  * XXX assumes that MAXDNAME is big enough - error checks
1849                  * has been made by callers
1850                  */
1851                 n = 0;
1852                 bp = qbuf;
1853                 cp = (const uint8_t *)addr+addrlen-1;
1854                 switch (af) {
1855 #ifdef INET6
1856                 case AF_INET6:
1857                         for (; n < addrlen; n++, cp--) {
1858                                 c = *cp;
1859                                 *bp++ = hex[c & 0xf];
1860                                 *bp++ = '.';
1861                                 *bp++ = hex[c >> 4];
1862                                 *bp++ = '.';
1863                         }
1864                         strcpy(bp, *tld);
1865                         break;
1866 #endif
1867                 case AF_INET:
1868                         for (; n < addrlen; n++, cp--) {
1869                                 c = *cp;
1870                                 if (c >= 100)
1871                                         *bp++ = '0' + c / 100;
1872                                 if (c >= 10)
1873                                         *bp++ = '0' + (c % 100) / 10;
1874                                 *bp++ = '0' + c % 10;
1875                                 *bp++ = '.';
1876                         }
1877                         strcpy(bp, *tld);
1878                         break;
1879                 }
1880
1881                 n = res_query(qbuf, C_IN, T_PTR, buf->buf, sizeof buf->buf);
1882                 if (n < 0) {
1883                         *errp = h_errno;
1884                         continue;
1885                 } else if ((size_t)n > sizeof(buf->buf)) {
1886                         *errp = NETDB_INTERNAL;
1887 #if 0
1888                         errno = ERANGE; /* XXX is it OK to set errno here? */
1889 #endif
1890                         continue;
1891                 }
1892                 hp = getanswer(buf, n, qbuf, T_PTR, &hbuf, errp);
1893                 if (!hp)
1894                         continue;
1895                 free(buf);
1896                 hbuf.h_addrtype = af;
1897                 hbuf.h_length = addrlen;
1898                 hbuf.h_addr_list = hlist;
1899                 hlist[0] = addr;
1900                 hlist[1] = NULL;
1901                 return _hpcopy(&hbuf, errp);
1902         }
1903         free(buf);
1904         return NULL;
1905 }
1906
1907 #ifdef ICMPNL
1908
1909 /*
1910  * experimental:
1911  *      draft-ietf-ipngwg-icmp-namelookups-02.txt
1912  *      ifindex is assumed to be encoded in addr.
1913  */
1914 #include <sys/uio.h>
1915 #include <netinet/ip6.h>
1916 #include <netinet/icmp6.h>
1917
1918 struct _icmp_host_cache {
1919         struct _icmp_host_cache *hc_next;
1920         int hc_ifindex;
1921         struct in6_addr hc_addr;
1922         char *hc_name;
1923 };
1924
1925 static char *
1926 _icmp_fqdn_query(const struct in6_addr *addr, int ifindex)
1927 {
1928         int s;
1929         struct icmp6_filter filter;
1930         struct msghdr msg;
1931         struct cmsghdr *cmsg;
1932         struct in6_pktinfo *pkt;
1933         char cbuf[256];
1934         char buf[1024];
1935         int cc;
1936         struct icmp6_fqdn_query *fq;
1937         struct icmp6_fqdn_reply *fr;
1938         struct _icmp_host_cache *hc;
1939         struct sockaddr_in6 sin6;
1940         struct iovec iov;
1941         fd_set s_fds, fds;
1942         struct timeval tout;
1943         int len;
1944         char *name;
1945         static int pid;
1946         static struct _icmp_host_cache *hc_head;
1947
1948         for (hc = hc_head; hc; hc = hc->hc_next) {
1949                 if (hc->hc_ifindex == ifindex
1950                 &&  IN6_ARE_ADDR_EQUAL(&hc->hc_addr, addr))
1951                         return hc->hc_name;
1952         }
1953
1954         if (pid == 0)
1955                 pid = getpid();
1956
1957         ICMP6_FILTER_SETBLOCKALL(&filter);
1958         ICMP6_FILTER_SETPASS(ICMP6_FQDN_REPLY, &filter);
1959
1960         FD_ZERO(&s_fds);
1961         tout.tv_sec = 0;
1962         tout.tv_usec = 200000;  /*XXX: 200ms*/
1963
1964         fq = (struct icmp6_fqdn_query *)buf;
1965         fq->icmp6_fqdn_type = ICMP6_FQDN_QUERY;
1966         fq->icmp6_fqdn_code = 0;
1967         fq->icmp6_fqdn_cksum = 0;
1968         fq->icmp6_fqdn_id = (u_short)pid;
1969         fq->icmp6_fqdn_unused = 0;
1970         fq->icmp6_fqdn_cookie[0] = 0;
1971         fq->icmp6_fqdn_cookie[1] = 0;
1972
1973         memset(&sin6, 0, sizeof(sin6));
1974         sin6.sin6_family = AF_INET6;
1975         sin6.sin6_addr = *addr;
1976
1977         memset(&msg, 0, sizeof(msg));
1978         msg.msg_name = (caddr_t)&sin6;
1979         msg.msg_namelen = sizeof(sin6);
1980         msg.msg_iov = &iov;
1981         msg.msg_iovlen = 1;
1982         msg.msg_control = NULL;
1983         msg.msg_controllen = 0;
1984         iov.iov_base = (caddr_t)buf;
1985         iov.iov_len = sizeof(struct icmp6_fqdn_query);
1986
1987         if (ifindex) {
1988                 msg.msg_control = cbuf;
1989                 msg.msg_controllen = sizeof(cbuf);
1990                 cmsg = CMSG_FIRSTHDR(&msg);
1991                 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
1992                 cmsg->cmsg_level = IPPROTO_IPV6;
1993                 cmsg->cmsg_type = IPV6_PKTINFO;
1994                 pkt = (struct in6_pktinfo *)&cmsg[1];
1995                 memset(&pkt->ipi6_addr, 0, sizeof(struct in6_addr));
1996                 pkt->ipi6_ifindex = ifindex;
1997                 cmsg = CMSG_NXTHDR(&msg, cmsg);
1998                 msg.msg_controllen = (char *)cmsg - cbuf;
1999         }
2000
2001         if ((s = _socket(PF_INET6, SOCK_RAW, IPPROTO_ICMPV6)) < 0)
2002                 return NULL;
2003         _setsockopt(s, IPPROTO_ICMPV6, ICMP6_FILTER,
2004                     (char *)&filter, sizeof(filter));
2005         cc = _sendmsg(s, &msg, 0);
2006         if (cc < 0) {
2007                 _close(s);
2008                 return NULL;
2009         }
2010         FD_SET(s, &s_fds);
2011         for (;;) {
2012                 fds = s_fds;
2013                 if (select(s + 1, &fds, NULL, NULL, &tout) <= 0) {
2014                         _close(s);
2015                         return NULL;
2016                 }
2017                 len = sizeof(sin6);
2018                 cc = _recvfrom(s, buf, sizeof(buf), 0,
2019                               (struct sockaddr *)&sin6, &len);
2020                 if (cc <= 0) {
2021                         _close(s);
2022                         return NULL;
2023                 }
2024                 if (cc < sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr))
2025                         continue;
2026                 if (!IN6_ARE_ADDR_EQUAL(addr, &sin6.sin6_addr))
2027                         continue;
2028                 fr = (struct icmp6_fqdn_reply *)(buf + sizeof(struct ip6_hdr));
2029                 if (fr->icmp6_fqdn_type == ICMP6_FQDN_REPLY)
2030                         break;
2031         }
2032         _close(s);
2033         if (fr->icmp6_fqdn_cookie[1] != 0) {
2034                 /* rfc1788 type */
2035                 name = buf + sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr) + 4;
2036                 len = (buf + cc) - name;
2037         } else {
2038                 len = fr->icmp6_fqdn_namelen;
2039                 name = fr->icmp6_fqdn_name;
2040         }
2041         if (len <= 0)
2042                 return NULL;
2043         name[len] = 0;
2044
2045         if ((hc = (struct _icmp_host_cache *)malloc(sizeof(*hc))) == NULL)
2046                 return NULL;
2047         /* XXX: limit number of cached entries */
2048         hc->hc_ifindex = ifindex;
2049         hc->hc_addr = *addr;
2050         hc->hc_name = strdup(name);
2051         hc->hc_next = hc_head;
2052         hc_head = hc;
2053         return hc->hc_name;
2054 }
2055
2056 static struct hostent *
2057 _icmp_ghbyaddr(const void *addr, int addrlen, int af, int *errp)
2058 {
2059         char *hname;
2060         int ifindex;
2061         struct in6_addr addr6;
2062
2063         if (af != AF_INET6) {
2064                 /*
2065                  * Note: rfc1788 defines Who Are You for IPv4,
2066                  * but no one implements it.
2067                  */
2068                 return NULL;
2069         }
2070
2071         memcpy(&addr6, addr, addrlen);
2072         ifindex = (addr6.s6_addr[2] << 8) | addr6.s6_addr[3];
2073         addr6.s6_addr[2] = addr6.s6_addr[3] = 0;
2074
2075         if (!IN6_IS_ADDR_LINKLOCAL(&addr6))
2076                 return NULL;    /*XXX*/
2077
2078         if ((hname = _icmp_fqdn_query(&addr6, ifindex)) == NULL)
2079                 return NULL;
2080         return _hpaddr(af, hname, &addr6, errp);
2081 }
2082 #endif /* ICMPNL */