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