Check for SYS/GL during library init. Reason is that
[AROS.git] / workbench / network / stacks / AROSTCP / bsdsocket / api / getaddrinfo.c
blobfa14958c738f1a4f403fcc26fc81f85410765e14
1 /* $KAME: getaddrinfo.c,v 1.0 2005/11/14 12:57:24 sonic Exp $ */
3 /*
4 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5 * All rights reserved.
6 * Copyright (C) 2005 - 2006 Pavel Fedin
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the project nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
34 * "#ifdef FAITH" part is local hack for supporting IPv4-v6 translator.
36 * Issues to be discussed:
37 * - Thread safe-ness must be checked.
38 * - Return values. There are nonstandard return values defined and used
39 * in the source code. This is because RFC2553 is silent about which error
40 * code must be returned for which situation.
41 * - freeaddrinfo(NULL). RFC2553 is silent about it. XNET 5.2 says it is
42 * invalid. current code - SEGV on freeaddrinfo(NULL)
44 * Note:
45 * - The code filters out AFs that are not supported by the kernel,
46 * when globbing NULL hostname (to loopback, or wildcard). Is it the right
47 * thing to do? What is the relationship with post-RFC2553 AI_ADDRCONFIG
48 * in ai_flags?
49 * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
50 * (1) what should we do against numeric hostname (2) what should we do
51 * against NULL hostname (3) what is AI_ADDRCONFIG itself. AF not ready?
52 * non-loopback address configured? global address configured?
54 * OS specific notes for netbsd/openbsd/freebsd4/bsdi4:
55 * - To avoid search order issue, we have a big amount of code duplicate
56 * from gethnamaddr.c and some other places. The issues that there's no
57 * lower layer function to lookup "IPv4 or IPv6" record. Calling
58 * gethostbyname2 from getaddrinfo will end up in wrong search order, as
59 * presented above.
61 * OS specific notes for freebsd4:
62 * - FreeBSD supported $GAI. The code does not.
63 * - FreeBSD allowed classful IPv4 numeric (127.1), the code does not.
66 #include <amitcp/socketbasetags.h>
67 //#include <emul/emulregs.h>
68 //#include <libraries/eztcp_private.h>
69 #define SYSTEM_PRIVATE
70 #define USE_INLINE_STDARG
71 #include <proto/socket.h>
73 #include <sys/cdefs.h>
74 //#include "namespace.h"
75 #include <sys/types.h>
76 #include <sys/param.h>
77 #include <sys/socket.h>
78 #include <net/if.h>
79 #include <netinet/in.h>
80 #include <sys/queue.h>
81 #ifdef INET6
82 #include <net/if_var.h>
83 #include <sys/sysctl.h>
84 #include <sys/ioctl.h>
85 #include <netinet6/in6_var.h> /* XXX */
86 #endif
87 #include <arpa/inet.h>
88 #include <arpa/nameser.h>
89 #include <rpc/rpc.h>
90 #include <rpcsvc/yp_prot.h>
91 #include <rpcsvc/ypclnt.h>
92 #include <netdb.h>
93 #include <pthread.h>
94 #include <resolv.h>
95 #include <string.h>
96 #include <stdlib.h>
97 #include <stddef.h>
98 #include <ctype.h>
99 #include <unistd.h>
100 #include <stdio.h>
101 #include <errno.h>
103 //#include "res_config.h"
105 #ifdef DEBUG
106 #include <syslog.h>
107 #endif
109 #include <stdarg.h>
110 #include <nsswitch.h>
111 //#include "un-namespace.h"
112 //#include "libc_private.h"
113 #include "miami.h"
115 #if defined(__KAME__) && defined(INET6)
116 # define FAITH
117 #endif
119 #define SUCCESS 0
120 #define ANY 0
121 #define YES 1
122 #define NO 0
124 static const char in_addrany[] = { 0, 0, 0, 0 };
125 static const char in_loopback[] = { 127, 0, 0, 1 };
126 #ifdef INET6
127 static const char in6_addrany[] = {
128 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
130 static const char in6_loopback[] = {
131 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
133 #endif
135 struct policyqueue {
136 TAILQ_ENTRY(policyqueue) pc_entry;
137 #ifdef INET6
138 struct in6_addrpolicy pc_policy;
139 #endif
141 TAILQ_HEAD(policyhead, policyqueue);
143 static const struct afd {
144 int a_af;
145 int a_addrlen;
146 int a_socklen;
147 int a_off;
148 const char *a_addrany;
149 const char *a_loopback;
150 int a_scoped;
151 } afdl [] = {
152 #ifdef INET6
153 #define N_INET6 0
154 {PF_INET6, sizeof(struct in6_addr),
155 sizeof(struct sockaddr_in6),
156 offsetof(struct sockaddr_in6, sin6_addr),
157 in6_addrany, in6_loopback, 1},
158 #define N_INET 1
159 #else
160 #define N_INET 0
161 #endif
162 {PF_INET, sizeof(struct in_addr),
163 sizeof(struct sockaddr_in),
164 offsetof(struct sockaddr_in, sin_addr),
165 in_addrany, in_loopback, 0},
166 {0, 0, 0, 0, NULL, NULL, 0},
169 struct explore {
170 int e_af;
171 int e_socktype;
172 int e_protocol;
173 const char *e_protostr;
174 int e_wild;
175 #define WILD_AF(ex) ((ex)->e_wild & 0x01)
176 #define WILD_SOCKTYPE(ex) ((ex)->e_wild & 0x02)
177 #define WILD_PROTOCOL(ex) ((ex)->e_wild & 0x04)
180 static const struct explore explore[] = {
181 #if 0
182 { PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
183 #endif
184 #ifdef INET6
185 { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
186 { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
187 { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
188 #endif
189 { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
190 { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
191 { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
192 { PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
193 { PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
194 { PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
195 { -1, 0, 0, NULL, 0 },
198 #ifdef INET6
199 #define PTON_MAX 16
200 #else
201 #define PTON_MAX 4
202 #endif
204 #define AIO_SRCFLAG_DEPRECATED 0x1
206 struct ai_order {
207 union {
208 struct sockaddr_storage aiou_ss;
209 struct sockaddr aiou_sa;
210 } aio_src_un;
211 #define aio_srcsa aio_src_un.aiou_sa
212 u_int32_t aio_srcflag;
213 int aio_srcscope;
214 int aio_dstscope;
215 struct policyqueue *aio_srcpolicy;
216 struct policyqueue *aio_dstpolicy;
217 struct addrinfo *aio_ai;
218 int aio_matchlen;
221 struct res_target {
222 struct res_target *next;
223 const char *name; /* domain name */
224 int qclass, qtype; /* class and type of query */
225 u_char *answer; /* buffer to put answer */
226 int anslen; /* size of answer buffer */
227 int n; /* result length */
230 #define MAXPACKET (64*1024)
232 typedef union {
233 HEADER hdr;
234 u_char buf[MAXPACKET];
235 } querybuf;
237 static int str2number(const char *);
238 static int explore_null(const struct addrinfo *,
239 const char *, struct addrinfo **, struct MiamiBase *);
240 static int explore_numeric(const struct addrinfo *, const char *,
241 const char *, struct addrinfo **, const char *, struct MiamiBase *);
242 static int explore_numeric_scope(const struct addrinfo *, const char *,
243 const char *, struct addrinfo **, struct MiamiBase *);
244 static int get_canonname(const struct addrinfo *,
245 struct addrinfo *, const char *);
246 static struct addrinfo *get_ai(const struct addrinfo *,
247 const struct afd *, const char *, struct MiamiBase *);
248 static int get_portmatch(const struct addrinfo *, const char *, struct MiamiBase *);
249 static int get_port(struct addrinfo *, const char *, int, struct MiamiBase *);
250 static const struct afd *find_afd(int);
251 static int addrconfig(struct addrinfo *, MiamiBase *);
252 static void set_source(struct ai_order *, struct policyhead *, struct MiamiBase *);
253 static int comp_dst(const void *, const void *);
254 #ifdef INET6
255 static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *, struct MiamiBase *);
256 #endif
257 static int gai_addr2scopetype(struct sockaddr *);
259 static int explore_fqdn(const struct addrinfo *, const char *,
260 const char *, struct addrinfo **, struct MiamiBase *);
262 static int reorder(struct addrinfo *, struct MiamiBase *);
263 static int get_addrselectpolicy(struct policyhead *, struct MiamiBase *);
264 static void free_addrselectpolicy(struct policyhead *);
265 static struct policyqueue *match_addrselectpolicy(struct sockaddr *,
266 struct policyhead *);
267 static int matchlen(struct sockaddr *, struct sockaddr *);
269 static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
270 const struct addrinfo *, struct MiamiBase *);
271 #if defined(RESOLVSORT)
272 static int addr4sort(struct addrinfo *, struct MiamiBase *);
273 #endif
274 static int _dns_getaddrinfo(void *, void *, va_list, struct MiamiBase *);
275 /*static struct addrinfo *gethtent(const char *, const struct addrinfo *);*/
276 static int _files_getaddrinfo(void *, void *, va_list, struct MiamiBase *);
277 #ifdef YP
278 static struct addrinfo *_yphostent(char *, const struct addrinfo *, struct MiamiBase *);
279 static int _yp_getaddrinfo(void *, void *, va_list, struct MiamiBase *);
280 #endif
281 static int _nsdispatch(void *, struct MiamiBase *, ...);
283 static int res_queryN(const char *, struct res_target *, struct MiamiBase *);
284 static int res_searchN(const char *, struct res_target *, struct MiamiBase *);
285 static int res_querydomainN(const char *, const char *,
286 struct res_target *, struct MiamiBase *);
288 static struct ai_errlist {
289 const char *str;
290 int code;
291 } ai_errlist[] = {
292 { "Success", 0, },
293 { "Temporary failure in name resolution", EAI_AGAIN, },
294 { "Invalid value for ai_flags", EAI_BADFLAGS, },
295 { "Non-recoverable failure in name resolution", EAI_FAIL, },
296 { "ai_family not supported", EAI_FAMILY, },
297 { "Memory allocation failure", EAI_MEMORY, },
298 { "hostname nor servname provided, or not known", EAI_NONAME, },
299 { "servname not supported for ai_socktype", EAI_SERVICE, },
300 { "ai_socktype not supported", EAI_SOCKTYPE, },
301 { "System error returned in errno", EAI_SYSTEM, },
302 { "Invalid value for hints", EAI_BADHINTS, },
303 { "Resolved protocol is unknown", EAI_PROTOCOL, },
304 /* backward compatibility with userland code prior to 2553bis-02 */
305 { "Address family for hostname not supported", 1, },
306 { "No address associated with hostname", 7, },
307 { NULL, -1, },
310 /* XXX macros that make external reference is BAD. */
312 #define GET_AI(ai, afd, addr) \
313 do { \
314 /* external reference: pai, error, and label free */ \
315 (ai) = get_ai(pai, (afd), (addr), MiamiBase); \
316 if ((ai) == NULL) { \
317 error = EAI_MEMORY; \
318 goto free; \
320 } while (/*CONSTCOND*/0)
322 #define GET_PORT(ai, serv) \
323 do { \
324 /* external reference: error and label free */ \
325 error = get_port((ai), (serv), 0, MiamiBase); \
326 if (error != 0) \
327 goto free; \
328 } while (/*CONSTCOND*/0)
330 #define GET_CANONNAME(ai, str) \
331 do { \
332 /* external reference: pai, error and label free */ \
333 error = get_canonname(pai, (ai), (str)); \
334 if (error != 0) \
335 goto free; \
336 } while (/*CONSTCOND*/0)
338 #define ERR(err) \
339 do { \
340 /* external reference: error, and label bad */ \
341 error = (err); \
342 goto bad; \
343 /*NOTREACHED*/ \
344 } while (/*CONSTCOND*/0)
346 #define MATCH_FAMILY(x, y, w) \
347 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
348 #define MATCH(x, y, w) \
349 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
351 #define SocketBase MiamiBase->SocketBase
352 #define _res (*(MiamiBase->res_state))
354 char *
355 gai_strerror(void)
357 int ecode = REG_D0;
358 struct ai_errlist *p;
360 for (p = ai_errlist; p->str; p++) {
361 if (p->code == ecode)
362 return (char *)p->str;
364 return "Unknown error";
367 void
368 __freeaddrinfo(ai)
369 struct addrinfo *ai;
371 struct addrinfo *next;
373 do {
374 next = ai->ai_next;
375 if (ai->ai_canonname)
376 free(ai->ai_canonname);
377 /* no need to free(ai->ai_addr) */
378 free(ai);
379 ai = next;
380 } while (ai);
383 void freeaddrinfo(void)
385 struct addrinfo *ai = (struct addrinfo *)REG_A0;
387 __freeaddrinfo(ai);
390 static int
391 str2number(p)
392 const char *p;
394 char *ep;
395 unsigned long v;
396 int errno;
398 if (*p == '\0')
399 return -1;
400 ep = NULL;
401 errno = 0;
402 v = __strtoul(p, &ep, 10, &errno);
403 SocketBaseTags(SBTM_SETVAL(SBTC_ERRNO),errno,TAG_DONE);
404 if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX)
405 return v;
406 else
407 return -1;
411 __getaddrinfo(hostname, servname, hints, res, MiamiBase)
412 const char *hostname, *servname;
413 const struct addrinfo *hints;
414 struct addrinfo **res;
415 struct MiamiBase *MiamiBase;
417 struct addrinfo sentinel;
418 struct addrinfo *cur;
419 int error = 0;
420 struct addrinfo ai;
421 struct addrinfo ai0;
422 struct addrinfo *pai;
423 const struct explore *ex;
424 int numeric = 0;
426 memset(&sentinel, 0, sizeof(sentinel));
427 cur = &sentinel;
428 pai = &ai;
429 pai->ai_flags = 0;
430 pai->ai_family = PF_UNSPEC;
431 pai->ai_socktype = ANY;
432 pai->ai_protocol = ANY;
433 pai->ai_addrlen = 0;
434 pai->ai_canonname = NULL;
435 pai->ai_addr = NULL;
436 pai->ai_next = NULL;
438 if (hostname == NULL && servname == NULL)
439 return EAI_NONAME;
440 if (hints) {
441 /* error check for hints */
442 if (hints->ai_addrlen || hints->ai_canonname ||
443 hints->ai_addr || hints->ai_next)
444 ERR(EAI_BADHINTS); /* xxx */
445 if (hints->ai_flags & ~AI_MASK)
446 ERR(EAI_BADFLAGS);
447 switch (hints->ai_family) {
448 case PF_UNSPEC:
449 case PF_INET:
450 #ifdef INET6
451 case PF_INET6:
452 #endif
453 break;
454 default:
455 ERR(EAI_FAMILY);
457 memcpy(pai, hints, sizeof(*pai));
460 * if both socktype/protocol are specified, check if they
461 * are meaningful combination.
463 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
464 for (ex = explore; ex->e_af >= 0; ex++) {
465 if (pai->ai_family != ex->e_af)
466 continue;
467 if (ex->e_socktype == ANY)
468 continue;
469 if (ex->e_protocol == ANY)
470 continue;
471 if (pai->ai_socktype == ex->e_socktype &&
472 pai->ai_protocol != ex->e_protocol) {
473 ERR(EAI_BADHINTS);
480 * post-2553: AI_ALL and AI_V4MAPPED are effective only against
481 * AF_INET6 query. They need to be ignored if specified in other
482 * occassions.
484 switch (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) {
485 case AI_V4MAPPED:
486 case AI_ALL | AI_V4MAPPED:
487 if (pai->ai_family != AF_INET6)
488 pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
489 break;
490 case AI_ALL:
491 #if 1
492 /* illegal */
493 ERR(EAI_BADFLAGS);
494 #else
495 pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
496 #endif
497 break;
501 * check for special cases. (1) numeric servname is disallowed if
502 * socktype/protocol are left unspecified. (2) servname is disallowed
503 * for raw and other inet{,6} sockets.
505 if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
506 #ifdef PF_INET6
507 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
508 #endif
510 ai0 = *pai; /* backup *pai */
512 if (pai->ai_family == PF_UNSPEC) {
513 #ifdef PF_INET6
514 pai->ai_family = PF_INET6;
515 #else
516 pai->ai_family = PF_INET;
517 #endif
519 error = get_portmatch(pai, servname, MiamiBase);
520 if (error)
521 ERR(error);
523 *pai = ai0;
526 ai0 = *pai;
528 /* NULL hostname, or numeric hostname */
529 for (ex = explore; ex->e_af >= 0; ex++) {
530 *pai = ai0;
532 /* PF_UNSPEC entries are prepared for DNS queries only */
533 if (ex->e_af == PF_UNSPEC)
534 continue;
536 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
537 continue;
538 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
539 continue;
540 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
541 continue;
543 if (pai->ai_family == PF_UNSPEC)
544 pai->ai_family = ex->e_af;
545 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
546 pai->ai_socktype = ex->e_socktype;
547 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
548 pai->ai_protocol = ex->e_protocol;
550 if (hostname == NULL)
551 error = explore_null(pai, servname, &cur->ai_next, MiamiBase);
552 else
553 error = explore_numeric_scope(pai, hostname, servname,
554 &cur->ai_next, MiamiBase);
556 if (error)
557 goto free;
559 while (cur && cur->ai_next)
560 cur = cur->ai_next;
564 * XXX
565 * If numreic representation of AF1 can be interpreted as FQDN
566 * representation of AF2, we need to think again about the code below.
568 if (sentinel.ai_next) {
569 numeric = 1;
570 goto good;
573 if (hostname == NULL)
574 ERR(EAI_NONAME); /* used to be EAI_NODATA */
575 if (pai->ai_flags & AI_NUMERICHOST)
576 ERR(EAI_NONAME);
578 if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(&ai0, MiamiBase))
579 ERR(EAI_FAIL);
582 * hostname as alphabetical name.
583 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
584 * outer loop by AFs.
586 for (ex = explore; ex->e_af >= 0; ex++) {
587 *pai = ai0;
589 /* require exact match for family field */
590 if (pai->ai_family != ex->e_af)
591 continue;
593 if (!MATCH(pai->ai_socktype, ex->e_socktype,
594 WILD_SOCKTYPE(ex))) {
595 continue;
597 if (!MATCH(pai->ai_protocol, ex->e_protocol,
598 WILD_PROTOCOL(ex))) {
599 continue;
602 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
603 pai->ai_socktype = ex->e_socktype;
604 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
605 pai->ai_protocol = ex->e_protocol;
607 error = explore_fqdn(pai, hostname, servname,
608 &cur->ai_next, MiamiBase);
610 while (cur && cur->ai_next)
611 cur = cur->ai_next;
614 /* XXX inhibit errors if we have the result */
615 if (sentinel.ai_next)
616 error = 0;
618 good:
620 * ensure we return either:
621 * - error == 0, non-NULL *res
622 * - error != 0, NULL *res
624 if (error == 0) {
625 if (sentinel.ai_next) {
627 * If the returned entry is for an active connection,
628 * and the given name is not numeric, reorder the
629 * list, so that the application would try the list
630 * in the most efficient order.
632 if (hints == NULL || !(hints->ai_flags & AI_PASSIVE)) {
633 if (!numeric)
634 (void)reorder(&sentinel, MiamiBase);
636 *res = sentinel.ai_next;
637 return SUCCESS;
638 } else
639 error = EAI_FAIL;
641 free:
642 bad:
643 if (sentinel.ai_next)
644 __freeaddrinfo(sentinel.ai_next);
645 *res = NULL;
646 return error;
649 int getaddrinfo(void)
651 const char *hostname = (const char *)REG_A0;
652 const char *servname = (const char *)REG_A1;
653 const struct addrinfo *hints = (const struct addrinfo *)REG_A2;
654 struct addrinfo **res = (struct addrinfo **)REG_A3;
655 struct MiamiBase *MiamiBase = (struct MiamiBase *)REG_A6;
657 return __getaddrinfo(hostname, servname, hints, res, MiamiBase);
660 static int
661 reorder(sentinel, MiamiBase)
662 struct addrinfo *sentinel;
663 struct MiamiBase *MiamiBase;
665 struct addrinfo *ai, **aip;
666 struct ai_order *aio;
667 int i, n;
668 struct policyhead policyhead;
670 /* count the number of addrinfo elements for sorting. */
671 for (n = 0, ai = sentinel->ai_next; ai != NULL; ai = ai->ai_next, n++)
675 * If the number is small enough, we can skip the reordering process.
677 if (n <= 1)
678 return(n);
680 /* allocate a temporary array for sort and initialization of it. */
681 if ((aio = malloc(sizeof(*aio) * n)) == NULL)
682 return(n); /* give up reordering */
683 memset(aio, 0, sizeof(*aio) * n);
685 /* retrieve address selection policy from the kernel */
686 TAILQ_INIT(&policyhead);
687 if (!get_addrselectpolicy(&policyhead, MiamiBase)) {
688 /* no policy is installed into kernel, we don't sort. */
689 free(aio);
690 return (n);
693 for (i = 0, ai = sentinel->ai_next; i < n; ai = ai->ai_next, i++) {
694 aio[i].aio_ai = ai;
695 aio[i].aio_dstscope = gai_addr2scopetype(ai->ai_addr);
696 aio[i].aio_dstpolicy = match_addrselectpolicy(ai->ai_addr,
697 &policyhead);
698 set_source(&aio[i], &policyhead, MiamiBase);
701 /* perform sorting. */
702 qsort(aio, n, sizeof(*aio), comp_dst);
704 /* reorder the addrinfo chain. */
705 for (i = 0, aip = &sentinel->ai_next; i < n; i++) {
706 *aip = aio[i].aio_ai;
707 aip = &aio[i].aio_ai->ai_next;
709 *aip = NULL;
711 /* cleanup and return */
712 free(aio);
713 free_addrselectpolicy(&policyhead);
714 return(n);
717 static int
718 get_addrselectpolicy(head, MiamiBase)
719 struct policyhead *head;
720 struct MiamiBase *MiamiBase;
722 #ifdef INET6
723 int mib[] = { CTL_NET, PF_INET6, IPPROTO_IPV6, IPV6CTL_ADDRCTLPOLICY };
724 size_t l;
725 char *buf;
726 struct in6_addrpolicy *pol, *ep;
728 if (EZTCP_sysctl(mib, sizeof(mib) / sizeof(mib[0]), NULL, &l, NULL, 0) < 0)
729 return (0);
730 if ((buf = malloc(l)) == NULL)
731 return (0);
732 if (EZTCP_sysctl(mib, sizeof(mib) / sizeof(mib[0]), buf, &l, NULL, 0) < 0) {
733 free(buf);
734 return (0);
737 ep = (struct in6_addrpolicy *)(buf + l);
738 for (pol = (struct in6_addrpolicy *)buf; pol + 1 <= ep; pol++) {
739 struct policyqueue *new;
741 if ((new = malloc(sizeof(*new))) == NULL) {
742 free_addrselectpolicy(head); /* make the list empty */
743 break;
745 new->pc_policy = *pol;
746 TAILQ_INSERT_TAIL(head, new, pc_entry);
749 free(buf);
750 return (1);
751 #else
752 return (0);
753 #endif
756 static void
757 free_addrselectpolicy(head)
758 struct policyhead *head;
760 struct policyqueue *ent, *nent;
762 for (ent = TAILQ_FIRST(head); ent; ent = nent) {
763 nent = TAILQ_NEXT(ent, pc_entry);
764 TAILQ_REMOVE(head, ent, pc_entry);
765 free(ent);
769 static struct policyqueue *
770 match_addrselectpolicy(addr, head)
771 struct sockaddr *addr;
772 struct policyhead *head;
774 #ifdef INET6
775 struct policyqueue *ent, *bestent = NULL;
776 struct in6_addrpolicy *pol;
777 int matchlen, bestmatchlen = -1;
778 u_char *mp, *ep, *k, *p, m;
779 struct sockaddr_in6 key;
781 switch(addr->sa_family) {
782 case AF_INET6:
783 key = *(struct sockaddr_in6 *)addr;
784 break;
785 case AF_INET:
786 /* convert the address into IPv4-mapped IPv6 address. */
787 memset(&key, 0, sizeof(key));
788 key.sin6_family = AF_INET6;
789 key.sin6_len = sizeof(key);
790 key.sin6_addr.s6_addr[10] = 0xff;
791 key.sin6_addr.s6_addr[11] = 0xff;
792 memcpy(&key.sin6_addr.s6_addr[12],
793 &((struct sockaddr_in *)addr)->sin_addr, 4);
794 break;
795 default:
796 return(NULL);
799 for (ent = TAILQ_FIRST(head); ent; ent = TAILQ_NEXT(ent, pc_entry)) {
800 pol = &ent->pc_policy;
801 matchlen = 0;
803 mp = (u_char *)&pol->addrmask.sin6_addr;
804 ep = mp + 16; /* XXX: scope field? */
805 k = (u_char *)&key.sin6_addr;
806 p = (u_char *)&pol->addr.sin6_addr;
807 for (; mp < ep && *mp; mp++, k++, p++) {
808 m = *mp;
809 if ((*k & m) != *p)
810 goto next; /* not match */
811 if (m == 0xff) /* short cut for a typical case */
812 matchlen += 8;
813 else {
814 while (m >= 0x80) {
815 matchlen++;
816 m <<= 1;
821 /* matched. check if this is better than the current best. */
822 if (matchlen > bestmatchlen) {
823 bestent = ent;
824 bestmatchlen = matchlen;
827 next:
828 continue;
831 return(bestent);
832 #else
833 return(NULL);
834 #endif
838 static void
839 set_source(aio, ph, MiamiBase)
840 struct ai_order *aio;
841 struct policyhead *ph;
842 struct MiamiBase *MiamiBase;
844 struct addrinfo ai = *aio->aio_ai;
845 struct sockaddr_storage ss;
846 int s, srclen;
848 /* set unspec ("no source is available"), just in case */
849 aio->aio_srcsa.sa_family = AF_UNSPEC;
850 aio->aio_srcscope = -1;
852 switch(ai.ai_family) {
853 case AF_INET:
854 #ifdef INET6
855 case AF_INET6:
856 #endif
857 break;
858 default: /* ignore unsupported AFs explicitly */
859 return;
862 /* XXX: make a dummy addrinfo to call connect() */
863 ai.ai_socktype = SOCK_DGRAM;
864 ai.ai_protocol = IPPROTO_UDP; /* is UDP too specific? */
865 ai.ai_next = NULL;
866 memset(&ss, 0, sizeof(ss));
867 memcpy(&ss, ai.ai_addr, ai.ai_addrlen);
868 ai.ai_addr = (struct sockaddr *)&ss;
869 get_port(&ai, "1", 0, MiamiBase);
871 /* open a socket to get the source address for the given dst */
872 if ((s = socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)) < 0)
873 return; /* give up */
874 if (connect(s, ai.ai_addr, ai.ai_addrlen) < 0)
875 goto cleanup;
876 srclen = ai.ai_addrlen;
877 if (getsockname(s, &aio->aio_srcsa, &srclen) < 0) {
878 aio->aio_srcsa.sa_family = AF_UNSPEC;
879 goto cleanup;
881 aio->aio_srcscope = gai_addr2scopetype(&aio->aio_srcsa);
882 aio->aio_srcpolicy = match_addrselectpolicy(&aio->aio_srcsa, ph);
883 aio->aio_matchlen = matchlen(&aio->aio_srcsa, aio->aio_ai->ai_addr);
884 #ifdef INET6
885 if (ai.ai_family == AF_INET6) {
886 struct in6_ifreq ifr6;
887 u_int32_t flags6;
889 /* XXX: interface name should not be hardcoded */
890 strncpy(ifr6.ifr_name, "lo0", sizeof(ifr6.ifr_name));
891 memset(&ifr6, 0, sizeof(ifr6));
892 memcpy(&ifr6.ifr_addr, ai.ai_addr, ai.ai_addrlen);
893 if (IoctlSocket(s, SIOCGIFAFLAG_IN6, &ifr6) == 0) {
894 flags6 = ifr6.ifr_ifru.ifru_flags6;
895 if ((flags6 & IN6_IFF_DEPRECATED))
896 aio->aio_srcflag |= AIO_SRCFLAG_DEPRECATED;
899 #endif
901 cleanup:
902 CloseSocket(s);
903 return;
906 static int
907 matchlen(src, dst)
908 struct sockaddr *src, *dst;
910 int match = 0;
911 u_char *s, *d;
912 u_char *lim, r;
913 int addrlen;
915 switch (src->sa_family) {
916 #ifdef INET6
917 case AF_INET6:
918 s = (u_char *)&((struct sockaddr_in6 *)src)->sin6_addr;
919 d = (u_char *)&((struct sockaddr_in6 *)dst)->sin6_addr;
920 addrlen = sizeof(struct in6_addr);
921 lim = s + addrlen;
922 break;
923 #endif
924 case AF_INET:
925 s = (u_char *)&((struct sockaddr_in6 *)src)->sin6_addr;
926 d = (u_char *)&((struct sockaddr_in6 *)dst)->sin6_addr;
927 addrlen = sizeof(struct in_addr);
928 lim = s + addrlen;
929 break;
930 default:
931 return(0);
934 while (s < lim)
935 if ((r = (*d++ ^ *s++)) != 0) {
936 while (r < addrlen * 8) {
937 match++;
938 r <<= 1;
940 break;
941 } else
942 match += 8;
943 return(match);
946 static int
947 comp_dst(arg1, arg2)
948 const void *arg1, *arg2;
950 const struct ai_order *dst1 = arg1, *dst2 = arg2;
953 * Rule 1: Avoid unusable destinations.
954 * XXX: we currently do not consider if an appropriate route exists.
956 if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
957 dst2->aio_srcsa.sa_family == AF_UNSPEC) {
958 return(-1);
960 if (dst1->aio_srcsa.sa_family == AF_UNSPEC &&
961 dst2->aio_srcsa.sa_family != AF_UNSPEC) {
962 return(1);
965 /* Rule 2: Prefer matching scope. */
966 if (dst1->aio_dstscope == dst1->aio_srcscope &&
967 dst2->aio_dstscope != dst2->aio_srcscope) {
968 return(-1);
970 if (dst1->aio_dstscope != dst1->aio_srcscope &&
971 dst2->aio_dstscope == dst2->aio_srcscope) {
972 return(1);
975 /* Rule 3: Avoid deprecated addresses. */
976 if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
977 dst2->aio_srcsa.sa_family != AF_UNSPEC) {
978 if (!(dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
979 (dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
980 return(-1);
982 if ((dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
983 !(dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
984 return(1);
988 /* Rule 4: Prefer home addresses. */
989 /* XXX: not implemented yet */
991 /* Rule 5: Prefer matching label. */
992 #ifdef INET6
993 if (dst1->aio_srcpolicy && dst1->aio_dstpolicy &&
994 dst1->aio_srcpolicy->pc_policy.label ==
995 dst1->aio_dstpolicy->pc_policy.label &&
996 (dst2->aio_srcpolicy == NULL || dst2->aio_dstpolicy == NULL ||
997 dst2->aio_srcpolicy->pc_policy.label !=
998 dst2->aio_dstpolicy->pc_policy.label)) {
999 return(-1);
1001 if (dst2->aio_srcpolicy && dst2->aio_dstpolicy &&
1002 dst2->aio_srcpolicy->pc_policy.label ==
1003 dst2->aio_dstpolicy->pc_policy.label &&
1004 (dst1->aio_srcpolicy == NULL || dst1->aio_dstpolicy == NULL ||
1005 dst1->aio_srcpolicy->pc_policy.label !=
1006 dst1->aio_dstpolicy->pc_policy.label)) {
1007 return(1);
1009 #endif
1011 /* Rule 6: Prefer higher precedence. */
1012 #ifdef INET6
1013 if (dst1->aio_dstpolicy &&
1014 (dst2->aio_dstpolicy == NULL ||
1015 dst1->aio_dstpolicy->pc_policy.preced >
1016 dst2->aio_dstpolicy->pc_policy.preced)) {
1017 return(-1);
1019 if (dst2->aio_dstpolicy &&
1020 (dst1->aio_dstpolicy == NULL ||
1021 dst2->aio_dstpolicy->pc_policy.preced >
1022 dst1->aio_dstpolicy->pc_policy.preced)) {
1023 return(1);
1025 #endif
1027 /* Rule 7: Prefer native transport. */
1028 /* XXX: not implemented yet */
1030 /* Rule 8: Prefer smaller scope. */
1031 if (dst1->aio_dstscope >= 0 &&
1032 dst1->aio_dstscope < dst2->aio_dstscope) {
1033 return(-1);
1035 if (dst2->aio_dstscope >= 0 &&
1036 dst2->aio_dstscope < dst1->aio_dstscope) {
1037 return(1);
1041 * Rule 9: Use longest matching prefix.
1042 * We compare the match length in a same AF only.
1044 if (dst1->aio_ai->ai_addr->sa_family ==
1045 dst2->aio_ai->ai_addr->sa_family) {
1046 if (dst1->aio_matchlen > dst2->aio_matchlen) {
1047 return(-1);
1049 if (dst1->aio_matchlen < dst2->aio_matchlen) {
1050 return(1);
1054 /* Rule 10: Otherwise, leave the order unchanged. */
1055 return(-1);
1059 * Copy from scope.c.
1060 * XXX: we should standardize the functions and link them as standard
1061 * library.
1063 static int
1064 gai_addr2scopetype(sa)
1065 struct sockaddr *sa;
1067 #ifdef INET6
1068 struct sockaddr_in6 *sa6;
1069 #endif
1070 struct sockaddr_in *sa4;
1072 switch(sa->sa_family) {
1073 #ifdef INET6
1074 case AF_INET6:
1075 sa6 = (struct sockaddr_in6 *)sa;
1076 if (IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
1077 /* just use the scope field of the multicast address */
1078 return(sa6->sin6_addr.s6_addr[2] & 0x0f);
1081 * Unicast addresses: map scope type to corresponding scope
1082 * value defined for multcast addresses.
1083 * XXX: hardcoded scope type values are bad...
1085 if (IN6_IS_ADDR_LOOPBACK(&sa6->sin6_addr))
1086 return(1); /* node local scope */
1087 if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr))
1088 return(2); /* link-local scope */
1089 if (IN6_IS_ADDR_SITELOCAL(&sa6->sin6_addr))
1090 return(5); /* site-local scope */
1091 return(14); /* global scope */
1092 break;
1093 #endif
1094 case AF_INET:
1096 * IPv4 pseudo scoping according to RFC 3484.
1098 sa4 = (struct sockaddr_in *)sa;
1099 /* IPv4 autoconfiguration addresses have link-local scope. */
1100 if (((u_char *)&sa4->sin_addr)[0] == 169 &&
1101 ((u_char *)&sa4->sin_addr)[1] == 254)
1102 return(2);
1103 /* Private addresses have site-local scope. */
1104 if (((u_char *)&sa4->sin_addr)[0] == 10 ||
1105 (((u_char *)&sa4->sin_addr)[0] == 172 &&
1106 (((u_char *)&sa4->sin_addr)[1] & 0xf0) == 16) ||
1107 (((u_char *)&sa4->sin_addr)[0] == 192 &&
1108 ((u_char *)&sa4->sin_addr)[1] == 168))
1109 return(14); /* XXX: It should be 5 unless NAT */
1110 /* Loopback addresses have link-local scope. */
1111 if (((u_char *)&sa4->sin_addr)[0] == 127)
1112 return(2);
1113 return(14);
1114 break;
1115 default:
1116 SocketBaseTags(SBTM_SETVAL(SBTC_ERRNO),EAFNOSUPPORT,TAG_DONE); /* is this a good error? */
1117 return(-1);
1122 * hostname == NULL.
1123 * passive socket -> anyaddr (0.0.0.0 or ::)
1124 * non-passive socket -> localhost (127.0.0.1 or ::1)
1126 static int
1127 explore_null(pai, servname, res, MiamiBase)
1128 const struct addrinfo *pai;
1129 const char *servname;
1130 struct addrinfo **res;
1131 struct MiamiBase *MiamiBase;
1133 int s;
1134 const struct afd *afd;
1135 struct addrinfo *cur;
1136 struct addrinfo sentinel;
1137 int error;
1139 *res = NULL;
1140 sentinel.ai_next = NULL;
1141 cur = &sentinel;
1144 * filter out AFs that are not supported by the kernel
1145 * XXX errno?
1147 s = socket(pai->ai_family, SOCK_DGRAM, 0);
1148 if (s < 0) {
1149 SocketBaseTags(SBTM_GETREF(SBTC_ERRNO),&error,TAG_DONE);
1150 if (error != EMFILE)
1151 return 0;
1152 } else
1153 CloseSocket(s);
1156 * if the servname does not match socktype/protocol, ignore it.
1158 if (get_portmatch(pai, servname, MiamiBase) != 0)
1159 return 0;
1161 afd = find_afd(pai->ai_family);
1162 if (afd == NULL)
1163 return 0;
1165 if (pai->ai_flags & AI_PASSIVE) {
1166 GET_AI(cur->ai_next, afd, afd->a_addrany);
1167 /* xxx meaningless?
1168 * GET_CANONNAME(cur->ai_next, "anyaddr");
1170 GET_PORT(cur->ai_next, servname);
1171 } else {
1172 GET_AI(cur->ai_next, afd, afd->a_loopback);
1173 /* xxx meaningless?
1174 * GET_CANONNAME(cur->ai_next, "localhost");
1176 GET_PORT(cur->ai_next, servname);
1178 cur = cur->ai_next;
1180 *res = sentinel.ai_next;
1181 return 0;
1183 free:
1184 if (sentinel.ai_next)
1185 __freeaddrinfo(sentinel.ai_next);
1186 return error;
1190 * numeric hostname
1192 static int
1193 explore_numeric(pai, hostname, servname, res, canonname, MiamiBase)
1194 const struct addrinfo *pai;
1195 const char *hostname;
1196 const char *servname;
1197 struct addrinfo **res;
1198 const char *canonname;
1199 struct MiamiBase *MiamiBase;
1201 const struct afd *afd;
1202 struct addrinfo *cur;
1203 struct addrinfo sentinel;
1204 int error;
1205 char pton[PTON_MAX];
1207 *res = NULL;
1208 sentinel.ai_next = NULL;
1209 cur = &sentinel;
1212 * if the servname does not match socktype/protocol, ignore it.
1214 if (get_portmatch(pai, servname, MiamiBase) != 0)
1215 return 0;
1217 afd = find_afd(pai->ai_family);
1218 if (afd == NULL)
1219 return 0;
1221 switch (afd->a_af) {
1222 #if 1 /*X/Open spec*/
1223 case AF_INET:
1224 if (__inet_aton(hostname, (struct in_addr *)pton) == 1) {
1225 if (pai->ai_family == afd->a_af ||
1226 pai->ai_family == PF_UNSPEC /*?*/) {
1227 GET_AI(cur->ai_next, afd, pton);
1228 GET_PORT(cur->ai_next, servname);
1229 if ((pai->ai_flags & AI_CANONNAME)) {
1231 * Set the numeric address itself as
1232 * the canonical name, based on a
1233 * clarification in rfc3493.
1235 GET_CANONNAME(cur->ai_next, canonname);
1237 while (cur && cur->ai_next)
1238 cur = cur->ai_next;
1239 } else
1240 ERR(EAI_FAMILY); /*xxx*/
1242 break;
1243 #endif
1244 default:
1245 if (__inet_pton(afd->a_af, hostname, pton, SocketBase) == 1) {
1246 if (pai->ai_family == afd->a_af ||
1247 pai->ai_family == PF_UNSPEC /*?*/) {
1248 GET_AI(cur->ai_next, afd, pton);
1249 GET_PORT(cur->ai_next, servname);
1250 if ((pai->ai_flags & AI_CANONNAME)) {
1252 * Set the numeric address itself as
1253 * the canonical name, based on a
1254 * clarification in rfc3493.
1256 GET_CANONNAME(cur->ai_next, canonname);
1258 while (cur && cur->ai_next)
1259 cur = cur->ai_next;
1260 } else
1261 ERR(EAI_FAMILY); /* XXX */
1263 break;
1266 *res = sentinel.ai_next;
1267 return 0;
1269 free:
1270 bad:
1271 if (sentinel.ai_next)
1272 __freeaddrinfo(sentinel.ai_next);
1273 return error;
1277 * numeric hostname with scope
1279 static int
1280 explore_numeric_scope(pai, hostname, servname, res, MiamiBase)
1281 const struct addrinfo *pai;
1282 const char *hostname;
1283 const char *servname;
1284 struct addrinfo **res;
1285 struct MiamiBase *MiamiBase;
1287 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
1288 return explore_numeric(pai, hostname, servname, res, hostname, MiamiBase);
1289 #else
1290 const struct afd *afd;
1291 struct addrinfo *cur;
1292 int error;
1293 char *cp, *hostname2 = NULL, *scope, *addr;
1294 struct sockaddr_in6 *sin6;
1297 * if the servname does not match socktype/protocol, ignore it.
1299 if (get_portmatch(pai, servname, MiamiBase) != 0)
1300 return 0;
1302 afd = find_afd(pai->ai_family);
1303 if (afd == NULL)
1304 return 0;
1306 if (!afd->a_scoped)
1307 return explore_numeric(pai, hostname, servname, res, hostname, MiamiBase);
1309 cp = strchr(hostname, SCOPE_DELIMITER);
1310 if (cp == NULL)
1311 return explore_numeric(pai, hostname, servname, res, hostname, MiamiBase);
1314 * Handle special case of <scoped_address><delimiter><scope id>
1316 hostname2 = strdup(hostname);
1317 if (hostname2 == NULL)
1318 return EAI_MEMORY;
1319 /* terminate at the delimiter */
1320 hostname2[cp - hostname] = '\0';
1321 addr = hostname2;
1322 scope = cp + 1;
1324 error = explore_numeric(pai, addr, servname, res, hostname, MiamiBase);
1325 if (error == 0) {
1326 u_int32_t scopeid;
1328 for (cur = *res; cur; cur = cur->ai_next) {
1329 if (cur->ai_family != AF_INET6)
1330 continue;
1331 sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
1332 if (ip6_str2scopeid(scope, sin6, &scopeid, MiamiBase) == -1) {
1333 free(hostname2);
1334 return(EAI_NONAME); /* XXX: is return OK? */
1336 sin6->sin6_scope_id = scopeid;
1340 free(hostname2);
1342 return error;
1343 #endif
1346 static int
1347 get_canonname(pai, ai, str)
1348 const struct addrinfo *pai;
1349 struct addrinfo *ai;
1350 const char *str;
1352 if ((pai->ai_flags & AI_CANONNAME) != 0) {
1353 ai->ai_canonname = strdup(str);
1354 if (ai->ai_canonname == NULL)
1355 return EAI_MEMORY;
1357 return 0;
1360 static struct addrinfo *
1361 get_ai(pai, afd, addr, MiamiBase)
1362 const struct addrinfo *pai;
1363 const struct afd *afd;
1364 const char *addr;
1365 struct MiamiBase *MiamiBase;
1367 char *p;
1368 struct addrinfo *ai;
1369 #ifdef FAITH
1370 struct in6_addr faith_prefix;
1371 char *fp_str;
1372 int translate = 0;
1373 #endif
1375 #ifdef FAITH
1377 * Transfrom an IPv4 addr into a special IPv6 addr format for
1378 * IPv6->IPv4 translation gateway. (only TCP is supported now)
1380 * +-----------------------------------+------------+
1381 * | faith prefix part (12 bytes) | embedded |
1382 * | | IPv4 addr part (4 bytes)
1383 * +-----------------------------------+------------+
1385 * faith prefix part is specified as ascii IPv6 addr format
1386 * in environmental variable GAI.
1387 * For FAITH to work correctly, routing to faith prefix must be
1388 * setup toward a machine where a FAITH daemon operates.
1389 * Also, the machine must enable some mechanizm
1390 * (e.g. faith interface hack) to divert those packet with
1391 * faith prefixed destination addr to user-land FAITH daemon.
1393 /* TODO: replace this getenv() with something that takes the value from ezTCP configuration */
1394 fp_str = getenv("GAI");
1395 if (fp_str && __inet_pton(AF_INET6, fp_str, &faith_prefix) == 1 &&
1396 afd->a_af == AF_INET && pai->ai_socktype == SOCK_STREAM, SocketBase) {
1397 u_int32_t v4a;
1398 u_int8_t v4a_top;
1400 memcpy(&v4a, addr, sizeof v4a);
1401 v4a_top = v4a >> IN_CLASSA_NSHIFT;
1402 if (!IN_MULTICAST(v4a) && !IN_EXPERIMENTAL(v4a) &&
1403 v4a_top != 0 && v4a != IN_LOOPBACKNET) {
1404 afd = &afdl[N_INET6];
1405 memcpy(&faith_prefix.s6_addr[12], addr,
1406 sizeof(struct in_addr));
1407 translate = 1;
1410 #endif
1412 ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
1413 + (afd->a_socklen));
1414 if (ai == NULL)
1415 return NULL;
1417 memcpy(ai, pai, sizeof(struct addrinfo));
1418 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1419 memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
1420 ai->ai_addr->sa_len = afd->a_socklen;
1421 ai->ai_addrlen = afd->a_socklen;
1422 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
1423 p = (char *)(void *)(ai->ai_addr);
1424 #ifdef FAITH
1425 if (translate == 1)
1426 memcpy(p + afd->a_off, &faith_prefix, (size_t)afd->a_addrlen);
1427 else
1428 #endif
1429 memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
1430 return ai;
1433 static int
1434 get_portmatch(ai, servname, MiamiBase)
1435 const struct addrinfo *ai;
1436 const char *servname;
1437 struct MiamiBase *MiamiBase;
1440 /* get_port does not touch first argument when matchonly == 1. */
1441 /* LINTED const cast */
1442 return get_port((struct addrinfo *)ai, servname, 1, MiamiBase);
1445 static int
1446 get_port(ai, servname, matchonly, MiamiBase)
1447 struct addrinfo *ai;
1448 const char *servname;
1449 int matchonly;
1450 struct MiamiBase *MiamiBase;
1452 const char *proto;
1453 struct servent *sp;
1454 int port;
1455 int allownumeric;
1457 if (servname == NULL)
1458 return 0;
1459 switch (ai->ai_family) {
1460 case AF_INET:
1461 #ifdef AF_INET6
1462 case AF_INET6:
1463 #endif
1464 break;
1465 default:
1466 return 0;
1469 switch (ai->ai_socktype) {
1470 case SOCK_RAW:
1471 return EAI_SERVICE;
1472 case SOCK_DGRAM:
1473 case SOCK_STREAM:
1474 allownumeric = 1;
1475 break;
1476 case ANY:
1477 allownumeric = 0;
1478 break;
1479 default:
1480 return EAI_SOCKTYPE;
1483 port = str2number(servname);
1484 if (port >= 0) {
1485 if (!allownumeric)
1486 return EAI_SERVICE;
1487 if (port < 0 || port > 65535)
1488 return EAI_SERVICE;
1489 port = htons(port);
1490 } else {
1491 if (ai->ai_flags & AI_NUMERICSERV)
1492 return EAI_NONAME;
1493 switch (ai->ai_socktype) {
1494 case SOCK_DGRAM:
1495 proto = "udp";
1496 break;
1497 case SOCK_STREAM:
1498 proto = "tcp";
1499 break;
1500 default:
1501 proto = NULL;
1502 break;
1504 if ((sp = getservbyname(servname, proto)) == NULL) {
1505 return EAI_SERVICE;
1507 port = sp->s_port;
1510 if (!matchonly) {
1511 switch (ai->ai_family) {
1512 case AF_INET:
1513 ((struct sockaddr_in *)(void *)
1514 ai->ai_addr)->sin_port = port;
1515 break;
1516 #ifdef INET6
1517 case AF_INET6:
1518 ((struct sockaddr_in6 *)(void *)
1519 ai->ai_addr)->sin6_port = port;
1520 break;
1521 #endif
1525 return 0;
1528 static const struct afd *
1529 find_afd(af)
1530 int af;
1532 const struct afd *afd;
1534 if (af == PF_UNSPEC)
1535 return NULL;
1536 for (afd = afdl; afd->a_af; afd++) {
1537 if (afd->a_af == af)
1538 return afd;
1540 return NULL;
1544 * post-2553: AI_ADDRCONFIG check. if we use getipnodeby* as backend, backend
1545 * will take care of it.
1546 * the semantics of AI_ADDRCONFIG is not defined well. we are not sure
1547 * if the code is right or not.
1549 * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with
1550 * _dns_getaddrinfo.
1552 static int
1553 addrconfig(pai, MiamiBase)
1554 struct addrinfo *pai;
1555 struct MiamiBase *MiamiBase;
1557 int s, af;
1560 * TODO:
1561 * Note that implementation dependent test for address
1562 * configuration should be done everytime called
1563 * (or apropriate interval),
1564 * because addresses will be dynamically assigned or deleted.
1566 af = pai->ai_family;
1567 if (af == AF_UNSPEC) {
1568 if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1569 af = AF_INET;
1570 else {
1571 CloseSocket(s);
1572 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1573 af = AF_INET6;
1574 else
1575 CloseSocket(s);
1578 if (af != AF_UNSPEC) {
1579 if ((s = socket(af, SOCK_DGRAM, 0)) < 0)
1580 return 0;
1581 CloseSocket(s);
1583 pai->ai_family = af;
1584 return 1;
1587 #ifdef INET6
1588 /* convert a string to a scope identifier. XXX: IPv6 specific */
1589 static int
1590 ip6_str2scopeid(scope, sin6, scopeid, MiamiBase)
1591 char *scope;
1592 struct sockaddr_in6 *sin6;
1593 u_int32_t *scopeid;
1594 struct MiamiBase *MiamiBase;
1596 u_long lscopeid;
1597 struct in6_addr *a6;
1598 char *ep;
1599 int errno;
1601 a6 = &sin6->sin6_addr;
1603 /* empty scopeid portion is invalid */
1604 if (*scope == '\0')
1605 return -1;
1607 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1609 * We currently assume a one-to-one mapping between links
1610 * and interfaces, so we simply use interface indices for
1611 * like-local scopes.
1613 *scopeid = __if_nametoindex(scope, SocketBase);
1614 if (*scopeid == 0)
1615 goto trynumeric;
1616 return 0;
1619 /* still unclear about literal, allow numeric only - placeholder */
1620 if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1621 goto trynumeric;
1622 if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1623 goto trynumeric;
1624 else
1625 goto trynumeric; /* global */
1627 /* try to convert to a numeric id as a last resort */
1628 trynumeric:
1629 errno = 0;
1630 lscopeid = __strtoul(scope, &ep, 10, &errno);
1631 SocketBaseTags(SBTM_SETVAL(SBTC_ERRNO),errno,TAG_DONE);
1632 *scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1633 if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1634 return 0;
1635 else
1636 return -1;
1638 #endif
1640 int _nsdispatch(void *retval, struct MiamiBase *MiamiBase, ...)
1642 va_list ap;
1643 int ret;
1645 va_start(ap, MiamiBase);
1646 if (MiamiBase->usens != 1) {
1647 if (_files_getaddrinfo(retval, NULL, ap, MiamiBase) == NS_SUCCESS) {
1648 va_end(ap);
1649 return NS_SUCCESS;
1652 ret = _dns_getaddrinfo(retval, NULL, ap, MiamiBase);
1653 if ((ret != NS_SUCCESS) && (MiamiBase->usens != 2))
1654 ret = _files_getaddrinfo(retval, NULL, ap, MiamiBase);
1655 va_end(ap);
1656 return ret;
1660 * FQDN hostname, DNS lookup
1662 static int
1663 explore_fqdn(pai, hostname, servname, res, MiamiBase)
1664 const struct addrinfo *pai;
1665 const char *hostname;
1666 const char *servname;
1667 struct addrinfo **res;
1668 struct MiamiBase *MiamiBase;
1670 struct addrinfo *result;
1671 struct addrinfo *cur;
1672 int error = 0;
1673 result = NULL;
1676 * if the servname does not match socktype/protocol, ignore it.
1678 if (get_portmatch(pai, servname, MiamiBase) != 0)
1679 return 0;
1681 switch (_nsdispatch(&result, MiamiBase, hostname, pai)) {
1682 case NS_TRYAGAIN:
1683 error = EAI_AGAIN;
1684 goto free;
1685 case NS_UNAVAIL:
1686 error = EAI_FAIL;
1687 goto free;
1688 case NS_NOTFOUND:
1689 error = EAI_NONAME;
1690 goto free;
1691 case NS_SUCCESS:
1692 error = 0;
1693 for (cur = result; cur; cur = cur->ai_next) {
1694 GET_PORT(cur, servname);
1695 /* canonname should be filled already */
1697 break;
1700 *res = result;
1702 return 0;
1704 free:
1705 if (result)
1706 __freeaddrinfo(result);
1707 return error;
1710 #ifdef DEBUG
1711 static const char AskedForGot[] =
1712 "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1713 #endif
1714 static FILE *hostf = NULL;
1716 static struct addrinfo *
1717 getanswer(answer, anslen, qname, qtype, pai, MiamiBase)
1718 const querybuf *answer;
1719 int anslen;
1720 const char *qname;
1721 int qtype;
1722 const struct addrinfo *pai;
1723 struct MiamiBase *MiamiBase;
1725 struct addrinfo sentinel, *cur;
1726 struct addrinfo ai;
1727 const struct afd *afd;
1728 char *canonname;
1729 const HEADER *hp;
1730 const u_char *cp;
1731 int n;
1732 const u_char *eom;
1733 char *bp, *ep;
1734 int type, class, ancount, qdcount;
1735 int haveanswer, had_error;
1736 char tbuf[MAXDNAME];
1737 int (*name_ok)(const char *);
1738 char hostbuf[8*1024];
1740 memset(&sentinel, 0, sizeof(sentinel));
1741 cur = &sentinel;
1743 canonname = NULL;
1744 eom = answer->buf + anslen;
1745 switch (qtype) {
1746 case T_A:
1747 case T_AAAA:
1748 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
1749 name_ok = res_hnok;
1750 break;
1751 default:
1752 return (NULL); /* XXX should be abort(); */
1755 * find first satisfactory answer
1757 hp = &answer->hdr;
1758 ancount = ntohs(hp->ancount);
1759 qdcount = ntohs(hp->qdcount);
1760 bp = hostbuf;
1761 ep = hostbuf + sizeof hostbuf;
1762 cp = answer->buf + HFIXEDSZ;
1763 if (qdcount != 1) {
1764 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),NO_DISCOVERY,TAG_DONE);
1765 return (NULL);
1767 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1768 if ((n < 0) || !(*name_ok)(bp)) {
1769 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),NO_RECOVERY,TAG_DONE);
1770 return (NULL);
1772 cp += n + QFIXEDSZ;
1773 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1774 /* res_send() has already verified that the query name is the
1775 * same as the one we sent; this just gets the expanded name
1776 * (i.e., with the succeeding search-domain tacked on).
1778 n = strlen(bp) + 1; /* for the \0 */
1779 if (n >= MAXHOSTNAMELEN) {
1780 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),NO_RECOVERY,TAG_DONE);
1781 return (NULL);
1783 canonname = bp;
1784 bp += n;
1785 /* The qname can be abbreviated, but h_name is now absolute. */
1786 qname = canonname;
1788 haveanswer = 0;
1789 had_error = 0;
1790 while (ancount-- > 0 && cp < eom && !had_error) {
1791 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1792 if ((n < 0) || !(*name_ok)(bp)) {
1793 had_error++;
1794 continue;
1796 cp += n; /* name */
1797 type = _getshort(cp);
1798 cp += INT16SZ; /* type */
1799 class = _getshort(cp);
1800 cp += INT16SZ + INT32SZ; /* class, TTL */
1801 n = _getshort(cp);
1802 cp += INT16SZ; /* len */
1803 if (class != C_IN) {
1804 /* XXX - debug? syslog? */
1805 cp += n;
1806 continue; /* XXX - had_error++ ? */
1808 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1809 type == T_CNAME) {
1810 n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1811 if ((n < 0) || !(*name_ok)(tbuf)) {
1812 had_error++;
1813 continue;
1815 cp += n;
1816 /* Get canonical name. */
1817 n = strlen(tbuf) + 1; /* for the \0 */
1818 if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1819 had_error++;
1820 continue;
1822 strlcpy(bp, tbuf, ep - bp);
1823 canonname = bp;
1824 bp += n;
1825 continue;
1827 if (qtype == T_ANY) {
1828 if (!(type == T_A || type == T_AAAA)) {
1829 cp += n;
1830 continue;
1832 } else if (type != qtype) {
1833 #ifdef DEBUG
1834 if (type != T_KEY && type != T_SIG)
1835 syslog(LOG_NOTICE|LOG_AUTH,
1836 "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1837 qname, p_class(C_IN), p_type(qtype),
1838 p_type(type));
1839 #endif
1840 cp += n;
1841 continue; /* XXX - had_error++ ? */
1843 switch (type) {
1844 case T_A:
1845 case T_AAAA:
1846 if (strcasecmp(canonname, bp) != 0) {
1847 #ifdef DEBUG
1848 syslog(LOG_NOTICE|LOG_AUTH,
1849 AskedForGot, canonname, bp);
1850 #endif
1851 cp += n;
1852 continue; /* XXX - had_error++ ? */
1854 if (type == T_A && n != INADDRSZ) {
1855 cp += n;
1856 continue;
1858 if (type == T_AAAA && n != IN6ADDRSZ) {
1859 cp += n;
1860 continue;
1862 #ifdef FILTER_V4MAPPED
1863 if (type == T_AAAA) {
1864 struct in6_addr in6;
1865 memcpy(&in6, cp, sizeof(in6));
1866 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1867 cp += n;
1868 continue;
1871 #endif
1872 if (!haveanswer) {
1873 int nn;
1875 canonname = bp;
1876 nn = strlen(bp) + 1; /* for the \0 */
1877 bp += nn;
1880 /* don't overwrite pai */
1881 ai = *pai;
1882 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1883 afd = find_afd(ai.ai_family);
1884 if (afd == NULL) {
1885 cp += n;
1886 continue;
1888 cur->ai_next = get_ai(&ai, afd, (const char *)cp, MiamiBase);
1889 if (cur->ai_next == NULL)
1890 had_error++;
1891 while (cur && cur->ai_next)
1892 cur = cur->ai_next;
1893 cp += n;
1894 break;
1895 default:
1896 abort();
1898 if (!had_error)
1899 haveanswer++;
1901 if (haveanswer) {
1902 #if defined(RESOLVSORT)
1904 * We support only IPv4 address for backward
1905 * compatibility against gethostbyname(3).
1907 if (_res.nsort && qtype == T_A) {
1908 if (addr4sort(&sentinel, MiamiBase) < 0) {
1909 __freeaddrinfo(sentinel.ai_next);
1910 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),NO_RECOVERY,TAG_DONE);
1911 return NULL;
1914 #endif /*RESOLVSORT*/
1915 if (!canonname)
1916 (void)get_canonname(pai, sentinel.ai_next, qname);
1917 else
1918 (void)get_canonname(pai, sentinel.ai_next, canonname);
1919 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),NETDB_SUCCESS,TAG_DONE);
1920 return sentinel.ai_next;
1922 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),NO_RECOVERY,TAG_DONE);
1923 return NULL;
1926 #ifdef RESOLVSORT
1927 struct addr_ptr {
1928 struct addrinfo *ai;
1929 int aval;
1932 static int
1933 addr4sort(struct addrinfo *sentinel, struct MiamiBase *MiamiBase)
1935 struct addrinfo *ai;
1936 struct addr_ptr *addrs, addr;
1937 struct sockaddr_in *sin;
1938 int naddrs, i, j;
1939 int needsort = 0;
1941 if (!sentinel)
1942 return -1;
1943 naddrs = 0;
1944 for (ai = sentinel->ai_next; ai; ai = ai->ai_next)
1945 naddrs++;
1946 if (naddrs < 2)
1947 return 0; /* We don't need sorting. */
1948 if ((addrs = malloc(sizeof(struct addr_ptr) * naddrs)) == NULL)
1949 return -1;
1950 i = 0;
1951 for (ai = sentinel->ai_next; ai; ai = ai->ai_next) {
1952 sin = (struct sockaddr_in *)ai->ai_addr;
1953 for (j = 0; (unsigned)j < _res.nsort; j++) {
1954 if (_res.sort_list[j].addr.s_addr ==
1955 (sin->sin_addr.s_addr & _res.sort_list[j].mask))
1956 break;
1958 addrs[i].ai = ai;
1959 addrs[i].aval = j;
1960 if (needsort == 0 && i > 0 && j < addrs[i - 1].aval)
1961 needsort = i;
1962 i++;
1964 if (!needsort) {
1965 free(addrs);
1966 return 0;
1969 while (needsort < naddrs) {
1970 for (j = needsort - 1; j >= 0; j--) {
1971 if (addrs[j].aval > addrs[j+1].aval) {
1972 addr = addrs[j];
1973 addrs[j] = addrs[j + 1];
1974 addrs[j + 1] = addr;
1975 } else
1976 break;
1978 needsort++;
1981 ai = sentinel;
1982 for (i = 0; i < naddrs; ++i) {
1983 ai->ai_next = addrs[i].ai;
1984 ai = ai->ai_next;
1986 ai->ai_next = NULL;
1987 free(addrs);
1988 return 0;
1990 #endif /*RESOLVSORT*/
1992 /*ARGSUSED*/
1993 static int
1994 _dns_getaddrinfo(rv, cb_data, ap, MiamiBase)
1995 void *rv;
1996 void *cb_data;
1997 va_list ap;
1998 struct MiamiBase *MiamiBase;
2000 struct addrinfo *ai;
2001 querybuf *buf, *buf2;
2002 const char *hostname;
2003 const struct addrinfo *pai;
2004 struct addrinfo sentinel, *cur;
2005 struct res_target q, q2;
2007 hostname = va_arg(ap, char *);
2008 pai = va_arg(ap, const struct addrinfo *);
2010 memset(&q, 0, sizeof(q2));
2011 memset(&q2, 0, sizeof(q2));
2012 memset(&sentinel, 0, sizeof(sentinel));
2013 cur = &sentinel;
2015 buf = malloc(sizeof(*buf));
2016 if (!buf) {
2017 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),NETDB_INTERNAL,TAG_DONE);
2018 return NS_NOTFOUND;
2020 buf2 = malloc(sizeof(*buf2));
2021 if (!buf2) {
2022 free(buf);
2023 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),NETDB_INTERNAL,TAG_DONE);
2024 return NS_NOTFOUND;
2027 switch (pai->ai_family) {
2028 case AF_UNSPEC:
2029 q.name = hostname;
2030 q.qclass = C_IN;
2031 q.qtype = T_A;
2032 q.answer = buf->buf;
2033 q.anslen = sizeof(buf->buf);
2034 q.next = &q2;
2035 q2.name = hostname;
2036 q2.qclass = C_IN;
2037 q2.qtype = T_AAAA;
2038 q2.answer = buf2->buf;
2039 q2.anslen = sizeof(buf2->buf);
2040 break;
2041 case AF_INET:
2042 q.name = hostname;
2043 q.qclass = C_IN;
2044 q.qtype = T_A;
2045 q.answer = buf->buf;
2046 q.anslen = sizeof(buf->buf);
2047 break;
2048 case AF_INET6:
2049 q.name = hostname;
2050 q.qclass = C_IN;
2051 q.qtype = T_AAAA;
2052 q.answer = buf->buf;
2053 q.anslen = sizeof(buf->buf);
2054 break;
2055 default:
2056 free(buf);
2057 free(buf2);
2058 return NS_UNAVAIL;
2060 if (res_searchN(hostname, &q, MiamiBase) < 0) {
2061 free(buf);
2062 free(buf2);
2063 return NS_NOTFOUND;
2065 /* prefer IPv6 */
2066 if (q.next) {
2067 ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai, MiamiBase);
2068 if (ai) {
2069 cur->ai_next = ai;
2070 while (cur && cur->ai_next)
2071 cur = cur->ai_next;
2074 ai = getanswer(buf, q.n, q.name, q.qtype, pai, MiamiBase);
2075 if (ai)
2076 cur->ai_next = ai;
2077 free(buf);
2078 free(buf2);
2079 if (sentinel.ai_next == NULL)
2081 int h_errno;
2082 SocketBaseTags(SBTM_GETREF(SBTC_HERRNO),&h_errno,TAG_DONE);
2083 switch (h_errno) {
2084 case HOST_NOT_FOUND:
2085 return NS_NOTFOUND;
2086 case TRY_AGAIN:
2087 return NS_TRYAGAIN;
2088 default:
2089 return NS_UNAVAIL;
2092 *((struct addrinfo **)rv) = sentinel.ai_next;
2093 return NS_SUCCESS;
2095 #if 0 /* TODO: move to netdb.c */
2096 static struct addrinfo *
2097 _gethtent(name, pai)
2098 const char *name;
2099 const struct addrinfo *pai;
2101 char *p;
2102 char *cp, *tname, *cname;
2103 struct addrinfo hints, *res0, *res;
2104 int error;
2105 const char *addr;
2106 char hostbuf[8*1024];
2108 if (!hostf && !(hostf = fopen(_PATH_HOSTS, "r" )))
2109 return (NULL);
2110 again:
2111 if (!(p = fgets(hostbuf, sizeof hostbuf, hostf)))
2112 return (NULL);
2113 if (*p == '#')
2114 goto again;
2115 cp = strpbrk(p, "#\n");
2116 if (cp != NULL)
2117 *cp = '\0';
2118 if (!(cp = strpbrk(p, " \t")))
2119 goto again;
2120 *cp++ = '\0';
2121 addr = p;
2122 cname = NULL;
2123 /* if this is not something we're looking for, skip it. */
2124 while (cp && *cp) {
2125 if (*cp == ' ' || *cp == '\t') {
2126 cp++;
2127 continue;
2129 tname = cp;
2130 if (cname == NULL)
2131 cname = cp;
2132 if ((cp = strpbrk(cp, " \t")) != NULL)
2133 *cp++ = '\0';
2134 if (strcasecmp(name, tname) == 0)
2135 goto found;
2137 goto again;
2139 found:
2140 /* we should not glob socktype/protocol here */
2141 memset(&hints, 0, sizeof(hints));
2142 hints.ai_family = pai->ai_family;
2143 hints.ai_socktype = SOCK_DGRAM;
2144 hints.ai_protocol = 0;
2145 hints.ai_flags = AI_NUMERICHOST;
2146 error = __getaddrinfo(addr, "0", &hints, &res0, MiamiBase);
2147 if (error)
2148 goto again;
2149 #ifdef FILTER_V4MAPPED
2150 /* XXX should check all items in the chain */
2151 if (res0->ai_family == AF_INET6 &&
2152 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) {
2153 __freeaddrinfo(res0);
2154 goto again;
2156 #endif
2157 for (res = res0; res; res = res->ai_next) {
2158 /* cover it up */
2159 res->ai_flags = pai->ai_flags;
2160 res->ai_socktype = pai->ai_socktype;
2161 res->ai_protocol = pai->ai_protocol;
2163 if (pai->ai_flags & AI_CANONNAME) {
2164 if (get_canonname(pai, res, cname) != 0) {
2165 __freeaddrinfo(res0);
2166 goto again;
2170 return res0;
2172 #endif
2173 /*ARGSUSED*/
2174 static int
2175 _files_getaddrinfo(rv, cb_data, ap, MiamiBase)
2176 void *rv;
2177 void *cb_data;
2178 va_list ap;
2179 struct MiamiBase *MiamiBase;
2181 const char *name;
2182 const struct addrinfo *pai;
2183 struct addrinfo sentinel, *cur;
2184 struct addrinfo *p;
2186 name = va_arg(ap, char *);
2187 pai = va_arg(ap, struct addrinfo *);
2189 memset(&sentinel, 0, sizeof(sentinel));
2190 cur = &sentinel;
2192 EZTCP_sethtent();
2193 while ((p = gethtent(name, pai, MiamiBase)) != NULL) {
2194 cur->ai_next = p;
2195 while (cur && cur->ai_next)
2196 cur = cur->ai_next;
2198 EZTCP_endhostent();
2200 *((struct addrinfo **)rv) = sentinel.ai_next;
2201 if (sentinel.ai_next == NULL)
2202 return NS_NOTFOUND;
2203 return NS_SUCCESS;
2206 #ifdef YP
2207 static char *__ypdomain;
2209 /*ARGSUSED*/
2210 static struct addrinfo *
2211 _yphostent(line, pai, MiamiBase)
2212 char *line;
2213 const struct addrinfo *pai;
2214 struct MiamiBase *MiamiBase;
2216 struct addrinfo sentinel, *cur;
2217 struct addrinfo hints, *res, *res0;
2218 int error;
2219 char *p = line;
2220 const char *addr, *canonname;
2221 char *nextline;
2222 char *cp;
2224 addr = canonname = NULL;
2226 memset(&sentinel, 0, sizeof(sentinel));
2227 cur = &sentinel;
2229 nextline:
2230 /* terminate line */
2231 cp = strchr(p, '\n');
2232 if (cp) {
2233 *cp++ = '\0';
2234 nextline = cp;
2235 } else
2236 nextline = NULL;
2238 cp = strpbrk(p, " \t");
2239 if (cp == NULL) {
2240 if (canonname == NULL)
2241 return (NULL);
2242 else
2243 goto done;
2245 *cp++ = '\0';
2247 addr = p;
2249 while (cp && *cp) {
2250 if (*cp == ' ' || *cp == '\t') {
2251 cp++;
2252 continue;
2254 if (!canonname)
2255 canonname = cp;
2256 if ((cp = strpbrk(cp, " \t")) != NULL)
2257 *cp++ = '\0';
2260 hints = *pai;
2261 hints.ai_flags = AI_NUMERICHOST;
2262 error = __getaddrinfo(addr, NULL, &hints, &res0, MiamiBase);
2263 if (error == 0) {
2264 for (res = res0; res; res = res->ai_next) {
2265 /* cover it up */
2266 res->ai_flags = pai->ai_flags;
2268 if (pai->ai_flags & AI_CANONNAME)
2269 (void)get_canonname(pai, res, canonname);
2271 } else
2272 res0 = NULL;
2273 if (res0) {
2274 cur->ai_next = res0;
2275 while (cur && cur->ai_next)
2276 cur = cur->ai_next;
2279 if (nextline) {
2280 p = nextline;
2281 goto nextline;
2284 done:
2285 return sentinel.ai_next;
2288 /*ARGSUSED*/
2289 static int
2290 _yp_getaddrinfo(rv, cb_data, ap, MiamiBase)
2291 void *rv;
2292 void *cb_data;
2293 va_list ap;
2294 struct MiamiBase *MiamiBase;
2296 struct addrinfo sentinel, *cur;
2297 struct addrinfo *ai = NULL;
2298 static char *__ypcurrent;
2299 int __ypcurrentlen, r;
2300 const char *name;
2301 const struct addrinfo *pai;
2303 name = va_arg(ap, char *);
2304 pai = va_arg(ap, const struct addrinfo *);
2306 memset(&sentinel, 0, sizeof(sentinel));
2307 cur = &sentinel;
2309 THREAD_LOCK();
2310 if (!__ypdomain) {
2311 if (_yp_check(&__ypdomain, MiamiBase) == 0) {
2312 THREAD_UNLOCK();
2313 return NS_UNAVAIL;
2316 if (__ypcurrent)
2317 free(__ypcurrent);
2318 __ypcurrent = NULL;
2320 /* hosts.byname is only for IPv4 (Solaris8) */
2321 if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
2322 r = yp_match(__ypdomain, "hosts.byname", name,
2323 (int)strlen(name), &__ypcurrent, &__ypcurrentlen, MiamiBase);
2324 if (r == 0) {
2325 struct addrinfo ai4;
2327 ai4 = *pai;
2328 ai4.ai_family = AF_INET;
2329 ai = _yphostent(__ypcurrent, &ai4, MiamiBase);
2330 if (ai) {
2331 cur->ai_next = ai;
2332 while (cur && cur->ai_next)
2333 cur = cur->ai_next;
2338 /* ipnodes.byname can hold both IPv4/v6 */
2339 r = yp_match(__ypdomain, "ipnodes.byname", name,
2340 (int)strlen(name), &__ypcurrent, &__ypcurrentlen, MiamiBase);
2341 if (r == 0) {
2342 ai = _yphostent(__ypcurrent, pai, MiamiBase);
2343 if (ai) {
2344 cur->ai_next = ai;
2345 while (cur && cur->ai_next)
2346 cur = cur->ai_next;
2349 THREAD_UNLOCK();
2351 if (sentinel.ai_next == NULL) {
2352 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),HOST_NOT_FOUND,TAG_DONE);
2353 return NS_NOTFOUND;
2355 *((struct addrinfo **)rv) = sentinel.ai_next;
2356 return NS_SUCCESS;
2358 #endif
2360 /* resolver logic */
2362 extern const char *__hostalias(const char *);
2365 * Formulate a normal query, send, and await answer.
2366 * Returned answer is placed in supplied buffer "answer".
2367 * Perform preliminary check of answer, returning success only
2368 * if no error is indicated and the answer count is nonzero.
2369 * Return the size of the response on success, -1 on error.
2370 * Error number is left in h_errno.
2372 * Caller must parse answer and determine whether it answers the question.
2374 static int
2375 res_queryN(name, target, MiamiBase)
2376 const char *name; /* domain name */
2377 struct res_target *target;
2378 struct MiamiBase *MiamiBase;
2380 u_char *buf;
2381 HEADER *hp;
2382 int n;
2383 struct res_target *t;
2384 int rcode;
2385 int ancount;
2387 rcode = NOERROR;
2388 ancount = 0;
2390 if ((_res.options & RES_INIT) == 0 && EZTCP_res_init() == -1) {
2391 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),NETDB_INTERNAL,TAG_DONE);
2392 return (-1);
2395 buf = malloc(MAXPACKET);
2396 if (!buf) {
2397 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),NETDB_INTERNAL,TAG_DONE);
2398 return -1;
2401 for (t = target; t; t = t->next) {
2402 int class, type;
2403 u_char *answer;
2404 int anslen;
2406 hp = (HEADER *)(void *)t->answer;
2407 hp->rcode = NOERROR; /* default */
2409 /* make it easier... */
2410 class = t->qclass;
2411 type = t->qtype;
2412 answer = t->answer;
2413 anslen = t->anslen;
2414 #ifdef DEBUG
2415 if (_res.options & RES_DEBUG)
2416 syslog(LOG_DEBUG, ";; res_query(%s, %d, %d)\n", name, class, type);
2417 #endif
2419 n = EZTCP_res_mkquery(QUERY, name, class, type, NULL, 0, NULL,
2420 buf, MAXPACKET);
2421 if (n > 0 && (_res.options & RES_USE_EDNS0) != 0)
2422 n = res_opt(n, buf, MAXPACKET, anslen);
2423 if (n <= 0) {
2424 #ifdef DEBUG
2425 if (_res.options & RES_DEBUG)
2426 vsyslog(LOG_DEBUG, ";; res_query: mkquery failed\n", NULL);
2427 #endif
2428 free(buf);
2429 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),NO_RECOVERY,TAG_DONE);
2430 return (n);
2432 n = EZTCP_res_send(buf, n, answer, anslen);
2433 #if 0
2434 if (n < 0) {
2435 #ifdef DEBUG
2436 if (_res.options & RES_DEBUG)
2437 vsyslog(LOG_DEBUG, ";; res_query: send error\n", NULL);
2438 #endif
2439 free(buf);
2440 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),TRY_AGAIN,TAG_DONE);
2441 return (n);
2443 #endif
2445 if (n < 0 || n > anslen)
2446 hp->rcode = FORMERR; /* XXX not very informative */
2447 if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
2448 rcode = hp->rcode; /* record most recent error */
2449 #ifdef DEBUG
2450 if (_res.options & RES_DEBUG)
2451 syslog(LOG_DEBUG, ";; rcode = %u, ancount=%u\n", hp->rcode,
2452 ntohs(hp->ancount));
2453 #endif
2454 continue;
2457 ancount += ntohs(hp->ancount);
2459 t->n = n;
2462 free(buf);
2464 if (ancount == 0) {
2465 int h_errno;
2466 switch (rcode) {
2467 case NXDOMAIN:
2468 h_errno = HOST_NOT_FOUND;
2469 break;
2470 case SERVFAIL:
2471 h_errno = TRY_AGAIN;
2472 break;
2473 case NOERROR:
2474 h_errno = NO_DATA;
2475 break;
2476 case FORMERR:
2477 case NOTIMP:
2478 case REFUSED:
2479 default:
2480 h_errno = NO_RECOVERY;
2481 break;
2483 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),h_errno,TAG_DONE);
2484 return (-1);
2486 return (ancount);
2490 * Formulate a normal query, send, and retrieve answer in supplied buffer.
2491 * Return the size of the response on success, -1 on error.
2492 * If enabled, implement search rules until answer or unrecoverable failure
2493 * is detected. Error code, if any, is left in h_errno.
2495 static int
2496 res_searchN(name, target, MiamiBase)
2497 const char *name; /* domain name */
2498 struct res_target *target;
2499 struct MiamiBase *MiamiBase;
2501 const char *cp, * const *domain;
2502 HEADER *hp = (HEADER *)(void *)target->answer; /*XXX*/
2503 u_int dots;
2504 int trailing_dot, ret, saved_herrno;
2505 int errno, herrno;
2506 int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
2508 if ((_res.options & RES_INIT) == 0 && EZTCP_res_init() == -1) {
2509 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),NETDB_INTERNAL,TAG_DONE);
2510 return (-1);
2512 /* default, if we never query */
2513 SocketBaseTags(SBTM_SETVAL(SBTC_ERRNO),0,SBTM_SETVAL(SBTC_HERRNO),HOST_NOT_FOUND,TAG_DONE);
2514 dots = 0;
2515 for (cp = name; *cp; cp++)
2516 dots += (*cp == '.');
2517 trailing_dot = 0;
2518 if (cp > name && *--cp == '.')
2519 trailing_dot++;
2522 * if there aren't any dots, it could be a user-level alias
2524 if (!dots && (cp = __hostalias(name)) != NULL)
2525 return (res_queryN(cp, target, MiamiBase));
2528 * If there are dots in the name already, let's just give it a try
2529 * 'as is'. The threshold can be set with the "ndots" option.
2531 saved_herrno = -1;
2532 if (dots >= _res.ndots) {
2533 ret = res_querydomainN(name, NULL, target, MiamiBase);
2534 if (ret > 0)
2535 return (ret);
2536 SocketBaseTags(SBTM_GETREF(SBTC_HERRNO),&saved_herrno,TAG_DONE);
2537 tried_as_is++;
2541 * We do at least one level of search if
2542 * - there is no dot and RES_DEFNAME is set, or
2543 * - there is at least one dot, there is no trailing dot,
2544 * and RES_DNSRCH is set.
2546 if ((!dots && (_res.options & RES_DEFNAMES)) ||
2547 (dots && !trailing_dot && (_res.options & RES_DNSRCH))) {
2548 int done = 0;
2550 for (domain = (const char * const *)_res.dnsrch;
2551 *domain && !done;
2552 domain++) {
2554 ret = res_querydomainN(name, *domain, target, MiamiBase);
2555 if (ret > 0)
2556 return (ret);
2559 * If no server present, give up.
2560 * If name isn't found in this domain,
2561 * keep trying higher domains in the search list
2562 * (if that's enabled).
2563 * On a NO_DATA error, keep trying, otherwise
2564 * a wildcard entry of another type could keep us
2565 * from finding this entry higher in the domain.
2566 * If we get some other error (negative answer or
2567 * server failure), then stop searching up,
2568 * but try the input name below in case it's
2569 * fully-qualified.
2571 SocketBaseTags(SBTM_GETREF(SBTC_ERRNO),&errno,TAG_DONE);
2572 if (errno == ECONNREFUSED) {
2573 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),TRY_AGAIN,TAG_DONE);
2574 return (-1);
2576 SocketBaseTags(SBTM_GETREF(SBTC_HERRNO),&h_errno,TAG_DONE);
2577 switch (h_errno) {
2578 case NO_DATA:
2579 got_nodata++;
2580 /* FALLTHROUGH */
2581 case HOST_NOT_FOUND:
2582 /* keep trying */
2583 break;
2584 case TRY_AGAIN:
2585 if (hp->rcode == SERVFAIL) {
2586 /* try next search element, if any */
2587 got_servfail++;
2588 break;
2590 /* FALLTHROUGH */
2591 default:
2592 /* anything else implies that we're done */
2593 done++;
2596 * if we got here for some reason other than DNSRCH,
2597 * we only wanted one iteration of the loop, so stop.
2599 if (!(_res.options & RES_DNSRCH))
2600 done++;
2605 * if we have not already tried the name "as is", do that now.
2606 * note that we do this regardless of how many dots were in the
2607 * name or whether it ends with a dot.
2609 if (!tried_as_is && (dots || !(_res.options & RES_NOTLDQUERY))) {
2610 ret = res_querydomainN(name, NULL, target, MiamiBase);
2611 if (ret > 0)
2612 return (ret);
2616 * if we got here, we didn't satisfy the search.
2617 * if we did an initial full query, return that query's h_errno
2618 * (note that we wouldn't be here if that query had succeeded).
2619 * else if we ever got a nodata, send that back as the reason.
2620 * else send back meaningless h_errno, that being the one from
2621 * the last DNSRCH we did.
2623 if (saved_herrno != -1)
2624 h_errno = saved_herrno;
2625 else if (got_nodata)
2626 h_errno = NO_DATA;
2627 else if (got_servfail)
2628 h_errno = TRY_AGAIN;
2629 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),h_errno,TAG_DONE);
2630 return (-1);
2634 * Perform a call on res_query on the concatenation of name and domain,
2635 * removing a trailing dot from name if domain is NULL.
2637 static int
2638 res_querydomainN(name, domain, target, MiamiBase)
2639 const char *name, *domain;
2640 struct res_target *target;
2641 struct MiamiBase *MiamiBase;
2643 char nbuf[MAXDNAME];
2644 const char *longname = nbuf;
2645 size_t n, d;
2647 if ((_res.options & RES_INIT) == 0 && EZTCP_res_init() == -1) {
2648 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),NETDB_INTERNAL,TAG_DONE);
2649 return (-1);
2651 #ifdef DEBUG
2652 if (_res.options & RES_DEBUG)
2653 syslog(LOG_DEBUG, ";; res_querydomain(%s, %s)\n",
2654 name, domain?domain:"<Nil>");
2655 #endif
2656 if (domain == NULL) {
2658 * Check for trailing '.';
2659 * copy without '.' if present.
2661 n = strlen(name);
2662 if (n >= MAXDNAME) {
2663 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),NO_RECOVERY,TAG_DONE);
2664 return (-1);
2666 if (n > 0 && name[--n] == '.') {
2667 strncpy(nbuf, name, n);
2668 nbuf[n] = '\0';
2669 } else
2670 longname = name;
2671 } else {
2672 n = strlen(name);
2673 d = strlen(domain);
2674 if (n + d + 1 >= MAXDNAME) {
2675 SocketBaseTags(SBTM_SETVAL(SBTC_HERRNO),NO_RECOVERY,TAG_DONE);
2676 return (-1);
2678 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2680 return (res_queryN(longname, target, MiamiBase));