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