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