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