OSDN Git Service

2003-05-28 Jeff Johnston <jjohnstn@redhat.com>
[pf3gnuchains/pf3gnuchains3x.git] / newlib / libc / sys / linux / net / getaddrinfo.c
1 /*      $KAME: getaddrinfo.c,v 1.15 2000/07/09 04:37:24 itojun Exp $    */
2
3 /*
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32 /*
33  * "#ifdef FAITH" part is local hack for supporting IPv4-v6 translator.
34  *
35  * Issues to be discussed:
36  * - Thread safe-ness must be checked.
37  * - Return values.  There are nonstandard return values defined and used
38  *   in the source code.  This is because RFC2553 is silent about which error
39  *   code must be returned for which situation.
40  * - freeaddrinfo(NULL).  RFC2553 is silent about it.  XNET 5.2 says it is
41  *   invalid.
42  *   current code - SEGV on freeaddrinfo(NULL)
43  * Note:
44  * - We use getipnodebyname() just for thread-safeness.  There's no intent
45  *   to let it do PF_UNSPEC (actually we never pass PF_UNSPEC to
46  *   getipnodebyname().
47  * - The code filters out AFs that are not supported by the kernel,
48  *   when globbing NULL hostname (to loopback, or wildcard).  Is it the right
49  *   thing to do?  What is the relationship with post-RFC2553 AI_ADDRCONFIG
50  *   in ai_flags?
51  * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
52  *   (1) what should we do against numeric hostname (2) what should we do
53  *   against NULL hostname (3) what is AI_ADDRCONFIG itself.  AF not ready?
54  *   non-loopback address configured?  global address configured?
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  *   follows:
60  *      - The code makes use of following calls when asked to resolver with
61  *        ai_family  = PF_UNSPEC:
62  *              getipnodebyname(host, AF_INET6);
63  *              getipnodebyname(host, AF_INET);
64  *        This will result in the following queries if the node is configure to
65  *        prefer /etc/hosts than DNS:
66  *              lookup /etc/hosts for IPv6 address
67  *              lookup DNS for IPv6 address
68  *              lookup /etc/hosts for IPv4 address
69  *              lookup DNS for IPv4 address
70  *        which may not meet people's requirement.
71  *        The right thing to happen is to have underlying layer which does
72  *        PF_UNSPEC lookup (lookup both) and return chain of addrinfos.
73  *        This would result in a bit of code duplicate with _dns_ghbyname() and
74  *        friends.
75  */
76 /*
77  * diffs with other KAME platforms:
78  * - other KAME platforms already nuked FAITH ($GAI), but as FreeBSD
79  *   4.0-RELEASE supplies it, we still have the code here.
80  * - AI_ADDRCONFIG support is supplied
81  * - some of FreeBSD style (#define tabify and others)
82  * - classful IPv4 numeric (127.1) is allowed.
83  */
84
85 #include <sys/cdefs.h>
86 #include <machine/endian.h>
87
88 #include "namespace.h"
89 #include <sys/types.h>
90 #include <sys/types.h>
91 #include <sys/param.h>
92 #include <sys/socket.h>
93 #include <net/if.h>
94 #include <netinet/in.h>
95 #include <arpa/inet.h>
96 #include <arpa/nameser.h>
97 #include <rpc/rpc.h>
98 #include <rpcsvc/yp_prot.h>
99 #include <rpcsvc/ypclnt.h>
100 #include <netdb.h>
101 #include <resolv.h>
102 #include <string.h>
103 #include <stdlib.h>
104 #include <stddef.h>
105 #include <ctype.h>
106 #include <unistd.h>
107 #include <stdio.h>
108 #include <errno.h>
109 #ifdef DEBUG
110 #include <syslog.h>
111 #endif
112
113 #include <syslog.h>
114 #include <stdarg.h>
115 #include <nsswitch.h>
116 #include "un-namespace.h"
117
118 #if defined(__KAME__) && defined(INET6)
119 # define FAITH
120 #endif
121
122 #define SUCCESS 0
123 #define ANY 0
124 #define YES 1
125 #define NO  0
126
127 static const char in_addrany[] = { 0, 0, 0, 0 };
128 static const char in6_addrany[] = {
129         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
130 };
131 static const char in_loopback[] = { 127, 0, 0, 1 };
132 static const char in6_loopback[] = {
133         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
134 };
135
136 static const struct afd {
137         int a_af;
138         int a_addrlen;
139         int a_socklen;
140         int a_off;
141         const char *a_addrany;
142         const char *a_loopback;
143         int a_scoped;
144 } afdl [] = {
145 #ifdef INET6
146 #define N_INET6 0
147         {PF_INET6, sizeof(struct in6_addr),
148          sizeof(struct sockaddr_in6),
149          offsetof(struct sockaddr_in6, sin6_addr),
150          in6_addrany, in6_loopback, 1},
151 #define N_INET 1
152 #else
153 #define N_INET 0
154 #endif
155         {PF_INET, sizeof(struct in_addr),
156          sizeof(struct sockaddr_in),
157          offsetof(struct sockaddr_in, sin_addr),
158          in_addrany, in_loopback, 0},
159         {0, 0, 0, 0, NULL, NULL, 0},
160 };
161
162 struct explore {
163         int e_af;
164         int e_socktype;
165         int e_protocol;
166         const char *e_protostr;
167         int e_wild;
168 #define WILD_AF(ex)             ((ex)->e_wild & 0x01)
169 #define WILD_SOCKTYPE(ex)       ((ex)->e_wild & 0x02)
170 #define WILD_PROTOCOL(ex)       ((ex)->e_wild & 0x04)
171 };
172
173 static const struct explore explore[] = {
174 #if 0
175         { PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
176 #endif
177 #ifdef INET6
178         { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
179         { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
180         { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
181 #endif
182         { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
183         { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
184         { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
185         { PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
186         { PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
187         { PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
188         { -1, 0, 0, NULL, 0 },
189 };
190
191 #ifdef INET6
192 #define PTON_MAX        16
193 #else
194 #define PTON_MAX        4
195 #endif
196
197 static const ns_src default_dns_files[] = {
198         { NSSRC_FILES,  NS_SUCCESS },
199         { NSSRC_DNS,    NS_SUCCESS },
200         { 0 }
201 };
202
203 #if PACKETSZ > 1024
204 #define MAXPACKET       PACKETSZ
205 #else
206 #define MAXPACKET       1024
207 #endif
208
209 typedef union {
210         HEADER hdr;
211         u_char buf[MAXPACKET];
212 } querybuf;
213
214 struct res_target {
215         struct res_target *next;
216         const char *name;       /* domain name */
217         int qclass, qtype;      /* class and type of query */
218         u_char *answer;         /* buffer to put answer */
219         int anslen;             /* size of answer buffer */
220         int n;                  /* result length */
221 };
222
223 static int str_isnumber(const char *);
224 static int explore_fqdn(const struct addrinfo *, const char *,
225         const char *, struct addrinfo **);
226 static int explore_null(const struct addrinfo *,
227         const char *, struct addrinfo **);
228 static int explore_numeric(const struct addrinfo *, const char *,
229         const char *, struct addrinfo **);
230 static int explore_numeric_scope(const struct addrinfo *, const char *,
231         const char *, struct addrinfo **);
232 static int get_canonname(const struct addrinfo *,
233         struct addrinfo *, const char *);
234 static struct addrinfo *get_ai(const struct addrinfo *,
235         const struct afd *, const char *);
236 static int get_portmatch(const struct addrinfo *, const char *);
237 static int get_port(struct addrinfo *, const char *, int);
238 static const struct afd *find_afd(int);
239 static int addrconfig(struct addrinfo *);
240 #ifdef INET6
241 static int ip6_str2scopeid(char *, struct sockaddr_in6 *);
242 #endif
243
244 static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
245         const struct addrinfo *);
246 static int _dns_getaddrinfo(void *, void *, va_list);
247 static void _sethtent(void);
248 static void _endhtent(void);
249 static struct addrinfo *_gethtent(const char *, const struct addrinfo *);
250 static int _files_getaddrinfo(void *, void *, va_list);
251 #ifdef YP
252 static struct addrinfo *_yphostent(char *, const struct addrinfo *);
253 static int _yp_getaddrinfo(void *, void *, va_list);
254 extern int _yp_check(char **);
255 #endif
256
257 u_int16_t _getshort(const u_char *src);
258
259 static int res_queryN(const char *, struct res_target *);
260 static int res_searchN(const char *, struct res_target *);
261 static int res_querydomainN(const char *, const char *,
262         struct res_target *);
263
264 static char *ai_errlist[] = {
265         "Success",
266         "Address family for hostname not supported",    /* EAI_ADDRFAMILY */
267         "Temporary failure in name resolution",         /* EAI_AGAIN      */
268         "Invalid value for ai_flags",                   /* EAI_BADFLAGS   */
269         "Non-recoverable failure in name resolution",   /* EAI_FAIL       */
270         "ai_family not supported",                      /* EAI_FAMILY     */
271         "Memory allocation failure",                    /* EAI_MEMORY     */
272         "No address associated with hostname",          /* EAI_NODATA     */
273         "hostname nor servname provided, or not known", /* EAI_NONAME     */
274         "servname not supported for ai_socktype",       /* EAI_SERVICE    */
275         "ai_socktype not supported",                    /* EAI_SOCKTYPE   */
276         "System error returned in errno",               /* EAI_SYSTEM     */
277         "Invalid value for hints",                      /* EAI_BADHINTS   */
278         "Resolved protocol is unknown",                 /* EAI_PROTOCOL   */
279         "Unknown error",                                /* EAI_MAX        */
280 };
281
282 /* XXX macros that make external reference is BAD. */
283
284 #define GET_AI(ai, afd, addr) \
285 do { \
286         /* external reference: pai, error, and label free */ \
287         (ai) = get_ai(pai, (afd), (addr)); \
288         if ((ai) == NULL) { \
289                 error = EAI_MEMORY; \
290                 goto free; \
291         } \
292 } while (/*CONSTCOND*/0)
293
294 #define GET_PORT(ai, serv) \
295 do { \
296         /* external reference: error and label free */ \
297         error = get_port((ai), (serv), 0); \
298         if (error != 0) \
299                 goto free; \
300 } while (/*CONSTCOND*/0)
301
302 #define GET_CANONNAME(ai, str) \
303 do { \
304         /* external reference: pai, error and label free */ \
305         error = get_canonname(pai, (ai), (str)); \
306         if (error != 0) \
307                 goto free; \
308 } while (/*CONSTCOND*/0)
309
310 #define ERR(err) \
311 do { \
312         /* external reference: error, and label bad */ \
313         error = (err); \
314         goto bad; \
315         /*NOTREACHED*/ \
316 } while (/*CONSTCOND*/0)
317
318 #define MATCH_FAMILY(x, y, w) \
319         ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
320 #define MATCH(x, y, w) \
321         ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
322
323 char *
324 gai_strerror(ecode)
325         int ecode;
326 {
327         if (ecode < 0 || ecode > EAI_MAX)
328                 ecode = EAI_MAX;
329         return ai_errlist[ecode];
330 }
331
332 void
333 freeaddrinfo(ai)
334         struct addrinfo *ai;
335 {
336         struct addrinfo *next;
337
338         do {
339                 next = ai->ai_next;
340                 if (ai->ai_canonname)
341                         free(ai->ai_canonname);
342                 /* no need to free(ai->ai_addr) */
343                 free(ai);
344                 ai = next;
345         } while (ai);
346 }
347
348 static int
349 str_isnumber(p)
350         const char *p;
351 {
352         char *ep;
353
354         if (*p == '\0')
355                 return NO;
356         ep = NULL;
357         (void)strtoul(p, &ep, 10);
358         if (ep && *ep == '\0')
359                 return YES;
360         else
361                 return NO;
362 }
363
364 int
365 getaddrinfo(hostname, servname, hints, res)
366         const char *hostname, *servname;
367         const struct addrinfo *hints;
368         struct addrinfo **res;
369 {
370         struct addrinfo sentinel;
371         struct addrinfo *cur;
372         int error = 0;
373         struct addrinfo ai;
374         struct addrinfo ai0;
375         struct addrinfo *pai;
376         const struct explore *ex;
377
378         memset(&sentinel, 0, sizeof(sentinel));
379         cur = &sentinel;
380         pai = &ai;
381         pai->ai_flags = 0;
382         pai->ai_family = PF_UNSPEC;
383         pai->ai_socktype = ANY;
384         pai->ai_protocol = ANY;
385         pai->ai_addrlen = 0;
386         pai->ai_canonname = NULL;
387         pai->ai_addr = NULL;
388         pai->ai_next = NULL;
389
390         if (hostname == NULL && servname == NULL)
391                 return EAI_NONAME;
392         if (hints) {
393                 /* error check for hints */
394                 if (hints->ai_addrlen || hints->ai_canonname ||
395                     hints->ai_addr || hints->ai_next)
396                         ERR(EAI_BADHINTS); /* xxx */
397                 if (hints->ai_flags & ~AI_MASK)
398                         ERR(EAI_BADFLAGS);
399                 switch (hints->ai_family) {
400                 case PF_UNSPEC:
401                 case PF_INET:
402 #ifdef INET6
403                 case PF_INET6:
404 #endif
405                         break;
406                 default:
407                         ERR(EAI_FAMILY);
408                 }
409                 memcpy(pai, hints, sizeof(*pai));
410
411                 /*
412                  * if both socktype/protocol are specified, check if they
413                  * are meaningful combination.
414                  */
415                 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
416                         for (ex = explore; ex->e_af >= 0; ex++) {
417                                 if (pai->ai_family != ex->e_af)
418                                         continue;
419                                 if (ex->e_socktype == ANY)
420                                         continue;
421                                 if (ex->e_protocol == ANY)
422                                         continue;
423                                 if (pai->ai_socktype == ex->e_socktype
424                                  && pai->ai_protocol != ex->e_protocol) {
425                                         ERR(EAI_BADHINTS);
426                                 }
427                         }
428                 }
429         }
430
431         /*
432          * post-2553: AI_ALL and AI_V4MAPPED are effective only against
433          * AF_INET6 query.  They needs to be ignored if specified in other
434          * occassions.
435          */
436         switch (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) {
437         case AI_V4MAPPED:
438         case AI_ALL | AI_V4MAPPED:
439                 if (pai->ai_family != AF_INET6)
440                         pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
441                 break;
442         case AI_ALL:
443 #if 1
444                 /* illegal */
445                 ERR(EAI_BADFLAGS);
446 #else
447                 pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
448 #endif
449                 break;
450         }
451
452         /*
453          * check for special cases.  (1) numeric servname is disallowed if
454          * socktype/protocol are left unspecified. (2) servname is disallowed
455          * for raw and other inet{,6} sockets.
456          */
457         if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
458 #ifdef PF_INET6
459             || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
460 #endif
461             ) {
462                 ai0 = *pai;     /* backup *pai */
463
464                 if (pai->ai_family == PF_UNSPEC) {
465 #ifdef PF_INET6
466                         pai->ai_family = PF_INET6;
467 #else
468                         pai->ai_family = PF_INET;
469 #endif
470                 }
471                 error = get_portmatch(pai, servname);
472                 if (error)
473                         ERR(error);
474
475                 *pai = ai0;
476         }
477
478         ai0 = *pai;
479
480         /* NULL hostname, or numeric hostname */
481         for (ex = explore; ex->e_af >= 0; ex++) {
482                 *pai = ai0;
483
484                 /* PF_UNSPEC entries are prepared for DNS queries only */
485                 if (ex->e_af == PF_UNSPEC)
486                         continue;
487
488                 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
489                         continue;
490                 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
491                         continue;
492                 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
493                         continue;
494
495                 if (pai->ai_family == PF_UNSPEC)
496                         pai->ai_family = ex->e_af;
497                 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
498                         pai->ai_socktype = ex->e_socktype;
499                 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
500                         pai->ai_protocol = ex->e_protocol;
501
502                 if (hostname == NULL)
503                         error = explore_null(pai, servname, &cur->ai_next);
504                 else
505                         error = explore_numeric_scope(pai, hostname, servname, &cur->ai_next);
506
507                 if (error)
508                         goto free;
509
510                 while (cur && cur->ai_next)
511                         cur = cur->ai_next;
512         }
513
514         /*
515          * XXX
516          * If numreic representation of AF1 can be interpreted as FQDN
517          * representation of AF2, we need to think again about the code below.
518          */
519         if (sentinel.ai_next)
520                 goto good;
521
522         if (pai->ai_flags & AI_NUMERICHOST)
523                 ERR(EAI_NONAME);
524         if (hostname == NULL)
525                 ERR(EAI_NODATA);
526
527         if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(&ai0))
528                 ERR(EAI_FAIL);
529
530         /*
531          * hostname as alphabetical name.
532          * we would like to prefer AF_INET6 than AF_INET, so we'll make a
533          * outer loop by AFs.
534          */
535         for (ex = explore; ex->e_af >= 0; ex++) {
536                 *pai = ai0;
537
538                 /* require exact match for family field */
539                 if (pai->ai_family != ex->e_af)
540                         continue;
541
542                 if (!MATCH(pai->ai_socktype, ex->e_socktype,
543                                 WILD_SOCKTYPE(ex))) {
544                         continue;
545                 }
546                 if (!MATCH(pai->ai_protocol, ex->e_protocol,
547                                 WILD_PROTOCOL(ex))) {
548                         continue;
549                 }
550
551                 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
552                         pai->ai_socktype = ex->e_socktype;
553                 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
554                         pai->ai_protocol = ex->e_protocol;
555
556                 error = explore_fqdn(pai, hostname, servname,
557                         &cur->ai_next);
558
559                 while (cur && cur->ai_next)
560                         cur = cur->ai_next;
561         }
562
563         /* XXX */
564         if (sentinel.ai_next)
565                 error = 0;
566
567         if (error)
568                 goto free;
569         if (error == 0) {
570                 if (sentinel.ai_next) {
571  good:
572                         *res = sentinel.ai_next;
573                         return SUCCESS;
574                 } else
575                         error = EAI_FAIL;
576         }
577  free:
578  bad:
579         if (sentinel.ai_next)
580                 freeaddrinfo(sentinel.ai_next);
581         *res = NULL;
582         return error;
583 }
584
585 /*
586  * FQDN hostname, DNS lookup
587  */
588 static int
589 explore_fqdn(pai, hostname, servname, res)
590         const struct addrinfo *pai;
591         const char *hostname;
592         const char *servname;
593         struct addrinfo **res;
594 {
595         struct addrinfo *result;
596         struct addrinfo *cur;
597         int error = 0;
598         static const ns_dtab dtab[] = {
599                 NS_FILES_CB(_files_getaddrinfo, NULL)
600                 { NSSRC_DNS, _dns_getaddrinfo, NULL },  /* force -DHESIOD */
601                 NS_NIS_CB(_yp_getaddrinfo, NULL)
602                 { 0 }
603         };
604
605         result = NULL;
606
607         /*
608          * if the servname does not match socktype/protocol, ignore it.
609          */
610         if (get_portmatch(pai, servname) != 0)
611                 return 0;
612
613         switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
614                         default_dns_files, hostname, pai)) {
615         case NS_TRYAGAIN:
616                 error = EAI_AGAIN;
617                 goto free;
618         case NS_UNAVAIL:
619                 error = EAI_FAIL;
620                 goto free;
621         case NS_NOTFOUND:
622                 error = EAI_NODATA;
623                 goto free;
624         case NS_SUCCESS:
625                 error = 0;
626                 for (cur = result; cur; cur = cur->ai_next) {
627                         GET_PORT(cur, servname);
628                         /* canonname should be filled already */
629                 }
630                 break;
631         }
632
633         *res = result;
634
635         return 0;
636
637 free:
638         if (result)
639                 freeaddrinfo(result);
640         return error;
641 }
642
643 /*
644  * hostname == NULL.
645  * passive socket -> anyaddr (0.0.0.0 or ::)
646  * non-passive socket -> localhost (127.0.0.1 or ::1)
647  */
648 static int
649 explore_null(pai, servname, res)
650         const struct addrinfo *pai;
651         const char *servname;
652         struct addrinfo **res;
653 {
654         int s;
655         const struct afd *afd;
656         struct addrinfo *cur;
657         struct addrinfo sentinel;
658         int error;
659
660         *res = NULL;
661         sentinel.ai_next = NULL;
662         cur = &sentinel;
663
664         /*
665          * filter out AFs that are not supported by the kernel
666          * XXX errno?
667          */
668         s = socket(pai->ai_family, SOCK_DGRAM, 0);
669         if (s < 0) {
670                 if (errno != EMFILE)
671                         return 0;
672         } else
673                 close(s);
674
675         /*
676          * if the servname does not match socktype/protocol, ignore it.
677          */
678         if (get_portmatch(pai, servname) != 0)
679                 return 0;
680
681         afd = find_afd(pai->ai_family);
682         if (afd == NULL)
683                 return 0;
684
685         if (pai->ai_flags & AI_PASSIVE) {
686                 GET_AI(cur->ai_next, afd, afd->a_addrany);
687                 /* xxx meaningless?
688                  * GET_CANONNAME(cur->ai_next, "anyaddr");
689                  */
690                 GET_PORT(cur->ai_next, servname);
691         } else {
692                 GET_AI(cur->ai_next, afd, afd->a_loopback);
693                 /* xxx meaningless?
694                  * GET_CANONNAME(cur->ai_next, "localhost");
695                  */
696                 GET_PORT(cur->ai_next, servname);
697         }
698         cur = cur->ai_next;
699
700         *res = sentinel.ai_next;
701         return 0;
702
703 free:
704         if (sentinel.ai_next)
705                 freeaddrinfo(sentinel.ai_next);
706         return error;
707 }
708
709 /*
710  * numeric hostname
711  */
712 static int
713 explore_numeric(pai, hostname, servname, res)
714         const struct addrinfo *pai;
715         const char *hostname;
716         const char *servname;
717         struct addrinfo **res;
718 {
719         const struct afd *afd;
720         struct addrinfo *cur;
721         struct addrinfo sentinel;
722         int error;
723         char pton[PTON_MAX];
724
725         *res = NULL;
726         sentinel.ai_next = NULL;
727         cur = &sentinel;
728
729         /*
730          * if the servname does not match socktype/protocol, ignore it.
731          */
732         if (get_portmatch(pai, servname) != 0)
733                 return 0;
734
735         afd = find_afd(pai->ai_family);
736         if (afd == NULL)
737                 return 0;
738
739         switch (afd->a_af) {
740 #if 1 /*X/Open spec*/
741         case AF_INET:
742                 if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
743                         if (pai->ai_family == afd->a_af ||
744                             pai->ai_family == PF_UNSPEC /*?*/) {
745                                 GET_AI(cur->ai_next, afd, pton);
746                                 GET_PORT(cur->ai_next, servname);
747                                 while (cur && cur->ai_next)
748                                         cur = cur->ai_next;
749                         } else
750                                 ERR(EAI_FAMILY);        /*xxx*/
751                 }
752                 break;
753 #endif
754         default:
755                 if (inet_pton(afd->a_af, hostname, pton) == 1) {
756                         if (pai->ai_family == afd->a_af ||
757                             pai->ai_family == PF_UNSPEC /*?*/) {
758                                 GET_AI(cur->ai_next, afd, pton);
759                                 GET_PORT(cur->ai_next, servname);
760                                 while (cur && cur->ai_next)
761                                         cur = cur->ai_next;
762                         } else
763                                 ERR(EAI_FAMILY);        /*xxx*/
764                 }
765                 break;
766         }
767
768         *res = sentinel.ai_next;
769         return 0;
770
771 free:
772 bad:
773         if (sentinel.ai_next)
774                 freeaddrinfo(sentinel.ai_next);
775         return error;
776 }
777
778 /*
779  * numeric hostname with scope
780  */
781 static int
782 explore_numeric_scope(pai, hostname, servname, res)
783         const struct addrinfo *pai;
784         const char *hostname;
785         const char *servname;
786         struct addrinfo **res;
787 {
788 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
789         return explore_numeric(pai, hostname, servname, res);
790 #else
791         const struct afd *afd;
792         struct addrinfo *cur;
793         int error;
794         char *cp, *hostname2 = NULL, *scope, *addr;
795         struct sockaddr_in6 *sin6;
796
797         /*
798          * if the servname does not match socktype/protocol, ignore it.
799          */
800         if (get_portmatch(pai, servname) != 0)
801                 return 0;
802
803         afd = find_afd(pai->ai_family);
804         if (afd == NULL)
805                 return 0;
806
807         if (!afd->a_scoped)
808                 return explore_numeric(pai, hostname, servname, res);
809
810         cp = strchr(hostname, SCOPE_DELIMITER);
811         if (cp == NULL)
812                 return explore_numeric(pai, hostname, servname, res);
813
814         /*
815          * Handle special case of <scoped_address><delimiter><scope id>
816          */
817         hostname2 = strdup(hostname);
818         if (hostname2 == NULL)
819                 return EAI_MEMORY;
820         /* terminate at the delimiter */
821         hostname2[cp - hostname] = '\0';
822         addr = hostname2;
823         scope = cp + 1;
824
825         error = explore_numeric(pai, addr, servname, res);
826         if (error == 0) {
827                 int scopeid;
828
829                 for (cur = *res; cur; cur = cur->ai_next) {
830                         if (cur->ai_family != AF_INET6)
831                                 continue;
832                         sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
833                         if ((scopeid = ip6_str2scopeid(scope, sin6)) == -1) {
834                                 free(hostname2);
835                                 return(EAI_NODATA); /* XXX: is return OK? */
836                         }
837                         sin6->sin6_scope_id = scopeid;
838                 }
839         }
840
841         free(hostname2);
842
843         return error;
844 #endif
845 }
846
847 static int
848 get_canonname(pai, ai, str)
849         const struct addrinfo *pai;
850         struct addrinfo *ai;
851         const char *str;
852 {
853         if ((pai->ai_flags & AI_CANONNAME) != 0) {
854                 ai->ai_canonname = (char *)malloc(strlen(str) + 1);
855                 if (ai->ai_canonname == NULL)
856                         return EAI_MEMORY;
857                 strcpy(ai->ai_canonname, str);
858         }
859         return 0;
860 }
861
862 static struct addrinfo *
863 get_ai(pai, afd, addr)
864         const struct addrinfo *pai;
865         const struct afd *afd;
866         const char *addr;
867 {
868         char *p;
869         struct addrinfo *ai;
870 #ifdef FAITH
871         struct in6_addr faith_prefix;
872         char *fp_str;
873         int translate = 0;
874 #endif
875
876 #ifdef FAITH
877         /*
878          * Transfrom an IPv4 addr into a special IPv6 addr format for
879          * IPv6->IPv4 translation gateway. (only TCP is supported now)
880          *
881          * +-----------------------------------+------------+
882          * | faith prefix part (12 bytes)      | embedded   |
883          * |                                   | IPv4 addr part (4 bytes)
884          * +-----------------------------------+------------+
885          *
886          * faith prefix part is specified as ascii IPv6 addr format
887          * in environmental variable GAI.
888          * For FAITH to work correctly, routing to faith prefix must be
889          * setup toward a machine where a FAITH daemon operates.
890          * Also, the machine must enable some mechanizm
891          * (e.g. faith interface hack) to divert those packet with
892          * faith prefixed destination addr to user-land FAITH daemon.
893          */
894         fp_str = getenv("GAI");
895         if (fp_str && inet_pton(AF_INET6, fp_str, &faith_prefix) == 1 &&
896             afd->a_af == AF_INET && pai->ai_socktype == SOCK_STREAM) {
897                 u_int32_t v4a;
898                 u_int8_t v4a_top;
899
900                 memcpy(&v4a, addr, sizeof v4a);
901                 v4a_top = v4a >> IN_CLASSA_NSHIFT;
902                 if (!IN_MULTICAST(v4a) && !IN_EXPERIMENTAL(v4a) &&
903                     v4a_top != 0 && v4a != IN_LOOPBACKNET) {
904                         afd = &afdl[N_INET6];
905                         memcpy(&faith_prefix.s6_addr[12], addr,
906                                sizeof(struct in_addr));
907                         translate = 1;
908                 }
909         }
910 #endif
911
912         ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
913                 + (afd->a_socklen));
914         if (ai == NULL)
915                 return NULL;
916
917         memcpy(ai, pai, sizeof(struct addrinfo));
918         ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
919         memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
920         ai->ai_addrlen = afd->a_socklen;
921         ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
922         p = (char *)(void *)(ai->ai_addr);
923 #ifdef FAITH
924         if (translate == 1)
925                 memcpy(p + afd->a_off, &faith_prefix, (size_t)afd->a_addrlen);
926         else
927 #endif
928         memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
929         return ai;
930 }
931
932 static int
933 get_portmatch(ai, servname)
934         const struct addrinfo *ai;
935         const char *servname;
936 {
937
938         /* get_port does not touch first argument. when matchonly == 1. */
939         /* LINTED const cast */
940         return get_port((struct addrinfo *)ai, servname, 1);
941 }
942
943 static int
944 get_port(ai, servname, matchonly)
945         struct addrinfo *ai;
946         const char *servname;
947         int matchonly;
948 {
949         const char *proto;
950         struct servent *sp;
951         int port;
952         int allownumeric;
953
954         if (servname == NULL)
955                 return 0;
956         switch (ai->ai_family) {
957         case AF_INET:
958 #ifdef AF_INET6
959         case AF_INET6:
960 #endif
961                 break;
962         default:
963                 return 0;
964         }
965
966         switch (ai->ai_socktype) {
967         case SOCK_RAW:
968                 return EAI_SERVICE;
969         case SOCK_DGRAM:
970         case SOCK_STREAM:
971                 allownumeric = 1;
972                 break;
973         case ANY:
974                 allownumeric = 0;
975                 break;
976         default:
977                 return EAI_SOCKTYPE;
978         }
979
980         if (str_isnumber(servname)) {
981                 if (!allownumeric)
982                         return EAI_SERVICE;
983                 port = htons(atoi(servname));
984                 if (port < 0 || port > 65535)
985                         return EAI_SERVICE;
986         } else {
987                 switch (ai->ai_socktype) {
988                 case SOCK_DGRAM:
989                         proto = "udp";
990                         break;
991                 case SOCK_STREAM:
992                         proto = "tcp";
993                         break;
994                 default:
995                         proto = NULL;
996                         break;
997                 }
998
999                 if ((sp = getservbyname(servname, proto)) == NULL)
1000                         return EAI_SERVICE;
1001                 port = sp->s_port;
1002         }
1003
1004         if (!matchonly) {
1005                 switch (ai->ai_family) {
1006                 case AF_INET:
1007                         ((struct sockaddr_in *)(void *)
1008                             ai->ai_addr)->sin_port = port;
1009                         break;
1010 #ifdef INET6
1011                 case AF_INET6:
1012                         ((struct sockaddr_in6 *)(void *)
1013                             ai->ai_addr)->sin6_port = port;
1014                         break;
1015 #endif
1016                 }
1017         }
1018
1019         return 0;
1020 }
1021
1022 static const struct afd *
1023 find_afd(af)
1024         int af;
1025 {
1026         const struct afd *afd;
1027
1028         if (af == PF_UNSPEC)
1029                 return NULL;
1030         for (afd = afdl; afd->a_af; afd++) {
1031                 if (afd->a_af == af)
1032                         return afd;
1033         }
1034         return NULL;
1035 }
1036
1037 /*
1038  * post-2553: AI_ADDRCONFIG check.  if we use getipnodeby* as backend, backend
1039  * will take care of it.
1040  * the semantics of AI_ADDRCONFIG is not defined well.  we are not sure
1041  * if the code is right or not.
1042  *
1043  * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with
1044  * _dns_getaddrinfo.
1045  */
1046 static int
1047 addrconfig(pai)
1048         struct addrinfo *pai;
1049 {
1050         int s, af;
1051
1052         /*
1053          * TODO:
1054          * Note that implementation dependent test for address
1055          * configuration should be done everytime called
1056          * (or apropriate interval),
1057          * because addresses will be dynamically assigned or deleted.
1058          */
1059         af = pai->ai_family;
1060         if (af == AF_UNSPEC) {
1061                 if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1062                         af = AF_INET;
1063                 else {
1064                         close(s);
1065                         if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1066                                 af = AF_INET6;
1067                         else
1068                                 close(s);
1069                 }
1070         }
1071         if (af != AF_UNSPEC) {
1072                 if ((s = socket(af, SOCK_DGRAM, 0)) < 0)
1073                         return 0;
1074                 close(s);
1075         }
1076         pai->ai_family = af;
1077         return 1;
1078 }
1079
1080 #ifdef INET6
1081 /* convert a string to a scope identifier. XXX: IPv6 specific */
1082 static int
1083 ip6_str2scopeid(scope, sin6)
1084         char *scope;
1085         struct sockaddr_in6 *sin6;
1086 {
1087         int scopeid;
1088         struct in6_addr *a6 = &sin6->sin6_addr;
1089         char *ep;
1090
1091         /* empty scopeid portion is invalid */
1092         if (*scope == '\0')
1093                 return -1;
1094
1095         if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1096                 /*
1097                  * We currently assume a one-to-one mapping between links
1098                  * and interfaces, so we simply use interface indices for
1099                  * like-local scopes.
1100                  */
1101                 scopeid = if_nametoindex(scope);
1102                 if (scopeid == 0)
1103                         goto trynumeric;
1104                 return(scopeid);
1105         }
1106
1107         /* still unclear about literal, allow numeric only - placeholder */
1108         if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1109                 goto trynumeric;
1110         if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1111                 goto trynumeric;
1112         else
1113                 goto trynumeric;        /* global */
1114
1115         /* try to convert to a numeric id as a last resort */
1116   trynumeric:
1117         scopeid = (int)strtoul(scope, &ep, 10);
1118         if (*ep == '\0')
1119                 return scopeid;
1120         else
1121                 return -1;
1122 }
1123 #endif
1124
1125 #ifdef DEBUG
1126 static const char AskedForGot[] =
1127         "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1128 #endif
1129 static FILE *hostf = NULL;
1130
1131 static struct addrinfo *
1132 getanswer(answer, anslen, qname, qtype, pai)
1133         const querybuf *answer;
1134         int anslen;
1135         const char *qname;
1136         int qtype;
1137         const struct addrinfo *pai;
1138 {
1139         struct addrinfo sentinel, *cur;
1140         struct addrinfo ai;
1141         const struct afd *afd;
1142         char *canonname;
1143         const HEADER *hp;
1144         const u_char *cp;
1145         int n;
1146         const u_char *eom;
1147         char *bp;
1148         int type, class, buflen, ancount, qdcount;
1149         int haveanswer, had_error;
1150         char tbuf[MAXDNAME];
1151         int (*name_ok)(const char *);
1152         char hostbuf[8*1024];
1153
1154         memset(&sentinel, 0, sizeof(sentinel));
1155         cur = &sentinel;
1156
1157         canonname = NULL;
1158         eom = answer->buf + anslen;
1159         switch (qtype) {
1160         case T_A:
1161         case T_AAAA:
1162         case T_ANY:     /*use T_ANY only for T_A/T_AAAA lookup*/
1163                 name_ok = res_hnok;
1164                 break;
1165         default:
1166                 return (NULL);  /* XXX should be abort(); */
1167         }
1168         /*
1169          * find first satisfactory answer
1170          */
1171         hp = &answer->hdr;
1172         ancount = ntohs(hp->ancount);
1173         qdcount = ntohs(hp->qdcount);
1174         bp = hostbuf;
1175         buflen = sizeof hostbuf;
1176         cp = answer->buf + HFIXEDSZ;
1177         if (qdcount != 1) {
1178                 h_errno = NO_RECOVERY;
1179                 return (NULL);
1180         }
1181         n = dn_expand(answer->buf, eom, cp, bp, buflen);
1182         if ((n < 0) || !(*name_ok)(bp)) {
1183                 h_errno = NO_RECOVERY;
1184                 return (NULL);
1185         }
1186         cp += n + QFIXEDSZ;
1187         if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1188                 /* res_send() has already verified that the query name is the
1189                  * same as the one we sent; this just gets the expanded name
1190                  * (i.e., with the succeeding search-domain tacked on).
1191                  */
1192                 n = strlen(bp) + 1;             /* for the \0 */
1193                 if (n >= MAXHOSTNAMELEN) {
1194                         h_errno = NO_RECOVERY;
1195                         return (NULL);
1196                 }
1197                 canonname = bp;
1198                 bp += n;
1199                 buflen -= n;
1200                 /* The qname can be abbreviated, but h_name is now absolute. */
1201                 qname = canonname;
1202         }
1203         haveanswer = 0;
1204         had_error = 0;
1205         while (ancount-- > 0 && cp < eom && !had_error) {
1206                 n = dn_expand(answer->buf, eom, cp, bp, buflen);
1207                 if ((n < 0) || !(*name_ok)(bp)) {
1208                         had_error++;
1209                         continue;
1210                 }
1211                 cp += n;                        /* name */
1212                 type = _getshort(cp);
1213                 cp += INT16SZ;                  /* type */
1214                 class = _getshort(cp);
1215                 cp += INT16SZ + INT32SZ;        /* class, TTL */
1216                 n = _getshort(cp);
1217                 cp += INT16SZ;                  /* len */
1218                 if (class != C_IN) {
1219                         /* XXX - debug? syslog? */
1220                         cp += n;
1221                         continue;               /* XXX - had_error++ ? */
1222                 }
1223                 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1224                     type == T_CNAME) {
1225                         n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1226                         if ((n < 0) || !(*name_ok)(tbuf)) {
1227                                 had_error++;
1228                                 continue;
1229                         }
1230                         cp += n;
1231                         /* Get canonical name. */
1232                         n = strlen(tbuf) + 1;   /* for the \0 */
1233                         if (n > buflen || n >= MAXHOSTNAMELEN) {
1234                                 had_error++;
1235                                 continue;
1236                         }
1237                         strcpy(bp, tbuf);
1238                         canonname = bp;
1239                         bp += n;
1240                         buflen -= n;
1241                         continue;
1242                 }
1243                 if (qtype == T_ANY) {
1244                         if (!(type == T_A || type == T_AAAA)) {
1245                                 cp += n;
1246                                 continue;
1247                         }
1248                 } else if (type != qtype) {
1249 #ifdef DEBUG
1250                         if (type != T_KEY && type != T_SIG)
1251                                 syslog(LOG_NOTICE|LOG_AUTH,
1252                "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1253                                        qname, p_class(C_IN), p_type(qtype),
1254                                        p_type(type));
1255 #endif
1256                         cp += n;
1257                         continue;               /* XXX - had_error++ ? */
1258                 }
1259                 switch (type) {
1260                 case T_A:
1261                 case T_AAAA:
1262                         if (strcasecmp(canonname, bp) != 0) {
1263 #ifdef DEBUG
1264                                 syslog(LOG_NOTICE|LOG_AUTH,
1265                                        AskedForGot, canonname, bp);
1266 #endif
1267                                 cp += n;
1268                                 continue;       /* XXX - had_error++ ? */
1269                         }
1270                         if (type == T_A && n != INADDRSZ) {
1271                                 cp += n;
1272                                 continue;
1273                         }
1274                         if (type == T_AAAA && n != IN6ADDRSZ) {
1275                                 cp += n;
1276                                 continue;
1277                         }
1278 #ifdef FILTER_V4MAPPED
1279                         if (type == T_AAAA) {
1280                                 struct in6_addr in6;
1281                                 memcpy(&in6, cp, sizeof(in6));
1282                                 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1283                                         cp += n;
1284                                         continue;
1285                                 }
1286                         }
1287 #endif
1288                         if (!haveanswer) {
1289                                 int nn;
1290
1291                                 canonname = bp;
1292                                 nn = strlen(bp) + 1;    /* for the \0 */
1293                                 bp += nn;
1294                                 buflen -= nn;
1295                         }
1296
1297                         /* don't overwrite pai */
1298                         ai = *pai;
1299                         ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1300                         afd = find_afd(ai.ai_family);
1301                         if (afd == NULL) {
1302                                 cp += n;
1303                                 continue;
1304                         }
1305                         cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1306                         if (cur->ai_next == NULL)
1307                                 had_error++;
1308                         while (cur && cur->ai_next)
1309                                 cur = cur->ai_next;
1310                         cp += n;
1311                         break;
1312                 default:
1313                         abort();
1314                 }
1315                 if (!had_error)
1316                         haveanswer++;
1317         }
1318         if (haveanswer) {
1319                 if (!canonname)
1320                         (void)get_canonname(pai, sentinel.ai_next, qname);
1321                 else
1322                         (void)get_canonname(pai, sentinel.ai_next, canonname);
1323                 h_errno = NETDB_SUCCESS;
1324                 return sentinel.ai_next;
1325         }
1326
1327         h_errno = NO_RECOVERY;
1328         return NULL;
1329 }
1330
1331 /*ARGSUSED*/
1332 static int
1333 _dns_getaddrinfo(rv, cb_data, ap)
1334         void    *rv;
1335         void    *cb_data;
1336         va_list  ap;
1337 {
1338         struct addrinfo *ai;
1339         querybuf buf, buf2;
1340         const char *name;
1341         const struct addrinfo *pai;
1342         struct addrinfo sentinel, *cur;
1343         struct res_target q, q2;
1344
1345         name = va_arg(ap, char *);
1346         pai = va_arg(ap, const struct addrinfo *);
1347
1348         memset(&q, 0, sizeof(q2));
1349         memset(&q2, 0, sizeof(q2));
1350         memset(&sentinel, 0, sizeof(sentinel));
1351         cur = &sentinel;
1352
1353         switch (pai->ai_family) {
1354         case AF_UNSPEC:
1355                 /* prefer IPv6 */
1356                 q.qclass = C_IN;
1357                 q.qtype = T_AAAA;
1358                 q.answer = buf.buf;
1359                 q.anslen = sizeof(buf);
1360                 q.next = &q2;
1361                 q2.qclass = C_IN;
1362                 q2.qtype = T_A;
1363                 q2.answer = buf2.buf;
1364                 q2.anslen = sizeof(buf2);
1365                 break;
1366         case AF_INET:
1367                 q.qclass = C_IN;
1368                 q.qtype = T_A;
1369                 q.answer = buf.buf;
1370                 q.anslen = sizeof(buf);
1371                 break;
1372         case AF_INET6:
1373                 q.qclass = C_IN;
1374                 q.qtype = T_AAAA;
1375                 q.answer = buf.buf;
1376                 q.anslen = sizeof(buf);
1377                 break;
1378         default:
1379                 return NS_UNAVAIL;
1380         }
1381         if (res_searchN(name, &q) < 0)
1382                 return NS_NOTFOUND;
1383         ai = getanswer(&buf, q.n, q.name, q.qtype, pai);
1384         if (ai) {
1385                 cur->ai_next = ai;
1386                 while (cur && cur->ai_next)
1387                         cur = cur->ai_next;
1388         }
1389         if (q.next) {
1390                 ai = getanswer(&buf2, q2.n, q2.name, q2.qtype, pai);
1391                 if (ai)
1392                         cur->ai_next = ai;
1393         }
1394         if (sentinel.ai_next == NULL)
1395                 switch (h_errno) {
1396                 case HOST_NOT_FOUND:
1397                         return NS_NOTFOUND;
1398                 case TRY_AGAIN:
1399                         return NS_TRYAGAIN;
1400                 default:
1401                         return NS_UNAVAIL;
1402                 }
1403         *((struct addrinfo **)rv) = sentinel.ai_next;
1404         return NS_SUCCESS;
1405 }
1406
1407 static void
1408 _sethtent()
1409 {
1410         if (!hostf)
1411                 hostf = fopen(_PATH_HOSTS, "r" );
1412         else
1413                 rewind(hostf);
1414 }
1415
1416 static void
1417 _endhtent()
1418 {
1419         if (hostf) {
1420                 (void) fclose(hostf);
1421                 hostf = NULL;
1422         }
1423 }
1424
1425 static struct addrinfo *
1426 _gethtent(name, pai)
1427         const char *name;
1428         const struct addrinfo *pai;
1429 {
1430         char *p;
1431         char *cp, *tname, *cname;
1432         struct addrinfo hints, *res0, *res;
1433         int error;
1434         const char *addr;
1435         char hostbuf[8*1024];
1436
1437         if (!hostf && !(hostf = fopen(_PATH_HOSTS, "r" )))
1438                 return (NULL);
1439  again:
1440         if (!(p = fgets(hostbuf, sizeof hostbuf, hostf)))
1441                 return (NULL);
1442         if (*p == '#')
1443                 goto again;
1444         if (!(cp = strpbrk(p, "#\n")))
1445                 goto again;
1446         *cp = '\0';
1447         if (!(cp = strpbrk(p, " \t")))
1448                 goto again;
1449         *cp++ = '\0';
1450         addr = p;
1451         cname = NULL;
1452         /* if this is not something we're looking for, skip it. */
1453         while (cp && *cp) {
1454                 if (*cp == ' ' || *cp == '\t') {
1455                         cp++;
1456                         continue;
1457                 }
1458                 tname = cp;
1459                 if (cname == NULL)
1460                         cname = cp;
1461                 if ((cp = strpbrk(cp, " \t")) != NULL)
1462                         *cp++ = '\0';
1463                 if (strcasecmp(name, tname) == 0)
1464                         goto found;
1465         }
1466         goto again;
1467
1468 found:
1469         hints = *pai;
1470         hints.ai_flags = AI_NUMERICHOST;
1471         error = getaddrinfo(addr, NULL, &hints, &res0);
1472         if (error)
1473                 goto again;
1474 #ifdef FILTER_V4MAPPED
1475         /* XXX should check all items in the chain */
1476         if (res0->ai_family == AF_INET6 &&
1477             IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) {
1478                 freeaddrinfo(res0);
1479                 goto again;
1480         }
1481 #endif
1482         for (res = res0; res; res = res->ai_next) {
1483                 /* cover it up */
1484                 res->ai_flags = pai->ai_flags;
1485
1486                 if (pai->ai_flags & AI_CANONNAME) {
1487                         if (get_canonname(pai, res, cname) != 0) {
1488                                 freeaddrinfo(res0);
1489                                 goto again;
1490                         }
1491                 }
1492         }
1493         return res0;
1494 }
1495
1496 /*ARGSUSED*/
1497 static int
1498 _files_getaddrinfo(rv, cb_data, ap)
1499         void    *rv;
1500         void    *cb_data;
1501         va_list  ap;
1502 {
1503         const char *name;
1504         const struct addrinfo *pai;
1505         struct addrinfo sentinel, *cur;
1506         struct addrinfo *p;
1507
1508         name = va_arg(ap, char *);
1509         pai = va_arg(ap, struct addrinfo *);
1510
1511         memset(&sentinel, 0, sizeof(sentinel));
1512         cur = &sentinel;
1513
1514         _sethtent();
1515         while ((p = _gethtent(name, pai)) != NULL) {
1516                 cur->ai_next = p;
1517                 while (cur && cur->ai_next)
1518                         cur = cur->ai_next;
1519         }
1520         _endhtent();
1521
1522         *((struct addrinfo **)rv) = sentinel.ai_next;
1523         if (sentinel.ai_next == NULL)
1524                 return NS_NOTFOUND;
1525         return NS_SUCCESS;
1526 }
1527
1528 #ifdef YP
1529 static char *__ypdomain;
1530
1531 /*ARGSUSED*/
1532 static struct addrinfo *
1533 _yphostent(line, pai)
1534         char *line;
1535         const struct addrinfo *pai;
1536 {
1537         struct addrinfo sentinel, *cur;
1538         struct addrinfo hints, *res, *res0;
1539         int error;
1540         char *p = line;
1541         const char *addr, *canonname;
1542         char *nextline;
1543         char *cp;
1544
1545         addr = canonname = NULL;
1546
1547         memset(&sentinel, 0, sizeof(sentinel));
1548         cur = &sentinel;
1549
1550 nextline:
1551         /* terminate line */
1552         cp = strchr(p, '\n');
1553         if (cp) {
1554                 *cp++ = '\0';
1555                 nextline = cp;
1556         } else
1557                 nextline = NULL;
1558
1559         cp = strpbrk(p, " \t");
1560         if (cp == NULL) {
1561                 if (canonname == NULL)
1562                         return (NULL);
1563                 else
1564                         goto done;
1565         }
1566         *cp++ = '\0';
1567
1568         addr = p;
1569
1570         while (cp && *cp) {
1571                 if (*cp == ' ' || *cp == '\t') {
1572                         cp++;
1573                         continue;
1574                 }
1575                 if (!canonname)
1576                         canonname = cp;
1577                 if ((cp = strpbrk(cp, " \t")) != NULL)
1578                         *cp++ = '\0';
1579         }
1580
1581         hints = *pai;
1582         hints.ai_flags = AI_NUMERICHOST;
1583         error = getaddrinfo(addr, NULL, &hints, &res0);
1584         if (error == 0) {
1585                 for (res = res0; res; res = res->ai_next) {
1586                         /* cover it up */
1587                         res->ai_flags = pai->ai_flags;
1588
1589                         if (pai->ai_flags & AI_CANONNAME)
1590                                 (void)get_canonname(pai, res, canonname);
1591                 }
1592         } else
1593                 res0 = NULL;
1594         if (res0) {
1595                 cur->ai_next = res0;
1596                 while (cur && cur->ai_next)
1597                         cur = cur->ai_next;
1598         }
1599
1600         if (nextline) {
1601                 p = nextline;
1602                 goto nextline;
1603         }
1604
1605 done:
1606         return sentinel.ai_next;
1607 }
1608
1609 /*ARGSUSED*/
1610 static int
1611 _yp_getaddrinfo(rv, cb_data, ap)
1612         void    *rv;
1613         void    *cb_data;
1614         va_list  ap;
1615 {
1616         struct addrinfo sentinel, *cur;
1617         struct addrinfo *ai = NULL;
1618         static char *__ypcurrent;
1619         int __ypcurrentlen, r;
1620         const char *name;
1621         const struct addrinfo *pai;
1622
1623         name = va_arg(ap, char *);
1624         pai = va_arg(ap, const struct addrinfo *);
1625
1626         memset(&sentinel, 0, sizeof(sentinel));
1627         cur = &sentinel;
1628
1629         if (!__ypdomain) {
1630                 if (_yp_check(&__ypdomain) == 0)
1631                         return NS_UNAVAIL;
1632         }
1633         if (__ypcurrent)
1634                 free(__ypcurrent);
1635         __ypcurrent = NULL;
1636
1637         /* hosts.byname is only for IPv4 (Solaris8) */
1638         if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
1639                 r = yp_match(__ypdomain, "hosts.byname", name,
1640                         (int)strlen(name), &__ypcurrent, &__ypcurrentlen);
1641                 if (r == 0) {
1642                         struct addrinfo ai4;
1643
1644                         ai4 = *pai;
1645                         ai4.ai_family = AF_INET;
1646                         ai = _yphostent(__ypcurrent, &ai4);
1647                         if (ai) {
1648                                 cur->ai_next = ai;
1649                                 while (cur && cur->ai_next)
1650                                         cur = cur->ai_next;
1651                         }
1652                 }
1653         }
1654
1655         /* ipnodes.byname can hold both IPv4/v6 */
1656         r = yp_match(__ypdomain, "ipnodes.byname", name,
1657                 (int)strlen(name), &__ypcurrent, &__ypcurrentlen);
1658         if (r == 0) {
1659                 ai = _yphostent(__ypcurrent, pai);
1660                 if (ai) {
1661                         cur->ai_next = ai;
1662                         while (cur && cur->ai_next)
1663                                 cur = cur->ai_next;
1664                 }
1665         }
1666
1667         if (sentinel.ai_next == NULL) {
1668                 h_errno = HOST_NOT_FOUND;
1669                 return NS_NOTFOUND;
1670         }
1671         *((struct addrinfo **)rv) = sentinel.ai_next;
1672         return NS_SUCCESS;
1673 }
1674 #endif
1675
1676 /* resolver logic */
1677
1678 extern const char *__hostalias(const char *);
1679 extern int h_errno;
1680
1681 /*
1682  * Formulate a normal query, send, and await answer.
1683  * Returned answer is placed in supplied buffer "answer".
1684  * Perform preliminary check of answer, returning success only
1685  * if no error is indicated and the answer count is nonzero.
1686  * Return the size of the response on success, -1 on error.
1687  * Error number is left in h_errno.
1688  *
1689  * Caller must parse answer and determine whether it answers the question.
1690  */
1691 static int
1692 res_queryN(name, target)
1693         const char *name;       /* domain name */
1694         struct res_target *target;
1695 {
1696         u_char buf[MAXPACKET];
1697         HEADER *hp;
1698         int n;
1699         struct res_target *t;
1700         int rcode;
1701         int ancount;
1702
1703         rcode = NOERROR;
1704         ancount = 0;
1705
1706         if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1707                 h_errno = NETDB_INTERNAL;
1708                 return (-1);
1709         }
1710
1711         for (t = target; t; t = t->next) {
1712                 int class, type;
1713                 u_char *answer;
1714                 int anslen;
1715
1716                 hp = (HEADER *)(void *)t->answer;
1717                 hp->rcode = NOERROR;    /* default */
1718
1719                 /* make it easier... */
1720                 class = t->qclass;
1721                 type = t->qtype;
1722                 answer = t->answer;
1723                 anslen = t->anslen;
1724 #ifdef DEBUG
1725                 if (_res.options & RES_DEBUG)
1726                         printf(";; res_query(%s, %d, %d)\n", name, class, type);
1727 #endif
1728
1729                 n = res_mkquery(QUERY, name, class, type, NULL, 0, NULL,
1730                     buf, sizeof(buf));
1731                 if (n > 0 && (_res.options & RES_USE_EDNS0) != 0)
1732                         n = res_opt(n, buf, sizeof(buf), anslen);
1733                 if (n <= 0) {
1734 #ifdef DEBUG
1735                         if (_res.options & RES_DEBUG)
1736                                 printf(";; res_query: mkquery failed\n");
1737 #endif
1738                         h_errno = NO_RECOVERY;
1739                         return (n);
1740                 }
1741                 n = res_send(buf, n, answer, anslen);
1742 #if 0
1743                 if (n < 0) {
1744 #ifdef DEBUG
1745                         if (_res.options & RES_DEBUG)
1746                                 printf(";; res_query: send error\n");
1747 #endif
1748                         h_errno = TRY_AGAIN;
1749                         return (n);
1750                 }
1751 #endif
1752
1753                 if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
1754                         rcode = hp->rcode;      /* record most recent error */
1755 #ifdef DEBUG
1756                         if (_res.options & RES_DEBUG)
1757                                 printf(";; rcode = %d, ancount=%d\n", hp->rcode,
1758                                     ntohs(hp->ancount));
1759 #endif
1760                         continue;
1761                 }
1762
1763                 ancount += ntohs(hp->ancount);
1764
1765                 t->n = n;
1766         }
1767
1768         if (ancount == 0) {
1769                 switch (rcode) {
1770                 case NXDOMAIN:
1771                         h_errno = HOST_NOT_FOUND;
1772                         break;
1773                 case SERVFAIL:
1774                         h_errno = TRY_AGAIN;
1775                         break;
1776                 case NOERROR:
1777                         h_errno = NO_DATA;
1778                         break;
1779                 case FORMERR:
1780                 case NOTIMP:
1781                 case REFUSED:
1782                 default:
1783                         h_errno = NO_RECOVERY;
1784                         break;
1785                 }
1786                 return (-1);
1787         }
1788         return (ancount);
1789 }
1790
1791 /*
1792  * Formulate a normal query, send, and retrieve answer in supplied buffer.
1793  * Return the size of the response on success, -1 on error.
1794  * If enabled, implement search rules until answer or unrecoverable failure
1795  * is detected.  Error code, if any, is left in h_errno.
1796  */
1797 static int
1798 res_searchN(name, target)
1799         const char *name;       /* domain name */
1800         struct res_target *target;
1801 {
1802         const char *cp, * const *domain;
1803         HEADER *hp = (HEADER *)(void *)target->answer;  /*XXX*/
1804         u_int dots;
1805         int trailing_dot, ret, saved_herrno;
1806         int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
1807
1808         if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1809                 h_errno = NETDB_INTERNAL;
1810                 return (-1);
1811         }
1812
1813         errno = 0;
1814         h_errno = HOST_NOT_FOUND;       /* default, if we never query */
1815         dots = 0;
1816         for (cp = name; *cp; cp++)
1817                 dots += (*cp == '.');
1818         trailing_dot = 0;
1819         if (cp > name && *--cp == '.')
1820                 trailing_dot++;
1821
1822         /*
1823          * if there aren't any dots, it could be a user-level alias
1824          */
1825         if (!dots && (cp = __hostalias(name)) != NULL)
1826                 return (res_queryN(cp, target));
1827
1828         /*
1829          * If there are dots in the name already, let's just give it a try
1830          * 'as is'.  The threshold can be set with the "ndots" option.
1831          */
1832         saved_herrno = -1;
1833         if (dots >= _res.ndots) {
1834                 ret = res_querydomainN(name, NULL, target);
1835                 if (ret > 0)
1836                         return (ret);
1837                 saved_herrno = h_errno;
1838                 tried_as_is++;
1839         }
1840
1841         /*
1842          * We do at least one level of search if
1843          *      - there is no dot and RES_DEFNAME is set, or
1844          *      - there is at least one dot, there is no trailing dot,
1845          *        and RES_DNSRCH is set.
1846          */
1847         if ((!dots && (_res.options & RES_DEFNAMES)) ||
1848             (dots && !trailing_dot && (_res.options & RES_DNSRCH))) {
1849                 int done = 0;
1850
1851                 for (domain = (const char * const *)_res.dnsrch;
1852                    *domain && !done;
1853                    domain++) {
1854
1855                         ret = res_querydomainN(name, *domain, target);
1856                         if (ret > 0)
1857                                 return (ret);
1858
1859                         /*
1860                          * If no server present, give up.
1861                          * If name isn't found in this domain,
1862                          * keep trying higher domains in the search list
1863                          * (if that's enabled).
1864                          * On a NO_DATA error, keep trying, otherwise
1865                          * a wildcard entry of another type could keep us
1866                          * from finding this entry higher in the domain.
1867                          * If we get some other error (negative answer or
1868                          * server failure), then stop searching up,
1869                          * but try the input name below in case it's
1870                          * fully-qualified.
1871                          */
1872                         if (errno == ECONNREFUSED) {
1873                                 h_errno = TRY_AGAIN;
1874                                 return (-1);
1875                         }
1876
1877                         switch (h_errno) {
1878                         case NO_DATA:
1879                                 got_nodata++;
1880                                 /* FALLTHROUGH */
1881                         case HOST_NOT_FOUND:
1882                                 /* keep trying */
1883                                 break;
1884                         case TRY_AGAIN:
1885                                 if (hp->rcode == SERVFAIL) {
1886                                         /* try next search element, if any */
1887                                         got_servfail++;
1888                                         break;
1889                                 }
1890                                 /* FALLTHROUGH */
1891                         default:
1892                                 /* anything else implies that we're done */
1893                                 done++;
1894                         }
1895                         /*
1896                          * if we got here for some reason other than DNSRCH,
1897                          * we only wanted one iteration of the loop, so stop.
1898                          */
1899                         if (!(_res.options & RES_DNSRCH))
1900                                 done++;
1901                 }
1902         }
1903
1904         /*
1905          * if we have not already tried the name "as is", do that now.
1906          * note that we do this regardless of how many dots were in the
1907          * name or whether it ends with a dot.
1908          */
1909         if (!tried_as_is && (dots || !(_res.options & RES_NOTLDQUERY))) {
1910                 ret = res_querydomainN(name, NULL, target);
1911                 if (ret > 0)
1912                         return (ret);
1913         }
1914
1915         /*
1916          * if we got here, we didn't satisfy the search.
1917          * if we did an initial full query, return that query's h_errno
1918          * (note that we wouldn't be here if that query had succeeded).
1919          * else if we ever got a nodata, send that back as the reason.
1920          * else send back meaningless h_errno, that being the one from
1921          * the last DNSRCH we did.
1922          */
1923         if (saved_herrno != -1)
1924                 h_errno = saved_herrno;
1925         else if (got_nodata)
1926                 h_errno = NO_DATA;
1927         else if (got_servfail)
1928                 h_errno = TRY_AGAIN;
1929         return (-1);
1930 }
1931
1932 /*
1933  * Perform a call on res_query on the concatenation of name and domain,
1934  * removing a trailing dot from name if domain is NULL.
1935  */
1936 static int
1937 res_querydomainN(name, domain, target)
1938         const char *name, *domain;
1939         struct res_target *target;
1940 {
1941         char nbuf[MAXDNAME];
1942         const char *longname = nbuf;
1943         size_t n, d;
1944
1945         if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1946                 h_errno = NETDB_INTERNAL;
1947                 return (-1);
1948         }
1949 #ifdef DEBUG
1950         if (_res.options & RES_DEBUG)
1951                 printf(";; res_querydomain(%s, %s)\n",
1952                         name, domain?domain:"<Nil>");
1953 #endif
1954         if (domain == NULL) {
1955                 /*
1956                  * Check for trailing '.';
1957                  * copy without '.' if present.
1958                  */
1959                 n = strlen(name);
1960                 if (n >= MAXDNAME) {
1961                         h_errno = NO_RECOVERY;
1962                         return (-1);
1963                 }
1964                 if (n > 0 && name[--n] == '.') {
1965                         strncpy(nbuf, name, n);
1966                         nbuf[n] = '\0';
1967                 } else
1968                         longname = name;
1969         } else {
1970                 n = strlen(name);
1971                 d = strlen(domain);
1972                 if (n + d + 1 >= MAXDNAME) {
1973                         h_errno = NO_RECOVERY;
1974                         return (-1);
1975                 }
1976                 sprintf(nbuf, "%s.%s", name, domain);
1977         }
1978         return (res_queryN(longname, target));
1979 }