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