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