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