]> CyberLeo.Net >> Repos - FreeBSD/releng/9.3.git/blob - lib/libc/net/getaddrinfo.c
MFS r267876 (MFC r267616):
[FreeBSD/releng/9.3.git] / lib / libc / net / getaddrinfo.c
1 /*      $KAME: getaddrinfo.c,v 1.15 2000/07/09 04:37:24 itojun Exp $    */
2
3 /*
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32 /*
33  * "#ifdef FAITH" part is local hack for supporting IPv4-v6 translator.
34  *
35  * Issues to be discussed:
36  * - Return values.  There are nonstandard return values defined and used
37  *   in the source code.  This is because RFC2553 is silent about which error
38  *   code must be returned for which situation.
39  * - freeaddrinfo(NULL).  RFC2553 is silent about it.  XNET 5.2 says it is
40  *   invalid.  current code - SEGV on freeaddrinfo(NULL)
41  *
42  * Note:
43  * - The code filters out AFs that are not supported by the kernel,
44  *   when globbing NULL hostname (to loopback, or wildcard).  Is it the right
45  *   thing to do?  What is the relationship with post-RFC2553 AI_ADDRCONFIG
46  *   in ai_flags?
47  * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
48  *   (1) what should we do against numeric hostname (2) what should we do
49  *   against NULL hostname (3) what is AI_ADDRCONFIG itself.  AF not ready?
50  *   non-loopback address configured?  global address configured?
51  *
52  * OS specific notes for freebsd4:
53  * - FreeBSD supported $GAI.  The code does not.
54  */
55
56 #include <sys/cdefs.h>
57 __FBSDID("$FreeBSD$");
58
59 #include "namespace.h"
60 #include <sys/types.h>
61 #include <sys/param.h>
62 #include <sys/socket.h>
63 #include <net/if.h>
64 #include <netinet/in.h>
65 #include <net/if_types.h>
66 #include <ifaddrs.h>
67 #include <sys/queue.h>
68 #ifdef INET6
69 #include <net/if_var.h>
70 #include <sys/sysctl.h>
71 #include <sys/ioctl.h>
72 #include <netinet6/in6_var.h>
73 #include <netinet6/nd6.h>
74 #endif
75 #include <arpa/inet.h>
76 #include <arpa/nameser.h>
77 #include <rpc/rpc.h>
78 #include <rpcsvc/yp_prot.h>
79 #include <rpcsvc/ypclnt.h>
80 #include <netdb.h>
81 #include <resolv.h>
82 #include <string.h>
83 #include <stdlib.h>
84 #include <stddef.h>
85 #include <ctype.h>
86 #include <unistd.h>
87 #include <stdio.h>
88 #include <errno.h>
89
90 #include "res_config.h"
91
92 #ifdef DEBUG
93 #include <syslog.h>
94 #endif
95
96 #include <stdarg.h>
97 #include <nsswitch.h>
98 #include "un-namespace.h"
99 #include "libc_private.h"
100 #ifdef NS_CACHING
101 #include "nscache.h"
102 #endif
103
104 #if defined(__KAME__) && defined(INET6)
105 # define FAITH
106 #endif
107
108 #define ANY 0
109 #define YES 1
110 #define NO  0
111
112 static const char in_addrany[] = { 0, 0, 0, 0 };
113 static const char in_loopback[] = { 127, 0, 0, 1 };
114 #ifdef INET6
115 static const char in6_addrany[] = {
116         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
117 };
118 static const char in6_loopback[] = {
119         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
120 };
121 #endif
122
123 struct policyqueue {
124         TAILQ_ENTRY(policyqueue) pc_entry;
125 #ifdef INET6
126         struct in6_addrpolicy pc_policy;
127 #endif
128 };
129 TAILQ_HEAD(policyhead, policyqueue);
130
131 static const struct afd {
132         int a_af;
133         int a_addrlen;
134         socklen_t a_socklen;
135         int a_off;
136         const char *a_addrany;
137         const char *a_loopback;
138         int a_scoped;
139 } afdl [] = {
140 #ifdef INET6
141 #define N_INET6 0
142         {PF_INET6, sizeof(struct in6_addr),
143          sizeof(struct sockaddr_in6),
144          offsetof(struct sockaddr_in6, sin6_addr),
145          in6_addrany, in6_loopback, 1},
146 #define N_INET 1
147 #else
148 #define N_INET 0
149 #endif
150         {PF_INET, sizeof(struct in_addr),
151          sizeof(struct sockaddr_in),
152          offsetof(struct sockaddr_in, sin_addr),
153          in_addrany, in_loopback, 0},
154         {0, 0, 0, 0, NULL, NULL, 0},
155 };
156
157 struct explore {
158         int e_af;
159         int e_socktype;
160         int e_protocol;
161         const char *e_protostr;
162         int e_wild;
163 #define WILD_AF(ex)             ((ex)->e_wild & 0x01)
164 #define WILD_SOCKTYPE(ex)       ((ex)->e_wild & 0x02)
165 #define WILD_PROTOCOL(ex)       ((ex)->e_wild & 0x04)
166 };
167
168 static const struct explore explore[] = {
169 #if 0
170         { PF_LOCAL, ANY, ANY, NULL, 0x01 },
171 #endif
172 #ifdef INET6
173         { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
174         { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
175         { PF_INET6, SOCK_STREAM, IPPROTO_SCTP, "sctp", 0x03 },
176         { PF_INET6, SOCK_SEQPACKET, IPPROTO_SCTP, "sctp", 0x07 },
177         { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
178 #endif
179         { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
180         { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
181         { PF_INET, SOCK_STREAM, IPPROTO_SCTP, "sctp", 0x03 },
182         { PF_INET, SOCK_SEQPACKET, IPPROTO_SCTP, "sctp", 0x07 },
183         { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
184         { -1, 0, 0, NULL, 0 },
185 };
186
187 #ifdef INET6
188 #define PTON_MAX        16
189 #else
190 #define PTON_MAX        4
191 #endif
192
193 #define AIO_SRCFLAG_DEPRECATED  0x1
194
195 struct ai_order {
196         union {
197                 struct sockaddr_storage aiou_ss;
198                 struct sockaddr aiou_sa;
199         } aio_src_un;
200 #define aio_srcsa aio_src_un.aiou_sa
201         u_int32_t aio_srcflag;
202         int aio_srcscope;
203         int aio_dstscope;
204         struct policyqueue *aio_srcpolicy;
205         struct policyqueue *aio_dstpolicy;
206         struct addrinfo *aio_ai;
207         int aio_matchlen;
208 };
209
210 static const ns_src default_dns_files[] = {
211         { NSSRC_FILES,  NS_SUCCESS },
212         { NSSRC_DNS,    NS_SUCCESS },
213         { 0 }
214 };
215
216 struct res_target {
217         struct res_target *next;
218         const char *name;       /* domain name */
219         int qclass, qtype;      /* class and type of query */
220         u_char *answer;         /* buffer to put answer */
221         int anslen;             /* size of answer buffer */
222         int n;                  /* result length */
223 };
224
225 #define MAXPACKET       (64*1024)
226
227 typedef union {
228         HEADER hdr;
229         u_char buf[MAXPACKET];
230 } querybuf;
231
232 static int str2number(const char *, int *);
233 static int explore_copy(const struct addrinfo *, const struct addrinfo *,
234         struct addrinfo **);
235 static int explore_null(const struct addrinfo *,
236         const char *, struct addrinfo **);
237 static int explore_numeric(const struct addrinfo *, const char *,
238         const char *, struct addrinfo **, const char *);
239 static int explore_numeric_scope(const struct addrinfo *, const char *,
240         const char *, struct addrinfo **);
241 static int get_canonname(const struct addrinfo *,
242         struct addrinfo *, const char *);
243 static struct addrinfo *get_ai(const struct addrinfo *,
244         const struct afd *, const char *);
245 static struct addrinfo *copy_ai(const struct addrinfo *);
246 static int get_portmatch(const struct addrinfo *, const char *);
247 static int get_port(struct addrinfo *, const char *, int);
248 static const struct afd *find_afd(int);
249 static int addrconfig(struct addrinfo *);
250 #ifdef INET6
251 static int is_ifdisabled(char *);
252 #endif
253 static void set_source(struct ai_order *, struct policyhead *);
254 static int comp_dst(const void *, const void *);
255 #ifdef INET6
256 static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
257 #endif
258 static int gai_addr2scopetype(struct sockaddr *);
259
260 static int explore_fqdn(const struct addrinfo *, const char *,
261         const char *, struct addrinfo **);
262
263 static int reorder(struct addrinfo *);
264 static int get_addrselectpolicy(struct policyhead *);
265 static void free_addrselectpolicy(struct policyhead *);
266 static struct policyqueue *match_addrselectpolicy(struct sockaddr *,
267         struct policyhead *);
268 static int matchlen(struct sockaddr *, struct sockaddr *);
269
270 static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
271         const struct addrinfo *, res_state);
272 #if defined(RESOLVSORT)
273 static int addr4sort(struct addrinfo *, res_state);
274 #endif
275 static int _dns_getaddrinfo(void *, void *, va_list);
276 static void _sethtent(FILE **);
277 static void _endhtent(FILE **);
278 static struct addrinfo *_gethtent(FILE **, const char *,
279         const struct addrinfo *);
280 static int _files_getaddrinfo(void *, void *, va_list);
281 #ifdef YP
282 static struct addrinfo *_yphostent(char *, const struct addrinfo *);
283 static int _yp_getaddrinfo(void *, void *, va_list);
284 #endif
285 #ifdef NS_CACHING
286 static int addrinfo_id_func(char *, size_t *, va_list, void *);
287 static int addrinfo_marshal_func(char *, size_t *, void *, va_list, void *);
288 static int addrinfo_unmarshal_func(char *, size_t, void *, va_list, void *);
289 #endif
290
291 static int res_queryN(const char *, struct res_target *, res_state);
292 static int res_searchN(const char *, struct res_target *, res_state);
293 static int res_querydomainN(const char *, const char *,
294         struct res_target *, res_state);
295
296 /* XXX macros that make external reference is BAD. */
297
298 #define GET_AI(ai, afd, addr) \
299 do { \
300         /* external reference: pai, error, and label free */ \
301         (ai) = get_ai(pai, (afd), (addr)); \
302         if ((ai) == NULL) { \
303                 error = EAI_MEMORY; \
304                 goto free; \
305         } \
306 } while (/*CONSTCOND*/0)
307
308 #define GET_PORT(ai, serv) \
309 do { \
310         /* external reference: error and label free */ \
311         error = get_port((ai), (serv), 0); \
312         if (error != 0) \
313                 goto free; \
314 } while (/*CONSTCOND*/0)
315
316 #define GET_CANONNAME(ai, str) \
317 do { \
318         /* external reference: pai, error and label free */ \
319         error = get_canonname(pai, (ai), (str)); \
320         if (error != 0) \
321                 goto free; \
322 } while (/*CONSTCOND*/0)
323
324 #define ERR(err) \
325 do { \
326         /* external reference: error, and label bad */ \
327         error = (err); \
328         goto bad; \
329         /*NOTREACHED*/ \
330 } while (/*CONSTCOND*/0)
331
332 #define MATCH_FAMILY(x, y, w) \
333         ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
334 #define MATCH(x, y, w) \
335         ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
336
337 void
338 freeaddrinfo(struct addrinfo *ai)
339 {
340         struct addrinfo *next;
341
342         do {
343                 next = ai->ai_next;
344                 if (ai->ai_canonname)
345                         free(ai->ai_canonname);
346                 /* no need to free(ai->ai_addr) */
347                 free(ai);
348                 ai = next;
349         } while (ai);
350 }
351
352 static int
353 str2number(const char *p, int *portp)
354 {
355         char *ep;
356         unsigned long v;
357
358         if (*p == '\0')
359                 return -1;
360         ep = NULL;
361         errno = 0;
362         v = strtoul(p, &ep, 10);
363         if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX) {
364                 *portp = v;
365                 return 0;
366         } else
367                 return -1;
368 }
369
370 int
371 getaddrinfo(const char *hostname, const char *servname,
372     const struct addrinfo *hints, struct addrinfo **res)
373 {
374         struct addrinfo sentinel;
375         struct addrinfo *cur;
376         int error = 0;
377         struct addrinfo ai, ai0, *afai;
378         struct addrinfo *pai;
379         const struct afd *afd;
380         const struct explore *ex;
381         struct addrinfo *afailist[sizeof(afdl)/sizeof(afdl[0])];
382         struct addrinfo *afai_unspec;
383         int found;
384         int numeric = 0;
385
386         /* ensure we return NULL on errors */
387         *res = NULL;
388
389         memset(&ai, 0, sizeof(ai));
390
391         memset(afailist, 0, sizeof(afailist));
392         afai_unspec = NULL;
393
394         memset(&sentinel, 0, sizeof(sentinel));
395         cur = &sentinel;
396         pai = &ai;
397         pai->ai_flags = 0;
398         pai->ai_family = PF_UNSPEC;
399         pai->ai_socktype = ANY;
400         pai->ai_protocol = ANY;
401         pai->ai_addrlen = 0;
402         pai->ai_canonname = NULL;
403         pai->ai_addr = NULL;
404         pai->ai_next = NULL;
405
406         if (hostname == NULL && servname == NULL)
407                 return EAI_NONAME;
408         if (hints) {
409                 /* error check for hints */
410                 if (hints->ai_addrlen || hints->ai_canonname ||
411                     hints->ai_addr || hints->ai_next)
412                         ERR(EAI_BADHINTS); /* xxx */
413                 if (hints->ai_flags & ~AI_MASK)
414                         ERR(EAI_BADFLAGS);
415                 switch (hints->ai_family) {
416                 case PF_UNSPEC:
417                 case PF_INET:
418 #ifdef INET6
419                 case PF_INET6:
420 #endif
421                         break;
422                 default:
423                         ERR(EAI_FAMILY);
424                 }
425                 memcpy(pai, hints, sizeof(*pai));
426
427                 /*
428                  * if both socktype/protocol are specified, check if they
429                  * are meaningful combination.
430                  */
431                 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
432                         for (ex = explore; ex->e_af >= 0; ex++) {
433                                 if (!MATCH_FAMILY(pai->ai_family, ex->e_af,
434                                     WILD_AF(ex)))
435                                         continue;
436                                 if (!MATCH(pai->ai_socktype, ex->e_socktype,
437                                     WILD_SOCKTYPE(ex)))
438                                         continue;
439                                 if (!MATCH(pai->ai_protocol, ex->e_protocol,
440                                     WILD_PROTOCOL(ex)))
441                                         continue;
442
443                                 /* matched */
444                                 break;
445                         }
446
447                         if (ex->e_af < 0)
448                                 ERR(EAI_BADHINTS);
449                 }
450         }
451
452         /*
453          * check for special cases.  (1) numeric servname is disallowed if
454          * socktype/protocol are left unspecified. (2) servname is disallowed
455          * for raw and other inet{,6} sockets.
456          */
457         if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
458 #ifdef PF_INET6
459             || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
460 #endif
461             ) {
462                 ai0 = *pai;     /* backup *pai */
463
464                 if (pai->ai_family == PF_UNSPEC) {
465 #ifdef PF_INET6
466                         pai->ai_family = PF_INET6;
467 #else
468                         pai->ai_family = PF_INET;
469 #endif
470                 }
471                 error = get_portmatch(pai, servname);
472                 if (error)
473                         goto bad;
474
475                 *pai = ai0;
476         }
477
478         ai0 = *pai;
479
480         /*
481          * NULL hostname, or numeric hostname.
482          * If numeric representation of AF1 can be interpreted as FQDN
483          * representation of AF2, we need to think again about the code below.
484          */
485         found = 0;
486         for (afd = afdl; afd->a_af; afd++) {
487                 *pai = ai0;
488
489                 if (!MATCH_FAMILY(pai->ai_family, afd->a_af, 1))
490                         continue;
491
492                 if (pai->ai_family == PF_UNSPEC)
493                         pai->ai_family = afd->a_af;
494
495                 if (hostname == NULL) {
496                         error = explore_null(pai, servname,
497                             &afailist[afd - afdl]);
498
499                         /*
500                          * Errors from explore_null should be unexpected and
501                          * be caught to avoid returning an incomplete result.
502                          */
503                         if (error != 0)
504                                 goto bad;
505                 } else {
506                         error = explore_numeric_scope(pai, hostname, servname,
507                             &afailist[afd - afdl]);
508
509                         /*
510                          * explore_numeric_scope returns an error for address
511                          * families that do not match that of hostname.
512                          * Thus we should not catch the error at this moment. 
513                          */
514                 }
515
516                 if (!error && afailist[afd - afdl])
517                         found++;
518         }
519         if (found) {
520                 numeric = 1;
521                 goto globcopy;
522         }
523
524         if (hostname == NULL)
525                 ERR(EAI_NONAME);        /* used to be EAI_NODATA */
526         if (pai->ai_flags & AI_NUMERICHOST)
527                 ERR(EAI_NONAME);
528
529         if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(&ai0))
530                 ERR(EAI_FAIL);
531
532         /*
533          * hostname as alphabetical name.
534          */
535         *pai = ai0;
536         error = explore_fqdn(pai, hostname, servname, &afai_unspec);
537
538 globcopy:
539         for (ex = explore; ex->e_af >= 0; ex++) {
540                 *pai = ai0;
541
542                 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
543                         continue;
544                 if (!MATCH(pai->ai_socktype, ex->e_socktype,
545                     WILD_SOCKTYPE(ex)))
546                         continue;
547                 if (!MATCH(pai->ai_protocol, ex->e_protocol,
548                     WILD_PROTOCOL(ex)))
549                         continue;
550
551                 if (pai->ai_family == PF_UNSPEC)
552                         pai->ai_family = ex->e_af;
553                 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
554                         pai->ai_socktype = ex->e_socktype;
555                 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
556                         pai->ai_protocol = ex->e_protocol;
557
558                 /*
559                  * if the servname does not match socktype/protocol, ignore it.
560                  */
561                 if (get_portmatch(pai, servname) != 0)
562                         continue;
563
564                 if (afai_unspec)
565                         afai = afai_unspec;
566                 else {
567                         if ((afd = find_afd(pai->ai_family)) == NULL)
568                                 continue;
569                         /* XXX assumes that afd points inside afdl[] */
570                         afai = afailist[afd - afdl];
571                 }
572                 if (!afai)
573                         continue;
574
575                 error = explore_copy(pai, afai, &cur->ai_next);
576                 if (error != 0)
577                         goto bad;
578
579                 while (cur && cur->ai_next)
580                         cur = cur->ai_next;
581         }
582
583         /*
584          * ensure we return either:
585          * - error == 0, non-NULL *res
586          * - error != 0, NULL *res
587          */
588         if (error == 0) {
589                 if (sentinel.ai_next) {
590                         /*
591                          * If the returned entry is for an active connection,
592                          * and the given name is not numeric, reorder the
593                          * list, so that the application would try the list
594                          * in the most efficient order.  Since the head entry
595                          * of the original list may contain ai_canonname and
596                          * that entry may be moved elsewhere in the new list,
597                          * we keep the pointer and will  restore it in the new
598                          * head entry.  (Note that RFC3493 requires the head
599                          * entry store it when requested by the caller).
600                          */
601                         if (hints == NULL || !(hints->ai_flags & AI_PASSIVE)) {
602                                 if (!numeric) {
603                                         char *canonname;
604
605                                         canonname =
606                                             sentinel.ai_next->ai_canonname;
607                                         sentinel.ai_next->ai_canonname = NULL;
608                                         (void)reorder(&sentinel);
609                                         if (sentinel.ai_next->ai_canonname ==
610                                             NULL) {
611                                                 sentinel.ai_next->ai_canonname
612                                                     = canonname;
613                                         } else if (canonname != NULL)
614                                                 free(canonname);
615                                 }
616                         }
617                         *res = sentinel.ai_next;
618                 } else
619                         error = EAI_FAIL;
620         }
621
622 bad:
623         if (afai_unspec)
624                 freeaddrinfo(afai_unspec);
625         for (afd = afdl; afd->a_af; afd++) {
626                 if (afailist[afd - afdl])
627                         freeaddrinfo(afailist[afd - afdl]);
628         }
629         if (!*res)
630                 if (sentinel.ai_next)
631                         freeaddrinfo(sentinel.ai_next);
632
633         return (error);
634 }
635
636 static int
637 reorder(struct addrinfo *sentinel)
638 {
639         struct addrinfo *ai, **aip;
640         struct ai_order *aio;
641         int i, n;
642         struct policyhead policyhead;
643
644         /* count the number of addrinfo elements for sorting. */
645         for (n = 0, ai = sentinel->ai_next; ai != NULL; ai = ai->ai_next, n++)
646                 ;
647
648         /*
649          * If the number is small enough, we can skip the reordering process.
650          */
651         if (n <= 1)
652                 return(n);
653
654         /* allocate a temporary array for sort and initialization of it. */
655         if ((aio = malloc(sizeof(*aio) * n)) == NULL)
656                 return(n);      /* give up reordering */
657         memset(aio, 0, sizeof(*aio) * n);
658
659         /* retrieve address selection policy from the kernel */
660         TAILQ_INIT(&policyhead);
661         if (!get_addrselectpolicy(&policyhead)) {
662                 /* no policy is installed into kernel, we don't sort. */
663                 free(aio);
664                 return (n);
665         }
666
667         for (i = 0, ai = sentinel->ai_next; i < n; ai = ai->ai_next, i++) {
668                 aio[i].aio_ai = ai;
669                 aio[i].aio_dstscope = gai_addr2scopetype(ai->ai_addr);
670                 aio[i].aio_dstpolicy = match_addrselectpolicy(ai->ai_addr,
671                                                               &policyhead);
672                 set_source(&aio[i], &policyhead);
673         }
674
675         /* perform sorting. */
676         qsort(aio, n, sizeof(*aio), comp_dst);
677
678         /* reorder the addrinfo chain. */
679         for (i = 0, aip = &sentinel->ai_next; i < n; i++) {
680                 *aip = aio[i].aio_ai;
681                 aip = &aio[i].aio_ai->ai_next;
682         }
683         *aip = NULL;
684
685         /* cleanup and return */
686         free(aio);
687         free_addrselectpolicy(&policyhead);
688         return(n);
689 }
690
691 static int
692 get_addrselectpolicy(struct policyhead *head)
693 {
694 #ifdef INET6
695         int mib[] = { CTL_NET, PF_INET6, IPPROTO_IPV6, IPV6CTL_ADDRCTLPOLICY };
696         size_t l;
697         char *buf;
698         struct in6_addrpolicy *pol, *ep;
699
700         if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), NULL, &l, NULL, 0) < 0)
701                 return (0);
702         if (l == 0)
703                 return (0);
704         if ((buf = malloc(l)) == NULL)
705                 return (0);
706         if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), buf, &l, NULL, 0) < 0) {
707                 free(buf);
708                 return (0);
709         }
710
711         ep = (struct in6_addrpolicy *)(buf + l);
712         for (pol = (struct in6_addrpolicy *)buf; pol + 1 <= ep; pol++) {
713                 struct policyqueue *new;
714
715                 if ((new = malloc(sizeof(*new))) == NULL) {
716                         free_addrselectpolicy(head); /* make the list empty */
717                         break;
718                 }
719                 new->pc_policy = *pol;
720                 TAILQ_INSERT_TAIL(head, new, pc_entry);
721         }
722
723         free(buf);
724         return (1);
725 #else
726         return (0);
727 #endif
728 }
729
730 static void
731 free_addrselectpolicy(struct policyhead *head)
732 {
733         struct policyqueue *ent, *nent;
734
735         for (ent = TAILQ_FIRST(head); ent; ent = nent) {
736                 nent = TAILQ_NEXT(ent, pc_entry);
737                 TAILQ_REMOVE(head, ent, pc_entry);
738                 free(ent);
739         }
740 }
741
742 static struct policyqueue *
743 match_addrselectpolicy(struct sockaddr *addr, struct policyhead *head)
744 {
745 #ifdef INET6
746         struct policyqueue *ent, *bestent = NULL;
747         struct in6_addrpolicy *pol;
748         int matchlen, bestmatchlen = -1;
749         u_char *mp, *ep, *k, *p, m;
750         struct sockaddr_in6 key;
751
752         switch(addr->sa_family) {
753         case AF_INET6:
754                 key = *(struct sockaddr_in6 *)addr;
755                 break;
756         case AF_INET:
757                 /* convert the address into IPv4-mapped IPv6 address. */
758                 memset(&key, 0, sizeof(key));
759                 key.sin6_family = AF_INET6;
760                 key.sin6_len = sizeof(key);
761                 key.sin6_addr.s6_addr[10] = 0xff;
762                 key.sin6_addr.s6_addr[11] = 0xff;
763                 memcpy(&key.sin6_addr.s6_addr[12],
764                        &((struct sockaddr_in *)addr)->sin_addr, 4);
765                 break;
766         default:
767                 return(NULL);
768         }
769
770         for (ent = TAILQ_FIRST(head); ent; ent = TAILQ_NEXT(ent, pc_entry)) {
771                 pol = &ent->pc_policy;
772                 matchlen = 0;
773
774                 mp = (u_char *)&pol->addrmask.sin6_addr;
775                 ep = mp + 16;   /* XXX: scope field? */
776                 k = (u_char *)&key.sin6_addr;
777                 p = (u_char *)&pol->addr.sin6_addr;
778                 for (; mp < ep && *mp; mp++, k++, p++) {
779                         m = *mp;
780                         if ((*k & m) != *p)
781                                 goto next; /* not match */
782                         if (m == 0xff) /* short cut for a typical case */
783                                 matchlen += 8;
784                         else {
785                                 while (m >= 0x80) {
786                                         matchlen++;
787                                         m <<= 1;
788                                 }
789                         }
790                 }
791
792                 /* matched.  check if this is better than the current best. */
793                 if (matchlen > bestmatchlen) {
794                         bestent = ent;
795                         bestmatchlen = matchlen;
796                 }
797
798           next:
799                 continue;
800         }
801
802         return(bestent);
803 #else
804         return(NULL);
805 #endif
806
807 }
808
809 static void
810 set_source(struct ai_order *aio, struct policyhead *ph)
811 {
812         struct addrinfo ai = *aio->aio_ai;
813         struct sockaddr_storage ss;
814         socklen_t srclen;
815         int s;
816
817         /* set unspec ("no source is available"), just in case */
818         aio->aio_srcsa.sa_family = AF_UNSPEC;
819         aio->aio_srcscope = -1;
820
821         switch(ai.ai_family) {
822         case AF_INET:
823 #ifdef INET6
824         case AF_INET6:
825 #endif
826                 break;
827         default:                /* ignore unsupported AFs explicitly */
828                 return;
829         }
830
831         /* XXX: make a dummy addrinfo to call connect() */
832         ai.ai_socktype = SOCK_DGRAM;
833         ai.ai_protocol = IPPROTO_UDP; /* is UDP too specific? */
834         ai.ai_next = NULL;
835         memset(&ss, 0, sizeof(ss));
836         memcpy(&ss, ai.ai_addr, ai.ai_addrlen);
837         ai.ai_addr = (struct sockaddr *)&ss;
838         get_port(&ai, "1", 0);
839
840         /* open a socket to get the source address for the given dst */
841         if ((s = _socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)) < 0)
842                 return;         /* give up */
843         if (_connect(s, ai.ai_addr, ai.ai_addrlen) < 0)
844                 goto cleanup;
845         srclen = ai.ai_addrlen;
846         if (_getsockname(s, &aio->aio_srcsa, &srclen) < 0) {
847                 aio->aio_srcsa.sa_family = AF_UNSPEC;
848                 goto cleanup;
849         }
850         aio->aio_srcscope = gai_addr2scopetype(&aio->aio_srcsa);
851         aio->aio_srcpolicy = match_addrselectpolicy(&aio->aio_srcsa, ph);
852         aio->aio_matchlen = matchlen(&aio->aio_srcsa, aio->aio_ai->ai_addr);
853 #ifdef INET6
854         if (ai.ai_family == AF_INET6) {
855                 struct in6_ifreq ifr6;
856                 u_int32_t flags6;
857
858                 memset(&ifr6, 0, sizeof(ifr6));
859                 memcpy(&ifr6.ifr_addr, ai.ai_addr, ai.ai_addrlen);
860                 if (_ioctl(s, SIOCGIFAFLAG_IN6, &ifr6) == 0) {
861                         flags6 = ifr6.ifr_ifru.ifru_flags6;
862                         if ((flags6 & IN6_IFF_DEPRECATED))
863                                 aio->aio_srcflag |= AIO_SRCFLAG_DEPRECATED;
864                 }
865         }
866 #endif
867
868   cleanup:
869         _close(s);
870         return;
871 }
872
873 static int
874 matchlen(struct sockaddr *src, struct sockaddr *dst)
875 {
876         int match = 0;
877         u_char *s, *d;
878         u_char *lim, r;
879         int addrlen;
880
881         switch (src->sa_family) {
882 #ifdef INET6
883         case AF_INET6:
884                 s = (u_char *)&((struct sockaddr_in6 *)src)->sin6_addr;
885                 d = (u_char *)&((struct sockaddr_in6 *)dst)->sin6_addr;
886                 addrlen = sizeof(struct in6_addr);
887                 lim = s + addrlen;
888                 break;
889 #endif
890         case AF_INET:
891                 s = (u_char *)&((struct sockaddr_in *)src)->sin_addr;
892                 d = (u_char *)&((struct sockaddr_in *)dst)->sin_addr;
893                 addrlen = sizeof(struct in_addr);
894                 lim = s + addrlen;
895                 break;
896         default:
897                 return(0);
898         }
899
900         while (s < lim)
901                 if ((r = (*d++ ^ *s++)) != 0) {
902                         while (r < addrlen * 8) {
903                                 match++;
904                                 r <<= 1;
905                         }
906                         break;
907                 } else
908                         match += 8;
909         return(match);
910 }
911
912 static int
913 comp_dst(const void *arg1, const void *arg2)
914 {
915         const struct ai_order *dst1 = arg1, *dst2 = arg2;
916
917         /*
918          * Rule 1: Avoid unusable destinations.
919          * XXX: we currently do not consider if an appropriate route exists.
920          */
921         if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
922             dst2->aio_srcsa.sa_family == AF_UNSPEC) {
923                 return(-1);
924         }
925         if (dst1->aio_srcsa.sa_family == AF_UNSPEC &&
926             dst2->aio_srcsa.sa_family != AF_UNSPEC) {
927                 return(1);
928         }
929
930         /* Rule 2: Prefer matching scope. */
931         if (dst1->aio_dstscope == dst1->aio_srcscope &&
932             dst2->aio_dstscope != dst2->aio_srcscope) {
933                 return(-1);
934         }
935         if (dst1->aio_dstscope != dst1->aio_srcscope &&
936             dst2->aio_dstscope == dst2->aio_srcscope) {
937                 return(1);
938         }
939
940         /* Rule 3: Avoid deprecated addresses. */
941         if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
942             dst2->aio_srcsa.sa_family != AF_UNSPEC) {
943                 if (!(dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
944                     (dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
945                         return(-1);
946                 }
947                 if ((dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
948                     !(dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
949                         return(1);
950                 }
951         }
952
953         /* Rule 4: Prefer home addresses. */
954         /* XXX: not implemented yet */
955
956         /* Rule 5: Prefer matching label. */
957 #ifdef INET6
958         if (dst1->aio_srcpolicy && dst1->aio_dstpolicy &&
959             dst1->aio_srcpolicy->pc_policy.label ==
960             dst1->aio_dstpolicy->pc_policy.label &&
961             (dst2->aio_srcpolicy == NULL || dst2->aio_dstpolicy == NULL ||
962              dst2->aio_srcpolicy->pc_policy.label !=
963              dst2->aio_dstpolicy->pc_policy.label)) {
964                 return(-1);
965         }
966         if (dst2->aio_srcpolicy && dst2->aio_dstpolicy &&
967             dst2->aio_srcpolicy->pc_policy.label ==
968             dst2->aio_dstpolicy->pc_policy.label &&
969             (dst1->aio_srcpolicy == NULL || dst1->aio_dstpolicy == NULL ||
970              dst1->aio_srcpolicy->pc_policy.label !=
971              dst1->aio_dstpolicy->pc_policy.label)) {
972                 return(1);
973         }
974 #endif
975
976         /* Rule 6: Prefer higher precedence. */
977 #ifdef INET6
978         if (dst1->aio_dstpolicy &&
979             (dst2->aio_dstpolicy == NULL ||
980              dst1->aio_dstpolicy->pc_policy.preced >
981              dst2->aio_dstpolicy->pc_policy.preced)) {
982                 return(-1);
983         }
984         if (dst2->aio_dstpolicy &&
985             (dst1->aio_dstpolicy == NULL ||
986              dst2->aio_dstpolicy->pc_policy.preced >
987              dst1->aio_dstpolicy->pc_policy.preced)) {
988                 return(1);
989         }
990 #endif
991
992         /* Rule 7: Prefer native transport. */
993         /* XXX: not implemented yet */
994
995         /* Rule 8: Prefer smaller scope. */
996         if (dst1->aio_dstscope >= 0 &&
997             dst1->aio_dstscope < dst2->aio_dstscope) {
998                 return(-1);
999         }
1000         if (dst2->aio_dstscope >= 0 &&
1001             dst2->aio_dstscope < dst1->aio_dstscope) {
1002                 return(1);
1003         }
1004
1005         /*
1006          * Rule 9: Use longest matching prefix.
1007          * We compare the match length in a same AF only.
1008          */
1009         if (dst1->aio_ai->ai_addr->sa_family ==
1010             dst2->aio_ai->ai_addr->sa_family) {
1011                 if (dst1->aio_matchlen > dst2->aio_matchlen) {
1012                         return(-1);
1013                 }
1014                 if (dst1->aio_matchlen < dst2->aio_matchlen) {
1015                         return(1);
1016                 }
1017         }
1018
1019         /* Rule 10: Otherwise, leave the order unchanged. */
1020         return(-1);
1021 }
1022
1023 /*
1024  * Copy from scope.c.
1025  * XXX: we should standardize the functions and link them as standard
1026  * library.
1027  */
1028 static int
1029 gai_addr2scopetype(struct sockaddr *sa)
1030 {
1031 #ifdef INET6
1032         struct sockaddr_in6 *sa6;
1033 #endif
1034         struct sockaddr_in *sa4;
1035
1036         switch(sa->sa_family) {
1037 #ifdef INET6
1038         case AF_INET6:
1039                 sa6 = (struct sockaddr_in6 *)sa;
1040                 if (IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
1041                         /* just use the scope field of the multicast address */
1042                         return(sa6->sin6_addr.s6_addr[2] & 0x0f);
1043                 }
1044                 /*
1045                  * Unicast addresses: map scope type to corresponding scope
1046                  * value defined for multcast addresses.
1047                  * XXX: hardcoded scope type values are bad...
1048                  */
1049                 if (IN6_IS_ADDR_LOOPBACK(&sa6->sin6_addr))
1050                         return(1); /* node local scope */
1051                 if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr))
1052                         return(2); /* link-local scope */
1053                 if (IN6_IS_ADDR_SITELOCAL(&sa6->sin6_addr))
1054                         return(5); /* site-local scope */
1055                 return(14);     /* global scope */
1056                 break;
1057 #endif
1058         case AF_INET:
1059                 /*
1060                  * IPv4 pseudo scoping according to RFC 3484.
1061                  */
1062                 sa4 = (struct sockaddr_in *)sa;
1063                 /* IPv4 autoconfiguration addresses have link-local scope. */
1064                 if (((u_char *)&sa4->sin_addr)[0] == 169 &&
1065                     ((u_char *)&sa4->sin_addr)[1] == 254)
1066                         return(2);
1067                 /* Private addresses have site-local scope. */
1068                 if (((u_char *)&sa4->sin_addr)[0] == 10 ||
1069                     (((u_char *)&sa4->sin_addr)[0] == 172 &&
1070                      (((u_char *)&sa4->sin_addr)[1] & 0xf0) == 16) ||
1071                     (((u_char *)&sa4->sin_addr)[0] == 192 &&
1072                      ((u_char *)&sa4->sin_addr)[1] == 168))
1073                         return(14);     /* XXX: It should be 5 unless NAT */
1074                 /* Loopback addresses have link-local scope. */
1075                 if (((u_char *)&sa4->sin_addr)[0] == 127)
1076                         return(2);
1077                 return(14);
1078                 break;
1079         default:
1080                 errno = EAFNOSUPPORT; /* is this a good error? */
1081                 return(-1);
1082         }
1083 }
1084
1085 static int
1086 explore_copy(const struct addrinfo *pai, const struct addrinfo *src0,
1087     struct addrinfo **res)
1088 {
1089         int error;
1090         struct addrinfo sentinel, *cur;
1091         const struct addrinfo *src;
1092
1093         error = 0;
1094         sentinel.ai_next = NULL;
1095         cur = &sentinel;
1096
1097         for (src = src0; src != NULL; src = src->ai_next) {
1098                 if (src->ai_family != pai->ai_family)
1099                         continue;
1100
1101                 cur->ai_next = copy_ai(src);
1102                 if (!cur->ai_next) {
1103                         error = EAI_MEMORY;
1104                         goto fail;
1105                 }
1106
1107                 cur->ai_next->ai_socktype = pai->ai_socktype;
1108                 cur->ai_next->ai_protocol = pai->ai_protocol;
1109                 cur = cur->ai_next;
1110         }
1111
1112         *res = sentinel.ai_next;
1113         return 0;
1114
1115 fail:
1116         freeaddrinfo(sentinel.ai_next);
1117         return error;
1118 }
1119
1120 /*
1121  * hostname == NULL.
1122  * passive socket -> anyaddr (0.0.0.0 or ::)
1123  * non-passive socket -> localhost (127.0.0.1 or ::1)
1124  */
1125 static int
1126 explore_null(const struct addrinfo *pai, const char *servname,
1127     struct addrinfo **res)
1128 {
1129         int s;
1130         const struct afd *afd;
1131         struct addrinfo *ai;
1132         int error;
1133
1134         *res = NULL;
1135         ai = NULL;
1136
1137         /*
1138          * filter out AFs that are not supported by the kernel
1139          * XXX errno?
1140          */
1141         s = _socket(pai->ai_family, SOCK_DGRAM, 0);
1142         if (s < 0) {
1143                 if (errno != EMFILE)
1144                         return 0;
1145         } else
1146                 _close(s);
1147
1148         afd = find_afd(pai->ai_family);
1149         if (afd == NULL)
1150                 return 0;
1151
1152         if (pai->ai_flags & AI_PASSIVE) {
1153                 GET_AI(ai, afd, afd->a_addrany);
1154                 GET_PORT(ai, servname);
1155         } else {
1156                 GET_AI(ai, afd, afd->a_loopback);
1157                 GET_PORT(ai, servname);
1158         }
1159
1160         *res = ai;
1161         return 0;
1162
1163 free:
1164         if (ai != NULL)
1165                 freeaddrinfo(ai);
1166         return error;
1167 }
1168
1169 /*
1170  * numeric hostname
1171  */
1172 static int
1173 explore_numeric(const struct addrinfo *pai, const char *hostname,
1174     const char *servname, struct addrinfo **res, const char *canonname)
1175 {
1176         const struct afd *afd;
1177         struct addrinfo *ai;
1178         int error;
1179         char pton[PTON_MAX];
1180
1181         *res = NULL;
1182         ai = NULL;
1183
1184         afd = find_afd(pai->ai_family);
1185         if (afd == NULL)
1186                 return 0;
1187
1188         switch (afd->a_af) {
1189         case AF_INET:
1190                 /*
1191                  * RFC3493 requires getaddrinfo() to accept AF_INET formats
1192                  * that are accepted by inet_addr() and its family.  The
1193                  * accepted forms includes the "classful" one, which inet_pton
1194                  * does not accept.  So we need to separate the case for
1195                  * AF_INET.
1196                  */
1197                 if (inet_aton(hostname, (struct in_addr *)pton) != 1)
1198                         return 0;
1199                 break;
1200         default:
1201                 if (inet_pton(afd->a_af, hostname, pton) != 1)
1202                         return 0;
1203                 break;
1204         }
1205
1206         if (pai->ai_family == afd->a_af) {
1207                 GET_AI(ai, afd, pton);
1208                 GET_PORT(ai, servname);
1209                 if ((pai->ai_flags & AI_CANONNAME)) {
1210                         /*
1211                          * Set the numeric address itself as the canonical
1212                          * name, based on a clarification in RFC3493.
1213                          */
1214                         GET_CANONNAME(ai, canonname);
1215                 }
1216         } else {
1217                 /*
1218                  * XXX: This should not happen since we already matched the AF
1219                  * by find_afd.
1220                  */
1221                 ERR(EAI_FAMILY);
1222         }
1223
1224         *res = ai;
1225         return 0;
1226
1227 free:
1228 bad:
1229         if (ai != NULL)
1230                 freeaddrinfo(ai);
1231         return error;
1232 }
1233
1234 /*
1235  * numeric hostname with scope
1236  */
1237 static int
1238 explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
1239     const char *servname, struct addrinfo **res)
1240 {
1241 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
1242         return explore_numeric(pai, hostname, servname, res, hostname);
1243 #else
1244         const struct afd *afd;
1245         struct addrinfo *cur;
1246         int error;
1247         char *cp, *hostname2 = NULL, *scope, *addr;
1248         struct sockaddr_in6 *sin6;
1249
1250         afd = find_afd(pai->ai_family);
1251         if (afd == NULL)
1252                 return 0;
1253
1254         if (!afd->a_scoped)
1255                 return explore_numeric(pai, hostname, servname, res, hostname);
1256
1257         cp = strchr(hostname, SCOPE_DELIMITER);
1258         if (cp == NULL)
1259                 return explore_numeric(pai, hostname, servname, res, hostname);
1260
1261         /*
1262          * Handle special case of <scoped_address><delimiter><scope id>
1263          */
1264         hostname2 = strdup(hostname);
1265         if (hostname2 == NULL)
1266                 return EAI_MEMORY;
1267         /* terminate at the delimiter */
1268         hostname2[cp - hostname] = '\0';
1269         addr = hostname2;
1270         scope = cp + 1;
1271
1272         error = explore_numeric(pai, addr, servname, res, hostname);
1273         if (error == 0) {
1274                 u_int32_t scopeid;
1275
1276                 for (cur = *res; cur; cur = cur->ai_next) {
1277                         if (cur->ai_family != AF_INET6)
1278                                 continue;
1279                         sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
1280                         if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
1281                                 free(hostname2);
1282                                 freeaddrinfo(*res);
1283                                 *res = NULL;
1284                                 return(EAI_NONAME); /* XXX: is return OK? */
1285                         }
1286                         sin6->sin6_scope_id = scopeid;
1287                 }
1288         }
1289
1290         free(hostname2);
1291
1292         if (error && *res) {
1293                 freeaddrinfo(*res);
1294                 *res = NULL;
1295         }
1296         return error;
1297 #endif
1298 }
1299
1300 static int
1301 get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
1302 {
1303         if ((pai->ai_flags & AI_CANONNAME) != 0) {
1304                 ai->ai_canonname = strdup(str);
1305                 if (ai->ai_canonname == NULL)
1306                         return EAI_MEMORY;
1307         }
1308         return 0;
1309 }
1310
1311 static struct addrinfo *
1312 get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
1313 {
1314         char *p;
1315         struct addrinfo *ai;
1316 #ifdef FAITH
1317         struct in6_addr faith_prefix;
1318         char *fp_str;
1319         int translate = 0;
1320 #endif
1321
1322 #ifdef FAITH
1323         /*
1324          * Transfrom an IPv4 addr into a special IPv6 addr format for
1325          * IPv6->IPv4 translation gateway. (only TCP is supported now)
1326          *
1327          * +-----------------------------------+------------+
1328          * | faith prefix part (12 bytes)      | embedded   |
1329          * |                                   | IPv4 addr part (4 bytes)
1330          * +-----------------------------------+------------+
1331          *
1332          * faith prefix part is specified as ascii IPv6 addr format
1333          * in environmental variable GAI.
1334          * For FAITH to work correctly, routing to faith prefix must be
1335          * setup toward a machine where a FAITH daemon operates.
1336          * Also, the machine must enable some mechanizm
1337          * (e.g. faith interface hack) to divert those packet with
1338          * faith prefixed destination addr to user-land FAITH daemon.
1339          */
1340         fp_str = getenv("GAI");
1341         if (fp_str && inet_pton(AF_INET6, fp_str, &faith_prefix) == 1 &&
1342             afd->a_af == AF_INET && pai->ai_socktype == SOCK_STREAM) {
1343                 u_int32_t v4a;
1344                 u_int8_t v4a_top;
1345
1346                 memcpy(&v4a, addr, sizeof v4a);
1347                 v4a_top = v4a >> IN_CLASSA_NSHIFT;
1348                 if (!IN_MULTICAST(v4a) && !IN_EXPERIMENTAL(v4a) &&
1349                     v4a_top != 0 && v4a != IN_LOOPBACKNET) {
1350                         afd = &afdl[N_INET6];
1351                         memcpy(&faith_prefix.s6_addr[12], addr,
1352                                sizeof(struct in_addr));
1353                         translate = 1;
1354                 }
1355         }
1356 #endif
1357
1358         ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
1359                 + (afd->a_socklen));
1360         if (ai == NULL)
1361                 return NULL;
1362
1363         memcpy(ai, pai, sizeof(struct addrinfo));
1364         ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1365         memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
1366         ai->ai_addr->sa_len = afd->a_socklen;
1367         ai->ai_addrlen = afd->a_socklen;
1368         ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
1369         p = (char *)(void *)(ai->ai_addr);
1370 #ifdef FAITH
1371         if (translate == 1)
1372                 memcpy(p + afd->a_off, &faith_prefix, (size_t)afd->a_addrlen);
1373         else
1374 #endif
1375         memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
1376         return ai;
1377 }
1378
1379 /* XXX need to malloc() the same way we do from other functions! */
1380 static struct addrinfo *
1381 copy_ai(const struct addrinfo *pai)
1382 {
1383         struct addrinfo *ai;
1384         size_t l;
1385
1386         l = sizeof(*ai) + pai->ai_addrlen;
1387         if ((ai = (struct addrinfo *)malloc(l)) == NULL)
1388                 return NULL;
1389         memset(ai, 0, l);
1390         memcpy(ai, pai, sizeof(*ai));
1391         ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1392         memcpy(ai->ai_addr, pai->ai_addr, pai->ai_addrlen);
1393
1394         if (pai->ai_canonname) {
1395                 l = strlen(pai->ai_canonname) + 1;
1396                 if ((ai->ai_canonname = malloc(l)) == NULL) {
1397                         free(ai);
1398                         return NULL;
1399                 }
1400                 strlcpy(ai->ai_canonname, pai->ai_canonname, l);
1401         } else {
1402                 /* just to make sure */
1403                 ai->ai_canonname = NULL;
1404         }
1405
1406         ai->ai_next = NULL;
1407
1408         return ai;
1409 }
1410
1411 static int
1412 get_portmatch(const struct addrinfo *ai, const char *servname)
1413 {
1414
1415         /* get_port does not touch first argument when matchonly == 1. */
1416         /* LINTED const cast */
1417         return get_port((struct addrinfo *)ai, servname, 1);
1418 }
1419
1420 static int
1421 get_port(struct addrinfo *ai, const char *servname, int matchonly)
1422 {
1423         const char *proto;
1424         struct servent *sp;
1425         int port, error;
1426         int allownumeric;
1427
1428         if (servname == NULL)
1429                 return 0;
1430         switch (ai->ai_family) {
1431         case AF_INET:
1432 #ifdef AF_INET6
1433         case AF_INET6:
1434 #endif
1435                 break;
1436         default:
1437                 return 0;
1438         }
1439
1440         switch (ai->ai_socktype) {
1441         case SOCK_RAW:
1442                 return EAI_SERVICE;
1443         case SOCK_DGRAM:
1444         case SOCK_STREAM:
1445         case SOCK_SEQPACKET:
1446                 allownumeric = 1;
1447                 break;
1448         case ANY:
1449                 switch (ai->ai_family) {
1450                 case AF_INET:
1451 #ifdef AF_INET6
1452                 case AF_INET6:
1453 #endif
1454                         allownumeric = 1;
1455                         break;
1456                 default:
1457                         allownumeric = 0;
1458                         break;
1459                 }
1460                 break;
1461         default:
1462                 return EAI_SOCKTYPE;
1463         }
1464
1465         error = str2number(servname, &port);
1466         if (error == 0) {
1467                 if (!allownumeric)
1468                         return EAI_SERVICE;
1469                 if (port < 0 || port > 65535)
1470                         return EAI_SERVICE;
1471                 port = htons(port);
1472         } else {
1473                 if (ai->ai_flags & AI_NUMERICSERV)
1474                         return EAI_NONAME;
1475
1476                 switch (ai->ai_protocol) {
1477                 case IPPROTO_UDP:
1478                         proto = "udp";
1479                         break;
1480                 case IPPROTO_TCP:
1481                         proto = "tcp";
1482                         break;
1483                 case IPPROTO_SCTP:
1484                         proto = "sctp";
1485                         break;
1486                 default:
1487                         proto = NULL;
1488                         break;
1489                 }
1490
1491                 if ((sp = getservbyname(servname, proto)) == NULL)
1492                         return EAI_SERVICE;
1493                 port = sp->s_port;
1494         }
1495
1496         if (!matchonly) {
1497                 switch (ai->ai_family) {
1498                 case AF_INET:
1499                         ((struct sockaddr_in *)(void *)
1500                             ai->ai_addr)->sin_port = port;
1501                         break;
1502 #ifdef INET6
1503                 case AF_INET6:
1504                         ((struct sockaddr_in6 *)(void *)
1505                             ai->ai_addr)->sin6_port = port;
1506                         break;
1507 #endif
1508                 }
1509         }
1510
1511         return 0;
1512 }
1513
1514 static const struct afd *
1515 find_afd(int af)
1516 {
1517         const struct afd *afd;
1518
1519         if (af == PF_UNSPEC)
1520                 return NULL;
1521         for (afd = afdl; afd->a_af; afd++) {
1522                 if (afd->a_af == af)
1523                         return afd;
1524         }
1525         return NULL;
1526 }
1527
1528 /*
1529  * post-2553: AI_ADDRCONFIG check.  Determines which address families are
1530  * configured on the local system and correlates with pai->ai_family value.
1531  * If an address family is not configured on the system, it will not be
1532  * queried for.  For this purpose, loopback addresses are not considered
1533  * configured addresses.
1534  *
1535  * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with
1536  * _dns_getaddrinfo.
1537  */
1538 static int
1539 addrconfig(struct addrinfo *pai)
1540 {
1541         struct ifaddrs *ifaddrs, *ifa;
1542         int seen_inet = 0, seen_inet6 = 0;
1543
1544         if (getifaddrs(&ifaddrs) != 0)
1545                 return 0;
1546
1547         for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
1548                 if (ifa->ifa_addr == NULL || (ifa->ifa_flags & IFF_UP) == 0)
1549                         continue;
1550                 if ((ifa->ifa_flags & IFT_LOOP) != 0)
1551                         continue;
1552                 switch (ifa->ifa_addr->sa_family) {
1553                 case AF_INET:
1554                         seen_inet = 1;
1555                         break;
1556 #ifdef INET6
1557                 case AF_INET6:
1558                         if (!seen_inet6 && !is_ifdisabled(ifa->ifa_name))
1559                                 seen_inet6 = 1;
1560                         break;
1561 #endif
1562                 }
1563         }
1564         freeifaddrs(ifaddrs);
1565
1566         switch(pai->ai_family) {
1567         case AF_INET6:
1568                 return seen_inet6;
1569         case AF_INET:
1570                 return seen_inet;
1571         case AF_UNSPEC:
1572                 if (seen_inet == seen_inet6)
1573                         return seen_inet;
1574                 pai->ai_family = seen_inet ? AF_INET : AF_INET6;
1575                 return 1;
1576         }
1577         return 1;
1578 }
1579
1580 #ifdef INET6
1581 static int
1582 is_ifdisabled(char *name)
1583 {
1584         struct in6_ndireq nd;
1585         int fd;
1586
1587         if ((fd = _socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1588                 return -1;
1589         memset(&nd, 0, sizeof(nd));
1590         strlcpy(nd.ifname, name, sizeof(nd.ifname));
1591         if (_ioctl(fd, SIOCGIFINFO_IN6, &nd) < 0) {
1592                 _close(fd);
1593                 return -1;
1594         }
1595         _close(fd);
1596         return ((nd.ndi.flags & ND6_IFF_IFDISABLED) != 0);
1597 }
1598
1599 /* convert a string to a scope identifier. XXX: IPv6 specific */
1600 static int
1601 ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1602 {
1603         u_long lscopeid;
1604         struct in6_addr *a6;
1605         char *ep;
1606
1607         a6 = &sin6->sin6_addr;
1608
1609         /* empty scopeid portion is invalid */
1610         if (*scope == '\0')
1611                 return -1;
1612
1613         if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6) ||
1614             IN6_IS_ADDR_MC_NODELOCAL(a6)) {
1615                 /*
1616                  * We currently assume a one-to-one mapping between links
1617                  * and interfaces, so we simply use interface indices for
1618                  * like-local scopes.
1619                  */
1620                 *scopeid = if_nametoindex(scope);
1621                 if (*scopeid == 0)
1622                         goto trynumeric;
1623                 return 0;
1624         }
1625
1626         /* still unclear about literal, allow numeric only - placeholder */
1627         if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1628                 goto trynumeric;
1629         if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1630                 goto trynumeric;
1631         else
1632                 goto trynumeric;        /* global */
1633
1634         /* try to convert to a numeric id as a last resort */
1635   trynumeric:
1636         errno = 0;
1637         lscopeid = strtoul(scope, &ep, 10);
1638         *scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1639         if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1640                 return 0;
1641         else
1642                 return -1;
1643 }
1644 #endif
1645
1646
1647 #ifdef NS_CACHING
1648 static int
1649 addrinfo_id_func(char *buffer, size_t *buffer_size, va_list ap,
1650     void *cache_mdata)
1651 {
1652         res_state statp;
1653         u_long res_options;
1654
1655         const int op_id = 0;    /* identifies the getaddrinfo for the cache */
1656         char *hostname;
1657         struct addrinfo *hints;
1658
1659         char *p;
1660         int ai_flags, ai_family, ai_socktype, ai_protocol;
1661         size_t desired_size, size;
1662
1663         statp = __res_state();
1664         res_options = statp->options & (RES_RECURSE | RES_DEFNAMES |
1665             RES_DNSRCH | RES_NOALIASES | RES_USE_INET6);
1666
1667         hostname = va_arg(ap, char *);
1668         hints = va_arg(ap, struct addrinfo *);
1669
1670         desired_size = sizeof(res_options) + sizeof(int) + sizeof(int) * 4;
1671         if (hostname != NULL) {
1672                 size = strlen(hostname);
1673                 desired_size += size + 1;
1674         } else
1675                 size = 0;
1676
1677         if (desired_size > *buffer_size) {
1678                 *buffer_size = desired_size;
1679                 return (NS_RETURN);
1680         }
1681
1682         if (hints == NULL)
1683                 ai_flags = ai_family = ai_socktype = ai_protocol = 0;
1684         else {
1685                 ai_flags = hints->ai_flags;
1686                 ai_family = hints->ai_family;
1687                 ai_socktype = hints->ai_socktype;
1688                 ai_protocol = hints->ai_protocol;
1689         }
1690
1691         p = buffer;
1692         memcpy(p, &res_options, sizeof(res_options));
1693         p += sizeof(res_options);
1694
1695         memcpy(p, &op_id, sizeof(int));
1696         p += sizeof(int);
1697
1698         memcpy(p, &ai_flags, sizeof(int));
1699         p += sizeof(int);
1700
1701         memcpy(p, &ai_family, sizeof(int));
1702         p += sizeof(int);
1703
1704         memcpy(p, &ai_socktype, sizeof(int));
1705         p += sizeof(int);
1706
1707         memcpy(p, &ai_protocol, sizeof(int));
1708         p += sizeof(int);
1709
1710         if (hostname != NULL)
1711                 memcpy(p, hostname, size);
1712
1713         *buffer_size = desired_size;
1714         return (NS_SUCCESS);
1715 }
1716
1717 static int
1718 addrinfo_marshal_func(char *buffer, size_t *buffer_size, void *retval,
1719     va_list ap, void *cache_mdata)
1720 {
1721         struct addrinfo *ai, *cai;
1722         char *p;
1723         size_t desired_size, size, ai_size;
1724
1725         ai = *((struct addrinfo **)retval);
1726
1727         desired_size = sizeof(size_t);
1728         ai_size = 0;
1729         for (cai = ai; cai != NULL; cai = cai->ai_next) {
1730                 desired_size += sizeof(struct addrinfo) + cai->ai_addrlen;
1731                 if (cai->ai_canonname != NULL)
1732                         desired_size += sizeof(size_t) +
1733                             strlen(cai->ai_canonname);
1734                 ++ai_size;
1735         }
1736
1737         if (desired_size > *buffer_size) {
1738                 /* this assignment is here for future use */
1739                 errno = ERANGE;
1740                 *buffer_size = desired_size;
1741                 return (NS_RETURN);
1742         }
1743
1744         memset(buffer, 0, desired_size);
1745         p = buffer;
1746
1747         memcpy(p, &ai_size, sizeof(size_t));
1748         p += sizeof(size_t);
1749         for (cai = ai; cai != NULL; cai = cai->ai_next) {
1750                 memcpy(p, cai, sizeof(struct addrinfo));
1751                 p += sizeof(struct addrinfo);
1752
1753                 memcpy(p, cai->ai_addr, cai->ai_addrlen);
1754                 p += cai->ai_addrlen;
1755
1756                 if (cai->ai_canonname != NULL) {
1757                         size = strlen(cai->ai_canonname);
1758                         memcpy(p, &size, sizeof(size_t));
1759                         p += sizeof(size_t);
1760
1761                         memcpy(p, cai->ai_canonname, size);
1762                         p += size;
1763                 }
1764         }
1765
1766         return (NS_SUCCESS);
1767 }
1768
1769 static int
1770 addrinfo_unmarshal_func(char *buffer, size_t buffer_size, void *retval,
1771     va_list ap, void *cache_mdata)
1772 {
1773         struct addrinfo new_ai, *result, *sentinel, *lasts;
1774
1775         char *p;
1776         size_t ai_size, ai_i, size;
1777
1778         p = buffer;
1779         memcpy(&ai_size, p, sizeof(size_t));
1780         p += sizeof(size_t);
1781
1782         result = NULL;
1783         lasts = NULL;
1784         for (ai_i = 0; ai_i < ai_size; ++ai_i) {
1785                 memcpy(&new_ai, p, sizeof(struct addrinfo));
1786                 p += sizeof(struct addrinfo);
1787                 size = new_ai.ai_addrlen + sizeof(struct addrinfo) +
1788                         _ALIGNBYTES;
1789
1790                 sentinel = (struct addrinfo *)malloc(size);
1791                 memset(sentinel, 0, size);
1792
1793                 memcpy(sentinel, &new_ai, sizeof(struct addrinfo));
1794                 sentinel->ai_addr = (struct sockaddr *)_ALIGN((char *)sentinel +
1795                     sizeof(struct addrinfo));
1796
1797                 memcpy(sentinel->ai_addr, p, new_ai.ai_addrlen);
1798                 p += new_ai.ai_addrlen;
1799
1800                 if (new_ai.ai_canonname != NULL) {
1801                         memcpy(&size, p, sizeof(size_t));
1802                         p += sizeof(size_t);
1803
1804                         sentinel->ai_canonname = (char *)malloc(size + 1);
1805                         memset(sentinel->ai_canonname, 0, size + 1);
1806
1807                         memcpy(sentinel->ai_canonname, p, size);
1808                         p += size;
1809                 }
1810
1811                 if (result == NULL) {
1812                         result = sentinel;
1813                         lasts = sentinel;
1814                 } else {
1815                         lasts->ai_next = sentinel;
1816                         lasts = sentinel;
1817                 }
1818         }
1819
1820         *((struct addrinfo **)retval) = result;
1821         return (NS_SUCCESS);
1822 }
1823 #endif /* NS_CACHING */
1824
1825 /*
1826  * FQDN hostname, DNS lookup
1827  */
1828 static int
1829 explore_fqdn(const struct addrinfo *pai, const char *hostname,
1830     const char *servname, struct addrinfo **res)
1831 {
1832         struct addrinfo *result;
1833         struct addrinfo *cur;
1834         int error = 0;
1835
1836 #ifdef NS_CACHING
1837         static const nss_cache_info cache_info =
1838         NS_COMMON_CACHE_INFO_INITIALIZER(
1839                 hosts, NULL, addrinfo_id_func, addrinfo_marshal_func,
1840                 addrinfo_unmarshal_func);
1841 #endif
1842         static const ns_dtab dtab[] = {
1843                 NS_FILES_CB(_files_getaddrinfo, NULL)
1844                 { NSSRC_DNS, _dns_getaddrinfo, NULL },  /* force -DHESIOD */
1845                 NS_NIS_CB(_yp_getaddrinfo, NULL)
1846 #ifdef NS_CACHING
1847                 NS_CACHE_CB(&cache_info)
1848 #endif
1849                 { 0 }
1850         };
1851
1852         result = NULL;
1853
1854         /*
1855          * if the servname does not match socktype/protocol, ignore it.
1856          */
1857         if (get_portmatch(pai, servname) != 0)
1858                 return 0;
1859
1860         switch (_nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
1861                         default_dns_files, hostname, pai)) {
1862         case NS_TRYAGAIN:
1863                 error = EAI_AGAIN;
1864                 goto free;
1865         case NS_UNAVAIL:
1866                 error = EAI_FAIL;
1867                 goto free;
1868         case NS_NOTFOUND:
1869                 error = EAI_NONAME;
1870                 goto free;
1871         case NS_SUCCESS:
1872                 error = 0;
1873                 for (cur = result; cur; cur = cur->ai_next) {
1874                         GET_PORT(cur, servname);
1875                         /* canonname should be filled already */
1876                 }
1877                 break;
1878         }
1879
1880         *res = result;
1881
1882         return 0;
1883
1884 free:
1885         if (result)
1886                 freeaddrinfo(result);
1887         return error;
1888 }
1889
1890 #ifdef DEBUG
1891 static const char AskedForGot[] =
1892         "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1893 #endif
1894
1895 static struct addrinfo *
1896 getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1897     const struct addrinfo *pai, res_state res)
1898 {
1899         struct addrinfo sentinel, *cur;
1900         struct addrinfo ai;
1901         const struct afd *afd;
1902         char *canonname;
1903         const HEADER *hp;
1904         const u_char *cp;
1905         int n;
1906         const u_char *eom;
1907         char *bp, *ep;
1908         int type, class, ancount, qdcount;
1909         int haveanswer, had_error;
1910         char tbuf[MAXDNAME];
1911         int (*name_ok)(const char *);
1912         char hostbuf[8*1024];
1913
1914         memset(&sentinel, 0, sizeof(sentinel));
1915         cur = &sentinel;
1916
1917         canonname = NULL;
1918         eom = answer->buf + anslen;
1919         switch (qtype) {
1920         case T_A:
1921         case T_AAAA:
1922         case T_ANY:     /*use T_ANY only for T_A/T_AAAA lookup*/
1923                 name_ok = res_hnok;
1924                 break;
1925         default:
1926                 return (NULL);  /* XXX should be abort(); */
1927         }
1928         /*
1929          * find first satisfactory answer
1930          */
1931         hp = &answer->hdr;
1932         ancount = ntohs(hp->ancount);
1933         qdcount = ntohs(hp->qdcount);
1934         bp = hostbuf;
1935         ep = hostbuf + sizeof hostbuf;
1936         cp = answer->buf + HFIXEDSZ;
1937         if (qdcount != 1) {
1938                 RES_SET_H_ERRNO(res, NO_RECOVERY);
1939                 return (NULL);
1940         }
1941         n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1942         if ((n < 0) || !(*name_ok)(bp)) {
1943                 RES_SET_H_ERRNO(res, NO_RECOVERY);
1944                 return (NULL);
1945         }
1946         cp += n + QFIXEDSZ;
1947         if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1948                 /* res_send() has already verified that the query name is the
1949                  * same as the one we sent; this just gets the expanded name
1950                  * (i.e., with the succeeding search-domain tacked on).
1951                  */
1952                 n = strlen(bp) + 1;             /* for the \0 */
1953                 if (n >= MAXHOSTNAMELEN) {
1954                         RES_SET_H_ERRNO(res, NO_RECOVERY);
1955                         return (NULL);
1956                 }
1957                 canonname = bp;
1958                 bp += n;
1959                 /* The qname can be abbreviated, but h_name is now absolute. */
1960                 qname = canonname;
1961         }
1962         haveanswer = 0;
1963         had_error = 0;
1964         while (ancount-- > 0 && cp < eom && !had_error) {
1965                 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1966                 if ((n < 0) || !(*name_ok)(bp)) {
1967                         had_error++;
1968                         continue;
1969                 }
1970                 cp += n;                        /* name */
1971                 type = _getshort(cp);
1972                 cp += INT16SZ;                  /* type */
1973                 class = _getshort(cp);
1974                 cp += INT16SZ + INT32SZ;        /* class, TTL */
1975                 n = _getshort(cp);
1976                 cp += INT16SZ;                  /* len */
1977                 if (class != C_IN) {
1978                         /* XXX - debug? syslog? */
1979                         cp += n;
1980                         continue;               /* XXX - had_error++ ? */
1981                 }
1982                 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1983                     type == T_CNAME) {
1984                         n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1985                         if ((n < 0) || !(*name_ok)(tbuf)) {
1986                                 had_error++;
1987                                 continue;
1988                         }
1989                         cp += n;
1990                         /* Get canonical name. */
1991                         n = strlen(tbuf) + 1;   /* for the \0 */
1992                         if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1993                                 had_error++;
1994                                 continue;
1995                         }
1996                         strlcpy(bp, tbuf, ep - bp);
1997                         canonname = bp;
1998                         bp += n;
1999                         continue;
2000                 }
2001                 if (qtype == T_ANY) {
2002                         if (!(type == T_A || type == T_AAAA)) {
2003                                 cp += n;
2004                                 continue;
2005                         }
2006                 } else if (type != qtype) {
2007 #ifdef DEBUG
2008                         if (type != T_KEY && type != T_SIG &&
2009                             type != ns_t_dname)
2010                                 syslog(LOG_NOTICE|LOG_AUTH,
2011                "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
2012                                        qname, p_class(C_IN), p_type(qtype),
2013                                        p_type(type));
2014 #endif
2015                         cp += n;
2016                         continue;               /* XXX - had_error++ ? */
2017                 }
2018                 switch (type) {
2019                 case T_A:
2020                 case T_AAAA:
2021                         if (strcasecmp(canonname, bp) != 0) {
2022 #ifdef DEBUG
2023                                 syslog(LOG_NOTICE|LOG_AUTH,
2024                                        AskedForGot, canonname, bp);
2025 #endif
2026                                 cp += n;
2027                                 continue;       /* XXX - had_error++ ? */
2028                         }
2029                         if (type == T_A && n != INADDRSZ) {
2030                                 cp += n;
2031                                 continue;
2032                         }
2033                         if (type == T_AAAA && n != IN6ADDRSZ) {
2034                                 cp += n;
2035                                 continue;
2036                         }
2037 #ifdef FILTER_V4MAPPED
2038                         if (type == T_AAAA) {
2039                                 struct in6_addr in6;
2040                                 memcpy(&in6, cp, sizeof(in6));
2041                                 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
2042                                         cp += n;
2043                                         continue;
2044                                 }
2045                         }
2046 #endif
2047                         if (!haveanswer) {
2048                                 int nn;
2049
2050                                 canonname = bp;
2051                                 nn = strlen(bp) + 1;    /* for the \0 */
2052                                 bp += nn;
2053                         }
2054
2055                         /* don't overwrite pai */
2056                         ai = *pai;
2057                         ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
2058                         afd = find_afd(ai.ai_family);
2059                         if (afd == NULL) {
2060                                 cp += n;
2061                                 continue;
2062                         }
2063                         cur->ai_next = get_ai(&ai, afd, (const char *)cp);
2064                         if (cur->ai_next == NULL)
2065                                 had_error++;
2066                         while (cur && cur->ai_next)
2067                                 cur = cur->ai_next;
2068                         cp += n;
2069                         break;
2070                 default:
2071                         abort();
2072                 }
2073                 if (!had_error)
2074                         haveanswer++;
2075         }
2076         if (haveanswer) {
2077 #if defined(RESOLVSORT)
2078                 /*
2079                  * We support only IPv4 address for backward
2080                  * compatibility against gethostbyname(3).
2081                  */
2082                 if (res->nsort && qtype == T_A) {
2083                         if (addr4sort(&sentinel, res) < 0) {
2084                                 freeaddrinfo(sentinel.ai_next);
2085                                 RES_SET_H_ERRNO(res, NO_RECOVERY);
2086                                 return NULL;
2087                         }
2088                 }
2089 #endif /*RESOLVSORT*/
2090                 if (!canonname)
2091                         (void)get_canonname(pai, sentinel.ai_next, qname);
2092                 else
2093                         (void)get_canonname(pai, sentinel.ai_next, canonname);
2094                 RES_SET_H_ERRNO(res, NETDB_SUCCESS);
2095                 return sentinel.ai_next;
2096         }
2097
2098         RES_SET_H_ERRNO(res, NO_RECOVERY);
2099         return NULL;
2100 }
2101
2102 #ifdef RESOLVSORT
2103 struct addr_ptr {
2104         struct addrinfo *ai;
2105         int aval;
2106 };
2107
2108 static int
2109 addr4sort(struct addrinfo *sentinel, res_state res)
2110 {
2111         struct addrinfo *ai;
2112         struct addr_ptr *addrs, addr;
2113         struct sockaddr_in *sin;
2114         int naddrs, i, j;
2115         int needsort = 0;
2116
2117         if (!sentinel)
2118                 return -1;
2119         naddrs = 0;
2120         for (ai = sentinel->ai_next; ai; ai = ai->ai_next)
2121                 naddrs++;
2122         if (naddrs < 2)
2123                 return 0;               /* We don't need sorting. */
2124         if ((addrs = malloc(sizeof(struct addr_ptr) * naddrs)) == NULL)
2125                 return -1;
2126         i = 0;
2127         for (ai = sentinel->ai_next; ai; ai = ai->ai_next) {
2128                 sin = (struct sockaddr_in *)ai->ai_addr;
2129                 for (j = 0; (unsigned)j < res->nsort; j++) {
2130                         if (res->sort_list[j].addr.s_addr ==
2131                             (sin->sin_addr.s_addr & res->sort_list[j].mask))
2132                                 break;
2133                 }
2134                 addrs[i].ai = ai;
2135                 addrs[i].aval = j;
2136                 if (needsort == 0 && i > 0 && j < addrs[i - 1].aval)
2137                         needsort = i;
2138                 i++;
2139         }
2140         if (!needsort) {
2141                 free(addrs);
2142                 return 0;
2143         }
2144
2145         while (needsort < naddrs) {
2146                 for (j = needsort - 1; j >= 0; j--) {
2147                         if (addrs[j].aval > addrs[j+1].aval) {
2148                                 addr = addrs[j];
2149                                 addrs[j] = addrs[j + 1];
2150                                 addrs[j + 1] = addr;
2151                         } else
2152                                 break;
2153                 }
2154                 needsort++;
2155         }
2156
2157         ai = sentinel;
2158         for (i = 0; i < naddrs; ++i) {
2159                 ai->ai_next = addrs[i].ai;
2160                 ai = ai->ai_next;
2161         }
2162         ai->ai_next = NULL;
2163         free(addrs);
2164         return 0;
2165 }
2166 #endif /*RESOLVSORT*/
2167
2168 /*ARGSUSED*/
2169 static int
2170 _dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
2171 {
2172         struct addrinfo *ai;
2173         querybuf *buf, *buf2;
2174         const char *hostname;
2175         const struct addrinfo *pai;
2176         struct addrinfo sentinel, *cur;
2177         struct res_target q, q2;
2178         res_state res;
2179
2180         hostname = va_arg(ap, char *);
2181         pai = va_arg(ap, const struct addrinfo *);
2182
2183         memset(&q, 0, sizeof(q));
2184         memset(&q2, 0, sizeof(q2));
2185         memset(&sentinel, 0, sizeof(sentinel));
2186         cur = &sentinel;
2187
2188         buf = malloc(sizeof(*buf));
2189         if (!buf) {
2190                 RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2191                 return NS_NOTFOUND;
2192         }
2193         buf2 = malloc(sizeof(*buf2));
2194         if (!buf2) {
2195                 free(buf);
2196                 RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2197                 return NS_NOTFOUND;
2198         }
2199
2200         switch (pai->ai_family) {
2201         case AF_UNSPEC:
2202                 q.name = hostname;
2203                 q.qclass = C_IN;
2204                 q.qtype = T_A;
2205                 q.answer = buf->buf;
2206                 q.anslen = sizeof(buf->buf);
2207                 q.next = &q2;
2208                 q2.name = hostname;
2209                 q2.qclass = C_IN;
2210                 q2.qtype = T_AAAA;
2211                 q2.answer = buf2->buf;
2212                 q2.anslen = sizeof(buf2->buf);
2213                 break;
2214         case AF_INET:
2215                 q.name = hostname;
2216                 q.qclass = C_IN;
2217                 q.qtype = T_A;
2218                 q.answer = buf->buf;
2219                 q.anslen = sizeof(buf->buf);
2220                 break;
2221         case AF_INET6:
2222                 q.name = hostname;
2223                 q.qclass = C_IN;
2224                 q.qtype = T_AAAA;
2225                 q.answer = buf->buf;
2226                 q.anslen = sizeof(buf->buf);
2227                 break;
2228         default:
2229                 free(buf);
2230                 free(buf2);
2231                 return NS_UNAVAIL;
2232         }
2233
2234         res = __res_state();
2235         if ((res->options & RES_INIT) == 0 && res_ninit(res) == -1) {
2236                 RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2237                 free(buf);
2238                 free(buf2);
2239                 return NS_NOTFOUND;
2240         }
2241
2242         if (res_searchN(hostname, &q, res) < 0) {
2243                 free(buf);
2244                 free(buf2);
2245                 return NS_NOTFOUND;
2246         }
2247         /* prefer IPv6 */
2248         if (q.next) {
2249                 ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai, res);
2250                 if (ai) {
2251                         cur->ai_next = ai;
2252                         while (cur && cur->ai_next)
2253                                 cur = cur->ai_next;
2254                 }
2255         }
2256         ai = getanswer(buf, q.n, q.name, q.qtype, pai, res);
2257         if (ai)
2258                 cur->ai_next = ai;
2259         free(buf);
2260         free(buf2);
2261         if (sentinel.ai_next == NULL)
2262                 switch (res->res_h_errno) {
2263                 case HOST_NOT_FOUND:
2264                         return NS_NOTFOUND;
2265                 case TRY_AGAIN:
2266                         return NS_TRYAGAIN;
2267                 default:
2268                         return NS_UNAVAIL;
2269                 }
2270         *((struct addrinfo **)rv) = sentinel.ai_next;
2271         return NS_SUCCESS;
2272 }
2273
2274 static void
2275 _sethtent(FILE **hostf)
2276 {
2277         if (!*hostf)
2278                 *hostf = fopen(_PATH_HOSTS, "r");
2279         else
2280                 rewind(*hostf);
2281 }
2282
2283 static void
2284 _endhtent(FILE **hostf)
2285 {
2286         if (*hostf) {
2287                 (void) fclose(*hostf);
2288                 *hostf = NULL;
2289         }
2290 }
2291
2292 static struct addrinfo *
2293 _gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
2294 {
2295         char *p;
2296         char *cp, *tname, *cname;
2297         struct addrinfo hints, *res0, *res;
2298         int error;
2299         const char *addr;
2300         char hostbuf[8*1024];
2301
2302         if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r")))
2303                 return (NULL);
2304 again:
2305         if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
2306                 return (NULL);
2307         if (*p == '#')
2308                 goto again;
2309         cp = strpbrk(p, "#\n");
2310         if (cp != NULL)
2311                 *cp = '\0';
2312         if (!(cp = strpbrk(p, " \t")))
2313                 goto again;
2314         *cp++ = '\0';
2315         addr = p;
2316         cname = NULL;
2317         /* if this is not something we're looking for, skip it. */
2318         while (cp && *cp) {
2319                 if (*cp == ' ' || *cp == '\t') {
2320                         cp++;
2321                         continue;
2322                 }
2323                 tname = cp;
2324                 if (cname == NULL)
2325                         cname = cp;
2326                 if ((cp = strpbrk(cp, " \t")) != NULL)
2327                         *cp++ = '\0';
2328                 if (strcasecmp(name, tname) == 0)
2329                         goto found;
2330         }
2331         goto again;
2332
2333 found:
2334         /* we should not glob socktype/protocol here */
2335         memset(&hints, 0, sizeof(hints));
2336         hints.ai_family = pai->ai_family;
2337         hints.ai_socktype = SOCK_DGRAM;
2338         hints.ai_protocol = 0;
2339         hints.ai_flags = AI_NUMERICHOST;
2340         error = getaddrinfo(addr, "0", &hints, &res0);
2341         if (error)
2342                 goto again;
2343 #ifdef FILTER_V4MAPPED
2344         /* XXX should check all items in the chain */
2345         if (res0->ai_family == AF_INET6 &&
2346             IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) {
2347                 freeaddrinfo(res0);
2348                 goto again;
2349         }
2350 #endif
2351         for (res = res0; res; res = res->ai_next) {
2352                 /* cover it up */
2353                 res->ai_flags = pai->ai_flags;
2354                 res->ai_socktype = pai->ai_socktype;
2355                 res->ai_protocol = pai->ai_protocol;
2356
2357                 if (pai->ai_flags & AI_CANONNAME) {
2358                         if (get_canonname(pai, res, cname) != 0) {
2359                                 freeaddrinfo(res0);
2360                                 goto again;
2361                         }
2362                 }
2363         }
2364         return res0;
2365 }
2366
2367 /*ARGSUSED*/
2368 static int
2369 _files_getaddrinfo(void *rv, void *cb_data, va_list ap)
2370 {
2371         const char *name;
2372         const struct addrinfo *pai;
2373         struct addrinfo sentinel, *cur;
2374         struct addrinfo *p;
2375         FILE *hostf = NULL;
2376
2377         name = va_arg(ap, char *);
2378         pai = va_arg(ap, struct addrinfo *);
2379
2380         memset(&sentinel, 0, sizeof(sentinel));
2381         cur = &sentinel;
2382
2383         _sethtent(&hostf);
2384         while ((p = _gethtent(&hostf, name, pai)) != NULL) {
2385                 cur->ai_next = p;
2386                 while (cur && cur->ai_next)
2387                         cur = cur->ai_next;
2388         }
2389         _endhtent(&hostf);
2390
2391         *((struct addrinfo **)rv) = sentinel.ai_next;
2392         if (sentinel.ai_next == NULL)
2393                 return NS_NOTFOUND;
2394         return NS_SUCCESS;
2395 }
2396
2397 #ifdef YP
2398 /*ARGSUSED*/
2399 static struct addrinfo *
2400 _yphostent(char *line, const struct addrinfo *pai)
2401 {
2402         struct addrinfo sentinel, *cur;
2403         struct addrinfo hints, *res, *res0;
2404         int error;
2405         char *p = line;
2406         const char *addr, *canonname;
2407         char *nextline;
2408         char *cp;
2409
2410         addr = canonname = NULL;
2411
2412         memset(&sentinel, 0, sizeof(sentinel));
2413         cur = &sentinel;
2414
2415 nextline:
2416         /* terminate line */
2417         cp = strchr(p, '\n');
2418         if (cp) {
2419                 *cp++ = '\0';
2420                 nextline = cp;
2421         } else
2422                 nextline = NULL;
2423
2424         cp = strpbrk(p, " \t");
2425         if (cp == NULL) {
2426                 if (canonname == NULL)
2427                         return (NULL);
2428                 else
2429                         goto done;
2430         }
2431         *cp++ = '\0';
2432
2433         addr = p;
2434
2435         while (cp && *cp) {
2436                 if (*cp == ' ' || *cp == '\t') {
2437                         cp++;
2438                         continue;
2439                 }
2440                 if (!canonname)
2441                         canonname = cp;
2442                 if ((cp = strpbrk(cp, " \t")) != NULL)
2443                         *cp++ = '\0';
2444         }
2445
2446         hints = *pai;
2447         hints.ai_flags = AI_NUMERICHOST;
2448         error = getaddrinfo(addr, NULL, &hints, &res0);
2449         if (error == 0) {
2450                 for (res = res0; res; res = res->ai_next) {
2451                         /* cover it up */
2452                         res->ai_flags = pai->ai_flags;
2453
2454                         if (pai->ai_flags & AI_CANONNAME)
2455                                 (void)get_canonname(pai, res, canonname);
2456                 }
2457         } else
2458                 res0 = NULL;
2459         if (res0) {
2460                 cur->ai_next = res0;
2461                 while (cur && cur->ai_next)
2462                         cur = cur->ai_next;
2463         }
2464
2465         if (nextline) {
2466                 p = nextline;
2467                 goto nextline;
2468         }
2469
2470 done:
2471         return sentinel.ai_next;
2472 }
2473
2474 /*ARGSUSED*/
2475 static int
2476 _yp_getaddrinfo(void *rv, void *cb_data, va_list ap)
2477 {
2478         struct addrinfo sentinel, *cur;
2479         struct addrinfo *ai = NULL;
2480         char *ypbuf;
2481         int ypbuflen, r;
2482         const char *name;
2483         const struct addrinfo *pai;
2484         char *ypdomain;
2485
2486         if (_yp_check(&ypdomain) == 0)
2487                 return NS_UNAVAIL;
2488
2489         name = va_arg(ap, char *);
2490         pai = va_arg(ap, const struct addrinfo *);
2491
2492         memset(&sentinel, 0, sizeof(sentinel));
2493         cur = &sentinel;
2494
2495         /* hosts.byname is only for IPv4 (Solaris8) */
2496         if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
2497                 r = yp_match(ypdomain, "hosts.byname", name,
2498                         (int)strlen(name), &ypbuf, &ypbuflen);
2499                 if (r == 0) {
2500                         struct addrinfo ai4;
2501
2502                         ai4 = *pai;
2503                         ai4.ai_family = AF_INET;
2504                         ai = _yphostent(ypbuf, &ai4);
2505                         if (ai) {
2506                                 cur->ai_next = ai;
2507                                 while (cur && cur->ai_next)
2508                                         cur = cur->ai_next;
2509                         }
2510                         free(ypbuf);
2511                 }
2512         }
2513
2514         /* ipnodes.byname can hold both IPv4/v6 */
2515         r = yp_match(ypdomain, "ipnodes.byname", name,
2516                 (int)strlen(name), &ypbuf, &ypbuflen);
2517         if (r == 0) {
2518                 ai = _yphostent(ypbuf, pai);
2519                 if (ai)
2520                         cur->ai_next = ai;
2521                 free(ypbuf);
2522         }
2523
2524         if (sentinel.ai_next == NULL) {
2525                 RES_SET_H_ERRNO(__res_state(), HOST_NOT_FOUND);
2526                 return NS_NOTFOUND;
2527         }
2528         *((struct addrinfo **)rv) = sentinel.ai_next;
2529         return NS_SUCCESS;
2530 }
2531 #endif
2532
2533 /* resolver logic */
2534
2535 /*
2536  * Formulate a normal query, send, and await answer.
2537  * Returned answer is placed in supplied buffer "answer".
2538  * Perform preliminary check of answer, returning success only
2539  * if no error is indicated and the answer count is nonzero.
2540  * Return the size of the response on success, -1 on error.
2541  * Error number is left in h_errno.
2542  *
2543  * Caller must parse answer and determine whether it answers the question.
2544  */
2545 static int
2546 res_queryN(const char *name, struct res_target *target, res_state res)
2547 {
2548         u_char *buf;
2549         HEADER *hp;
2550         int n;
2551         u_int oflags;
2552         struct res_target *t;
2553         int rcode;
2554         int ancount;
2555
2556         rcode = NOERROR;
2557         ancount = 0;
2558
2559         buf = malloc(MAXPACKET);
2560         if (!buf) {
2561                 RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2562                 return -1;
2563         }
2564
2565         for (t = target; t; t = t->next) {
2566                 int class, type;
2567                 u_char *answer;
2568                 int anslen;
2569
2570                 hp = (HEADER *)(void *)t->answer;
2571
2572                 /* make it easier... */
2573                 class = t->qclass;
2574                 type = t->qtype;
2575                 answer = t->answer;
2576                 anslen = t->anslen;
2577
2578                 oflags = res->_flags;
2579
2580 again:
2581                 hp->rcode = NOERROR;    /* default */
2582
2583 #ifdef DEBUG
2584                 if (res->options & RES_DEBUG)
2585                         printf(";; res_query(%s, %d, %d)\n", name, class, type);
2586 #endif
2587
2588                 n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
2589                     buf, MAXPACKET);
2590                 if (n > 0 && (res->_flags & RES_F_EDNS0ERR) == 0 &&
2591                     (res->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0U)
2592                         n = res_nopt(res, n, buf, MAXPACKET, anslen);
2593                 if (n <= 0) {
2594 #ifdef DEBUG
2595                         if (res->options & RES_DEBUG)
2596                                 printf(";; res_query: mkquery failed\n");
2597 #endif
2598                         free(buf);
2599                         RES_SET_H_ERRNO(res, NO_RECOVERY);
2600                         return (n);
2601                 }
2602                 n = res_nsend(res, buf, n, answer, anslen);
2603                 if (n < 0) {
2604                         /*
2605                          * if the query choked with EDNS0, retry
2606                          * without EDNS0
2607                          */
2608                         if ((res->options & (RES_USE_EDNS0|RES_USE_DNSSEC))
2609                             != 0U &&
2610                             ((oflags ^ res->_flags) & RES_F_EDNS0ERR) != 0) {
2611                                 res->_flags |= RES_F_EDNS0ERR;
2612                                 if (res->options & RES_DEBUG)
2613                                         printf(";; res_nquery: retry without EDNS0\n");
2614                                 goto again;
2615                         }
2616                         rcode = hp->rcode;      /* record most recent error */
2617 #ifdef DEBUG
2618                         if (res->options & RES_DEBUG)
2619                                 printf(";; res_query: send error\n");
2620 #endif
2621                         continue;
2622                 }
2623
2624                 if (n > anslen)
2625                         hp->rcode = FORMERR; /* XXX not very informative */
2626                 if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
2627                         rcode = hp->rcode;      /* record most recent error */
2628 #ifdef DEBUG
2629                         if (res->options & RES_DEBUG)
2630                                 printf(";; rcode = %u, ancount=%u\n", hp->rcode,
2631                                     ntohs(hp->ancount));
2632 #endif
2633                         continue;
2634                 }
2635
2636                 ancount += ntohs(hp->ancount);
2637
2638                 t->n = n;
2639         }
2640
2641         free(buf);
2642
2643         if (ancount == 0) {
2644                 switch (rcode) {
2645                 case NXDOMAIN:
2646                         RES_SET_H_ERRNO(res, HOST_NOT_FOUND);
2647                         break;
2648                 case SERVFAIL:
2649                         RES_SET_H_ERRNO(res, TRY_AGAIN);
2650                         break;
2651                 case NOERROR:
2652                         RES_SET_H_ERRNO(res, NO_DATA);
2653                         break;
2654                 case FORMERR:
2655                 case NOTIMP:
2656                 case REFUSED:
2657                 default:
2658                         RES_SET_H_ERRNO(res, NO_RECOVERY);
2659                         break;
2660                 }
2661                 return (-1);
2662         }
2663         return (ancount);
2664 }
2665
2666 /*
2667  * Formulate a normal query, send, and retrieve answer in supplied buffer.
2668  * Return the size of the response on success, -1 on error.
2669  * If enabled, implement search rules until answer or unrecoverable failure
2670  * is detected.  Error code, if any, is left in h_errno.
2671  */
2672 static int
2673 res_searchN(const char *name, struct res_target *target, res_state res)
2674 {
2675         const char *cp, * const *domain;
2676         HEADER *hp = (HEADER *)(void *)target->answer;  /*XXX*/
2677         u_int dots;
2678         int trailing_dot, ret, saved_herrno;
2679         int got_nodata = 0, got_servfail = 0, root_on_list = 0;
2680         int tried_as_is = 0;
2681         int searched = 0;
2682         char abuf[MAXDNAME];
2683
2684         errno = 0;
2685         RES_SET_H_ERRNO(res, HOST_NOT_FOUND); /* default, if we never query */
2686         dots = 0;
2687         for (cp = name; *cp; cp++)
2688                 dots += (*cp == '.');
2689         trailing_dot = 0;
2690         if (cp > name && *--cp == '.')
2691                 trailing_dot++;
2692
2693         /*
2694          * if there aren't any dots, it could be a user-level alias
2695          */
2696         if (!dots &&
2697             (cp = res_hostalias(res, name, abuf, sizeof(abuf))) != NULL)
2698                 return (res_queryN(cp, target, res));
2699
2700         /*
2701          * If there are enough dots in the name, let's just give it a
2702          * try 'as is'. The threshold can be set with the "ndots" option.
2703          * Also, query 'as is', if there is a trailing dot in the name.
2704          */
2705         saved_herrno = -1;
2706         if (dots >= res->ndots || trailing_dot) {
2707                 ret = res_querydomainN(name, NULL, target, res);
2708                 if (ret > 0 || trailing_dot)
2709                         return (ret);
2710                 if (errno == ECONNREFUSED) {
2711                         RES_SET_H_ERRNO(res, TRY_AGAIN);
2712                         return (-1);
2713                 }
2714                 switch (res->res_h_errno) {
2715                 case NO_DATA:
2716                 case HOST_NOT_FOUND:
2717                         break;
2718                 case TRY_AGAIN:
2719                         if (hp->rcode == SERVFAIL)
2720                                 break;
2721                         /* FALLTHROUGH */
2722                 default:
2723                         return (-1);
2724                 }
2725                 saved_herrno = res->res_h_errno;
2726                 tried_as_is++;
2727         }
2728
2729         /*
2730          * We do at least one level of search if
2731          *      - there is no dot and RES_DEFNAME is set, or
2732          *      - there is at least one dot, there is no trailing dot,
2733          *        and RES_DNSRCH is set.
2734          */
2735         if ((!dots && (res->options & RES_DEFNAMES)) ||
2736             (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
2737                 int done = 0;
2738
2739                 for (domain = (const char * const *)res->dnsrch;
2740                    *domain && !done;
2741                    domain++) {
2742                         searched = 1;
2743
2744                         if (domain[0][0] == '\0' ||
2745                             (domain[0][0] == '.' && domain[0][1] == '\0'))
2746                                 root_on_list++;
2747
2748                         if (root_on_list && tried_as_is)
2749                                 continue;
2750
2751                         ret = res_querydomainN(name, *domain, target, res);
2752                         if (ret > 0)
2753                                 return (ret);
2754
2755                         /*
2756                          * If no server present, give up.
2757                          * If name isn't found in this domain,
2758                          * keep trying higher domains in the search list
2759                          * (if that's enabled).
2760                          * On a NO_DATA error, keep trying, otherwise
2761                          * a wildcard entry of another type could keep us
2762                          * from finding this entry higher in the domain.
2763                          * If we get some other error (negative answer or
2764                          * server failure), then stop searching up,
2765                          * but try the input name below in case it's
2766                          * fully-qualified.
2767                          */
2768                         if (errno == ECONNREFUSED) {
2769                                 RES_SET_H_ERRNO(res, TRY_AGAIN);
2770                                 return (-1);
2771                         }
2772
2773                         switch (res->res_h_errno) {
2774                         case NO_DATA:
2775                                 got_nodata++;
2776                                 /* FALLTHROUGH */
2777                         case HOST_NOT_FOUND:
2778                                 /* keep trying */
2779                                 break;
2780                         case TRY_AGAIN:
2781                                 got_servfail++;
2782                                 if (hp->rcode == SERVFAIL) {
2783                                         /* try next search element, if any */
2784                                         break;
2785                                 }
2786                                 /* FALLTHROUGH */
2787                         default:
2788                                 /* anything else implies that we're done */
2789                                 done++;
2790                         }
2791                         /*
2792                          * if we got here for some reason other than DNSRCH,
2793                          * we only wanted one iteration of the loop, so stop.
2794                          */
2795                         if (!(res->options & RES_DNSRCH))
2796                                 done++;
2797                 }
2798         }
2799
2800         switch (res->res_h_errno) {
2801         case NO_DATA:
2802         case HOST_NOT_FOUND:
2803                 break;
2804         case TRY_AGAIN:
2805                 if (hp->rcode == SERVFAIL)
2806                         break;
2807                 /* FALLTHROUGH */
2808         default:
2809                 goto giveup;
2810         }
2811
2812         /*
2813          * If the query has not already been tried as is then try it
2814          * unless RES_NOTLDQUERY is set and there were no dots.
2815          */
2816         if ((dots || !searched || !(res->options & RES_NOTLDQUERY)) &&
2817             !(tried_as_is || root_on_list)) {
2818                 ret = res_querydomainN(name, NULL, target, res);
2819                 if (ret > 0)
2820                         return (ret);
2821         }
2822
2823         /*
2824          * if we got here, we didn't satisfy the search.
2825          * if we did an initial full query, return that query's h_errno
2826          * (note that we wouldn't be here if that query had succeeded).
2827          * else if we ever got a nodata, send that back as the reason.
2828          * else send back meaningless h_errno, that being the one from
2829          * the last DNSRCH we did.
2830          */
2831 giveup:
2832         if (saved_herrno != -1)
2833                 RES_SET_H_ERRNO(res, saved_herrno);
2834         else if (got_nodata)
2835                 RES_SET_H_ERRNO(res, NO_DATA);
2836         else if (got_servfail)
2837                 RES_SET_H_ERRNO(res, TRY_AGAIN);
2838         return (-1);
2839 }
2840
2841 /*
2842  * Perform a call on res_query on the concatenation of name and domain,
2843  * removing a trailing dot from name if domain is NULL.
2844  */
2845 static int
2846 res_querydomainN(const char *name, const char *domain,
2847     struct res_target *target, res_state res)
2848 {
2849         char nbuf[MAXDNAME];
2850         const char *longname = nbuf;
2851         size_t n, d;
2852
2853 #ifdef DEBUG
2854         if (res->options & RES_DEBUG)
2855                 printf(";; res_querydomain(%s, %s)\n",
2856                         name, domain?domain:"<Nil>");
2857 #endif
2858         if (domain == NULL) {
2859                 /*
2860                  * Check for trailing '.';
2861                  * copy without '.' if present.
2862                  */
2863                 n = strlen(name);
2864                 if (n >= MAXDNAME) {
2865                         RES_SET_H_ERRNO(res, NO_RECOVERY);
2866                         return (-1);
2867                 }
2868                 if (n > 0 && name[--n] == '.') {
2869                         strncpy(nbuf, name, n);
2870                         nbuf[n] = '\0';
2871                 } else
2872                         longname = name;
2873         } else {
2874                 n = strlen(name);
2875                 d = strlen(domain);
2876                 if (n + d + 1 >= MAXDNAME) {
2877                         RES_SET_H_ERRNO(res, NO_RECOVERY);
2878                         return (-1);
2879                 }
2880                 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2881         }
2882         return (res_queryN(longname, target, res));
2883 }