Merge from vendor branch TCSH:
[dragonfly.git] / contrib / bind-9.3 / lib / bind / irs / getaddrinfo.c
1 /*      $KAME: getaddrinfo.c,v 1.14 2001/01/06 09:41:15 jinmei 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  * Issues to be discussed:
34  * - Thread safe-ness must be checked.
35  * - Return values.  There are nonstandard return values defined and used
36  *   in the source code.  This is because RFC2553 is silent about which error
37  *   code must be returned for which situation.
38  * - IPv4 classful (shortened) form.  RFC2553 is silent about it.  XNET 5.2
39  *   says to use inet_aton() to convert IPv4 numeric to binary (allows
40  *   classful form as a result).
41  *   current code - disallow classful form for IPv4 (due to use of inet_pton).
42  * - freeaddrinfo(NULL).  RFC2553 is silent about it.  XNET 5.2 says it is
43  *   invalid.
44  *   current code - SEGV on freeaddrinfo(NULL)
45  * Note:
46  * - We use getipnodebyname() just for thread-safeness.  There's no intent
47  *   to let it do PF_UNSPEC (actually we never pass PF_UNSPEC to
48  *   getipnodebyname().
49  * - The code filters out AFs that are not supported by the kernel,
50  *   when globbing NULL hostname (to loopback, or wildcard).  Is it the right
51  *   thing to do?  What is the relationship with post-RFC2553 AI_ADDRCONFIG
52  *   in ai_flags?
53  * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
54  *   (1) what should we do against numeric hostname (2) what should we do
55  *   against NULL hostname (3) what is AI_ADDRCONFIG itself.  AF not ready?
56  *   non-loopback address configured?  global address configured?
57  * - To avoid search order issue, we have a big amount of code duplicate
58  *   from gethnamaddr.c and some other places.  The issues that there's no
59  *   lower layer function to lookup "IPv4 or IPv6" record.  Calling
60  *   gethostbyname2 from getaddrinfo will end up in wrong search order, as
61  *   follows:
62  *      - The code makes use of following calls when asked to resolver with
63  *        ai_family  = PF_UNSPEC:
64  *              getipnodebyname(host, AF_INET6);
65  *              getipnodebyname(host, AF_INET);
66  *        This will result in the following queries if the node is configure to
67  *        prefer /etc/hosts than DNS:
68  *              lookup /etc/hosts for IPv6 address
69  *              lookup DNS for IPv6 address
70  *              lookup /etc/hosts for IPv4 address
71  *              lookup DNS for IPv4 address
72  *        which may not meet people's requirement.
73  *        The right thing to happen is to have underlying layer which does
74  *        PF_UNSPEC lookup (lookup both) and return chain of addrinfos.
75  *        This would result in a bit of code duplicate with _dns_ghbyname() and
76  *        friends.
77  */
78
79 #include "port_before.h"
80
81 #include <sys/types.h>
82 #include <sys/param.h>
83 #include <sys/socket.h>
84
85 #include <net/if.h>
86 #include <netinet/in.h>
87
88 #include <arpa/inet.h>
89 #include <arpa/nameser.h>
90
91 #include <netdb.h>
92 #include <resolv.h>
93 #include <string.h>
94 #include <stdlib.h>
95 #include <stddef.h>
96 #include <ctype.h>
97 #include <unistd.h>
98 #include <stdio.h>
99 #include <errno.h>
100
101 #include <stdarg.h>
102
103 #include <irs.h>
104 #include <isc/assertions.h>
105
106 #include "port_after.h"
107
108 #include "irs_data.h"
109
110 #define SUCCESS 0
111 #define ANY 0
112 #define YES 1
113 #define NO  0
114
115 static const char in_addrany[] = { 0, 0, 0, 0 };
116 static const char in6_addrany[] = {
117         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
118 };
119 static const char in_loopback[] = { 127, 0, 0, 1 };
120 static const char in6_loopback[] = {
121         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
122 };
123
124 static const struct afd {
125         int a_af;
126         int a_addrlen;
127         int a_socklen;
128         int a_off;
129         const char *a_addrany;
130         const char *a_loopback;
131         int a_scoped;
132 } afdl [] = {
133         {PF_INET6, sizeof(struct in6_addr),
134          sizeof(struct sockaddr_in6),
135          offsetof(struct sockaddr_in6, sin6_addr),
136          in6_addrany, in6_loopback, 1},
137         {PF_INET, sizeof(struct in_addr),
138          sizeof(struct sockaddr_in),
139          offsetof(struct sockaddr_in, sin_addr),
140          in_addrany, in_loopback, 0},
141         {0, 0, 0, 0, NULL, NULL, 0},
142 };
143
144 struct explore {
145         int e_af;
146         int e_socktype;
147         int e_protocol;
148         const char *e_protostr;
149         int e_wild;
150 #define WILD_AF(ex)             ((ex)->e_wild & 0x01)
151 #define WILD_SOCKTYPE(ex)       ((ex)->e_wild & 0x02)
152 #define WILD_PROTOCOL(ex)       ((ex)->e_wild & 0x04)
153 };
154
155 static const struct explore explore[] = {
156 #if 0
157         { PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
158 #endif
159         { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
160         { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
161         { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
162         { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
163         { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
164         { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
165         { -1, 0, 0, NULL, 0 },
166 };
167
168 #define PTON_MAX        16
169
170 static int str_isnumber __P((const char *));
171 static int explore_fqdn __P((const struct addrinfo *, const char *,
172         const char *, struct addrinfo **));
173 static int explore_copy __P((const struct addrinfo *, const struct addrinfo *,
174         struct addrinfo **));
175 static int explore_null __P((const struct addrinfo *,
176         const char *, struct addrinfo **));
177 static int explore_numeric __P((const struct addrinfo *, const char *,
178         const char *, struct addrinfo **));
179 static int explore_numeric_scope __P((const struct addrinfo *, const char *,
180         const char *, struct addrinfo **));
181 static int get_canonname __P((const struct addrinfo *,
182         struct addrinfo *, const char *));
183 static struct addrinfo *get_ai __P((const struct addrinfo *,
184         const struct afd *, const char *));
185 static struct addrinfo *copy_ai __P((const struct addrinfo *));
186 static int get_portmatch __P((const struct addrinfo *, const char *));
187 static int get_port __P((const struct addrinfo *, const char *, int));
188 static const struct afd *find_afd __P((int));
189 static int addrconfig __P((int));
190 static int ip6_str2scopeid __P((char *, struct sockaddr_in6 *,
191                                 u_int32_t *scopeidp));
192 static struct net_data *init __P((void));
193
194 struct addrinfo *hostent2addrinfo __P((struct hostent *,
195                                        const struct addrinfo *));
196 struct addrinfo *addr2addrinfo __P((const struct addrinfo *,
197                                     const char *));
198
199 #if 0
200 static const char *ai_errlist[] = {
201         "Success",
202         "Address family for hostname not supported",    /* EAI_ADDRFAMILY */
203         "Temporary failure in name resolution",         /* EAI_AGAIN      */
204         "Invalid value for ai_flags",                   /* EAI_BADFLAGS   */
205         "Non-recoverable failure in name resolution",   /* EAI_FAIL       */
206         "ai_family not supported",                      /* EAI_FAMILY     */
207         "Memory allocation failure",                    /* EAI_MEMORY     */
208         "No address associated with hostname",          /* EAI_NODATA     */
209         "hostname nor servname provided, or not known", /* EAI_NONAME     */
210         "servname not supported for ai_socktype",       /* EAI_SERVICE    */
211         "ai_socktype not supported",                    /* EAI_SOCKTYPE   */
212         "System error returned in errno",               /* EAI_SYSTEM     */
213         "Invalid value for hints",                      /* EAI_BADHINTS   */
214         "Resolved protocol is unknown",                 /* EAI_PROTOCOL   */
215         "Unknown error",                                /* EAI_MAX        */
216 };
217 #endif
218
219 /* XXX macros that make external reference is BAD. */
220
221 #define GET_AI(ai, afd, addr) \
222 do { \
223         /* external reference: pai, error, and label free */ \
224         (ai) = get_ai(pai, (afd), (addr)); \
225         if ((ai) == NULL) { \
226                 error = EAI_MEMORY; \
227                 goto free; \
228         } \
229 } while (/*CONSTCOND*/0)
230
231 #define GET_PORT(ai, serv) \
232 do { \
233         /* external reference: error and label free */ \
234         error = get_port((ai), (serv), 0); \
235         if (error != 0) \
236                 goto free; \
237 } while (/*CONSTCOND*/0)
238
239 #define GET_CANONNAME(ai, str) \
240 do { \
241         /* external reference: pai, error and label free */ \
242         error = get_canonname(pai, (ai), (str)); \
243         if (error != 0) \
244                 goto free; \
245 } while (/*CONSTCOND*/0)
246
247 #ifndef SOLARIS2
248 #define SETERROR(err) \
249 do { \
250         /* external reference: error, and label bad */ \
251         error = (err); \
252         goto bad; \
253         /*NOTREACHED*/ \
254 } while (/*CONSTCOND*/0)
255 #else
256 #define SETERROR(err) \
257 do { \
258         /* external reference: error, and label bad */ \
259         error = (err); \
260         if (error == error) \
261                 goto bad; \
262 } while (/*CONSTCOND*/0)
263 #endif
264
265
266 #define MATCH_FAMILY(x, y, w) \
267         ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
268 #define MATCH(x, y, w) \
269         ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
270
271 #if 0                           /* bind8 has its own version */
272 char *
273 gai_strerror(ecode)
274         int ecode;
275 {
276         if (ecode < 0 || ecode > EAI_MAX)
277                 ecode = EAI_MAX;
278         return ai_errlist[ecode];
279 }
280 #endif
281
282 void
283 freeaddrinfo(ai)
284         struct addrinfo *ai;
285 {
286         struct addrinfo *next;
287
288         do {
289                 next = ai->ai_next;
290                 if (ai->ai_canonname)
291                         free(ai->ai_canonname);
292                 /* no need to free(ai->ai_addr) */
293                 free(ai);
294                 ai = next;
295         } while (ai);
296 }
297
298 static int
299 str_isnumber(p)
300         const char *p;
301 {
302         char *ep;
303
304         if (*p == '\0')
305                 return NO;
306         ep = NULL;
307         errno = 0;
308         (void)strtoul(p, &ep, 10);
309         if (errno == 0 && ep && *ep == '\0')
310                 return YES;
311         else
312                 return NO;
313 }
314
315 int
316 getaddrinfo(hostname, servname, hints, res)
317         const char *hostname, *servname;
318         const struct addrinfo *hints;
319         struct addrinfo **res;
320 {
321         struct addrinfo sentinel;
322         struct addrinfo *cur;
323         int error = 0;
324         struct addrinfo ai, ai0, *afai = NULL;
325         struct addrinfo *pai;
326         const struct explore *ex;
327
328         memset(&sentinel, 0, sizeof(sentinel));
329         cur = &sentinel;
330         pai = &ai;
331         pai->ai_flags = 0;
332         pai->ai_family = PF_UNSPEC;
333         pai->ai_socktype = ANY;
334         pai->ai_protocol = ANY;
335 #if defined(sun) && defined(_SOCKLEN_T) && defined(__sparcv9)
336         /*
337          * clear _ai_pad to preserve binary
338          * compatibility with previously compiled 64-bit
339          * applications in a pre-SUSv3 environment by
340          * guaranteeing the upper 32-bits are empty.
341          */
342         pai->_ai_pad = 0;
343 #endif
344         pai->ai_addrlen = 0;
345         pai->ai_canonname = NULL;
346         pai->ai_addr = NULL;
347         pai->ai_next = NULL;
348
349         if (hostname == NULL && servname == NULL)
350                 return EAI_NONAME;
351         if (hints) {
352                 /* error check for hints */
353                 if (hints->ai_addrlen || hints->ai_canonname ||
354                     hints->ai_addr || hints->ai_next)
355                         SETERROR(EAI_BADHINTS); /* xxx */
356                 if (hints->ai_flags & ~AI_MASK)
357                         SETERROR(EAI_BADFLAGS);
358                 switch (hints->ai_family) {
359                 case PF_UNSPEC:
360                 case PF_INET:
361                 case PF_INET6:
362                         break;
363                 default:
364                         SETERROR(EAI_FAMILY);
365                 }
366                 memcpy(pai, hints, sizeof(*pai));
367
368 #if defined(sun) && defined(_SOCKLEN_T) && defined(__sparcv9)
369                 /*
370                  * We need to clear _ai_pad to preserve binary
371                  * compatibility.  See prior comment.
372                  */
373                 pai->_ai_pad = 0;
374 #endif
375                 /*
376                  * if both socktype/protocol are specified, check if they
377                  * are meaningful combination.
378                  */
379                 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
380                         for (ex = explore; ex->e_af >= 0; ex++) {
381                                 if (pai->ai_family != ex->e_af)
382                                         continue;
383                                 if (ex->e_socktype == ANY)
384                                         continue;
385                                 if (ex->e_protocol == ANY)
386                                         continue;
387                                 if (pai->ai_socktype == ex->e_socktype &&
388                                     pai->ai_protocol != ex->e_protocol) {
389                                         SETERROR(EAI_BADHINTS);
390                                 }
391                         }
392                 }
393         }
394
395         /*
396          * post-2553: AI_ALL and AI_V4MAPPED are effective only against
397          * AF_INET6 query.  They needs to be ignored if specified in other
398          * occassions.
399          */
400         switch (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) {
401         case AI_V4MAPPED:
402         case AI_ALL | AI_V4MAPPED:
403                 if (pai->ai_family != AF_INET6)
404                         pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
405                 break;
406         case AI_ALL:
407 #if 1
408                 /* illegal */
409                 SETERROR(EAI_BADFLAGS);
410 #else
411                 pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
412                 break;
413 #endif
414         }
415
416         /*
417          * check for special cases.  (1) numeric servname is disallowed if
418          * socktype/protocol are left unspecified. (2) servname is disallowed
419          * for raw and other inet{,6} sockets.
420          */
421         if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
422 #ifdef PF_INET6
423          || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
424 #endif
425             ) {
426                 ai0 = *pai;     /* backup *pai */
427
428                 if (pai->ai_family == PF_UNSPEC) {
429 #ifdef PF_INET6
430                         pai->ai_family = PF_INET6;
431 #else
432                         pai->ai_family = PF_INET;
433 #endif
434                 }
435                 error = get_portmatch(pai, servname);
436                 if (error)
437                         SETERROR(error);
438
439                 *pai = ai0;
440         }
441
442         ai0 = *pai;
443
444         /* NULL hostname, or numeric hostname */
445         for (ex = explore; ex->e_af >= 0; ex++) {
446                 *pai = ai0;
447
448                 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
449                         continue;
450                 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
451                         continue;
452                 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
453                         continue;
454
455                 if (pai->ai_family == PF_UNSPEC)
456                         pai->ai_family = ex->e_af;
457                 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
458                         pai->ai_socktype = ex->e_socktype;
459                 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
460                         pai->ai_protocol = ex->e_protocol;
461
462                 /*
463                  * if the servname does not match socktype/protocol, ignore it.
464                  */
465                 if (get_portmatch(pai, servname) != 0)
466                         continue;
467
468                 if (hostname == NULL) {
469                         /*
470                          * filter out AFs that are not supported by the kernel
471                          * XXX errno?
472                          */
473                         if (!addrconfig(pai->ai_family))
474                                 continue;
475                         error = explore_null(pai, servname, &cur->ai_next);
476                 } else
477                         error = explore_numeric_scope(pai, hostname, servname,
478                             &cur->ai_next);
479
480                 if (error)
481                         goto free;
482
483                 while (cur && cur->ai_next)
484                         cur = cur->ai_next;
485         }
486
487         /*
488          * XXX
489          * If numreic representation of AF1 can be interpreted as FQDN
490          * representation of AF2, we need to think again about the code below.
491          */
492         if (sentinel.ai_next)
493                 goto good;
494
495         if (pai->ai_flags & AI_NUMERICHOST)
496                 SETERROR(EAI_NONAME);
497         if (hostname == NULL)
498                 SETERROR(EAI_NONAME);
499
500         /*
501          * hostname as alphabetical name.
502          * We'll make sure that
503          * - if returning addrinfo list is empty, return non-zero error
504          *   value (already known one or EAI_NONAME).
505          * - otherwise, 
506          *   + if we haven't had any errors, return 0 (i.e. success).
507          *   + if we've had an error, free the list and return the error.
508          * without any assumption on the behavior of explore_fqdn().
509          */
510
511         /* first, try to query DNS for all possible address families. */
512         *pai = ai0;
513         error = explore_fqdn(pai, hostname, servname, &afai);
514         if (error) {
515                 if (afai != NULL)
516                         freeaddrinfo(afai);
517                 goto free;
518         }
519         if (afai == NULL) {
520                 error = EAI_NONAME; /* we've had no errors. */
521                 goto free;
522         }
523
524         /*
525          * we would like to prefer AF_INET6 than AF_INET, so we'll make an
526          * outer loop by AFs.
527          */
528         for (ex = explore; ex->e_af >= 0; ex++) {
529                 *pai = ai0;
530
531                 if (pai->ai_family == PF_UNSPEC)
532                         pai->ai_family = ex->e_af;
533
534                 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
535                         continue;
536                 if (!MATCH(pai->ai_socktype, ex->e_socktype,
537                            WILD_SOCKTYPE(ex))) {
538                         continue;
539                 }
540                 if (!MATCH(pai->ai_protocol, ex->e_protocol,
541                            WILD_PROTOCOL(ex))) {
542                         continue;
543                 }
544
545 #ifdef AI_ADDRCONFIG
546                 /*
547                  * If AI_ADDRCONFIG is specified, check if we are
548                  * expected to return the address family or not.
549                  */
550                 if ((pai->ai_flags & AI_ADDRCONFIG) != 0 &&
551                     !addrconfig(pai->ai_family))
552                         continue;
553 #endif
554
555                 if (pai->ai_family == PF_UNSPEC)
556                         pai->ai_family = ex->e_af;
557                 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
558                         pai->ai_socktype = ex->e_socktype;
559                 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
560                         pai->ai_protocol = ex->e_protocol;
561
562                 /*
563                  * if the servname does not match socktype/protocol, ignore it.
564                  */
565                 if (get_portmatch(pai, servname) != 0)
566                         continue;
567
568                 if ((error = explore_copy(pai, afai, &cur->ai_next)) != 0) {
569                         freeaddrinfo(afai);
570                         goto free;
571                 }
572
573                 while (cur && cur->ai_next)
574                         cur = cur->ai_next;
575         }
576
577         freeaddrinfo(afai);     /* afai must not be NULL at this point. */
578
579         if (sentinel.ai_next) {
580 good:
581                 *res = sentinel.ai_next;
582                 return(SUCCESS);
583         } else {
584                 /*
585                  * All the process succeeded, but we've had an empty list. 
586                  * This can happen if the given hints do not match our
587                  * candidates.
588                  */
589                 error = EAI_NONAME;
590         }
591
592 free:
593 bad:
594         if (sentinel.ai_next)
595                 freeaddrinfo(sentinel.ai_next);
596         *res = NULL;
597         return(error);
598 }
599
600 /*
601  * FQDN hostname, DNS lookup
602  */
603 static int
604 explore_fqdn(pai, hostname, servname, res)
605         const struct addrinfo *pai;
606         const char *hostname;
607         const char *servname;
608         struct addrinfo **res;
609 {
610         struct addrinfo *result;
611         struct addrinfo *cur;
612         struct net_data *net_data = init();
613         struct irs_ho *ho;
614         int error = 0;
615         char tmp[NS_MAXDNAME];
616         const char *cp;
617
618         INSIST(res != NULL && *res == NULL);
619
620         /*
621          * if the servname does not match socktype/protocol, ignore it.
622          */
623         if (get_portmatch(pai, servname) != 0)
624                 return(0);
625
626         if (!net_data || !(ho = net_data->ho))
627                 return(0);
628 #if 0                           /* XXX (notyet) */
629         if (net_data->ho_stayopen && net_data->ho_last &&
630             net_data->ho_last->h_addrtype == af) {
631                 if (ns_samename(name, net_data->ho_last->h_name) == 1)
632                         return (net_data->ho_last);
633                 for (hap = net_data->ho_last->h_aliases; hap && *hap; hap++)
634                         if (ns_samename(name, *hap) == 1)
635                                 return (net_data->ho_last);
636         }
637 #endif
638         if (!strchr(hostname, '.') &&
639             (cp = res_hostalias(net_data->res, hostname,
640                                 tmp, sizeof(tmp))))
641                 hostname = cp;
642         result = (*ho->addrinfo)(ho, hostname, pai);
643         if (!net_data->ho_stayopen) {
644                 (*ho->minimize)(ho);
645         }
646         if (result == NULL) {
647                 int e = h_errno;
648
649                 switch(e) {
650                 case NETDB_INTERNAL:
651                         error = EAI_SYSTEM;
652                         break;
653                 case TRY_AGAIN:
654                         error = EAI_AGAIN;
655                         break;
656                 case NO_RECOVERY:
657                         error = EAI_FAIL;
658                         break;
659                 case HOST_NOT_FOUND:
660                 case NO_DATA:
661                         error = EAI_NONAME;
662                         break;
663                 default:
664                 case NETDB_SUCCESS: /* should be impossible... */
665                         error = EAI_NONAME;
666                         break;
667                 }
668                 goto free;
669         }
670
671         for (cur = result; cur; cur = cur->ai_next) {
672                 GET_PORT(cur, servname); /* XXX: redundant lookups... */
673                 /* canonname should already be filled. */
674         }
675
676         *res = result;
677
678         return(0);
679
680 free:
681         if (result)
682                 freeaddrinfo(result);
683         return error;
684 }
685
686 static int
687 explore_copy(pai, src0, res)
688         const struct addrinfo *pai;     /* seed */
689         const struct addrinfo *src0;    /* source */
690         struct addrinfo **res;
691 {
692         int error;
693         struct addrinfo sentinel, *cur;
694         const struct addrinfo *src;
695
696         error = 0;
697         sentinel.ai_next = NULL;
698         cur = &sentinel;
699
700         for (src = src0; src != NULL; src = src->ai_next) {
701                 if (src->ai_family != pai->ai_family)
702                         continue;
703
704                 cur->ai_next = copy_ai(src);
705                 if (!cur->ai_next) {
706                         error = EAI_MEMORY;
707                         goto fail;
708                 }
709
710                 cur->ai_next->ai_socktype = pai->ai_socktype;
711                 cur->ai_next->ai_protocol = pai->ai_protocol;
712                 cur = cur->ai_next;
713         }
714
715         *res = sentinel.ai_next;
716         return 0;
717
718 fail:
719         freeaddrinfo(sentinel.ai_next);
720         return error;
721 }
722
723 /*
724  * hostname == NULL.
725  * passive socket -> anyaddr (0.0.0.0 or ::)
726  * non-passive socket -> localhost (127.0.0.1 or ::1)
727  */
728 static int
729 explore_null(pai, servname, res)
730         const struct addrinfo *pai;
731         const char *servname;
732         struct addrinfo **res;
733 {
734         const struct afd *afd;
735         struct addrinfo *cur;
736         struct addrinfo sentinel;
737         int error;
738
739         *res = NULL;
740         sentinel.ai_next = NULL;
741         cur = &sentinel;
742
743         afd = find_afd(pai->ai_family);
744         if (afd == NULL)
745                 return 0;
746
747         if (pai->ai_flags & AI_PASSIVE) {
748                 GET_AI(cur->ai_next, afd, afd->a_addrany);
749                 /* xxx meaningless?
750                  * GET_CANONNAME(cur->ai_next, "anyaddr");
751                  */
752                 GET_PORT(cur->ai_next, servname);
753         } else {
754                 GET_AI(cur->ai_next, afd, afd->a_loopback);
755                 /* xxx meaningless?
756                  * GET_CANONNAME(cur->ai_next, "localhost");
757                  */
758                 GET_PORT(cur->ai_next, servname);
759         }
760         cur = cur->ai_next;
761
762         *res = sentinel.ai_next;
763         return 0;
764
765 free:
766         if (sentinel.ai_next)
767                 freeaddrinfo(sentinel.ai_next);
768         return error;
769 }
770
771 /*
772  * numeric hostname
773  */
774 static int
775 explore_numeric(pai, hostname, servname, res)
776         const struct addrinfo *pai;
777         const char *hostname;
778         const char *servname;
779         struct addrinfo **res;
780 {
781         const struct afd *afd;
782         struct addrinfo *cur;
783         struct addrinfo sentinel;
784         int error;
785         char pton[PTON_MAX];
786
787         *res = NULL;
788         sentinel.ai_next = NULL;
789         cur = &sentinel;
790
791         afd = find_afd(pai->ai_family);
792         if (afd == NULL)
793                 return 0;
794
795         switch (afd->a_af) {
796 #if 0 /*X/Open spec*/
797         case AF_INET:
798                 if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
799                         if (pai->ai_family == afd->a_af ||
800                             pai->ai_family == PF_UNSPEC /*?*/) {
801                                 GET_AI(cur->ai_next, afd, pton);
802                                 GET_PORT(cur->ai_next, servname);
803                                 while (cur->ai_next)
804                                         cur = cur->ai_next;
805                         } else
806                                 SETERROR(EAI_FAMILY);   /*xxx*/
807                 }
808                 break;
809 #endif
810         default:
811                 if (inet_pton(afd->a_af, hostname, pton) == 1) {
812                         if (pai->ai_family == afd->a_af ||
813                             pai->ai_family == PF_UNSPEC /*?*/) {
814                                 GET_AI(cur->ai_next, afd, pton);
815                                 GET_PORT(cur->ai_next, servname);
816                                 while (cur->ai_next)
817                                         cur = cur->ai_next;
818                         } else
819                                 SETERROR(EAI_FAMILY);   /*xxx*/
820                 }
821                 break;
822         }
823
824         *res = sentinel.ai_next;
825         return 0;
826
827 free:
828 bad:
829         if (sentinel.ai_next)
830                 freeaddrinfo(sentinel.ai_next);
831         return error;
832 }
833
834 /*
835  * numeric hostname with scope
836  */
837 static int
838 explore_numeric_scope(pai, hostname, servname, res)
839         const struct addrinfo *pai;
840         const char *hostname;
841         const char *servname;
842         struct addrinfo **res;
843 {
844 #ifndef SCOPE_DELIMITER
845         return explore_numeric(pai, hostname, servname, res);
846 #else
847         const struct afd *afd;
848         struct addrinfo *cur;
849         int error;
850         char *cp, *hostname2 = NULL, *scope, *addr;
851         struct sockaddr_in6 *sin6;
852
853         afd = find_afd(pai->ai_family);
854         if (afd == NULL)
855                 return 0;
856
857         if (!afd->a_scoped)
858                 return explore_numeric(pai, hostname, servname, res);
859
860         cp = strchr(hostname, SCOPE_DELIMITER);
861         if (cp == NULL)
862                 return explore_numeric(pai, hostname, servname, res);
863
864         /*
865          * Handle special case of <scoped_address><delimiter><scope id>
866          */
867         hostname2 = strdup(hostname);
868         if (hostname2 == NULL)
869                 return EAI_MEMORY;
870         /* terminate at the delimiter */
871         hostname2[cp - hostname] = '\0';
872         addr = hostname2;
873         scope = cp + 1;
874
875         error = explore_numeric(pai, addr, servname, res);
876         if (error == 0) {
877                 u_int32_t scopeid = 0;
878
879                 for (cur = *res; cur; cur = cur->ai_next) {
880                         if (cur->ai_family != AF_INET6)
881                                 continue;
882                         sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
883                         if (!ip6_str2scopeid(scope, sin6, &scopeid)) {
884                                 free(hostname2);
885                                 return(EAI_NONAME); /* XXX: is return OK? */
886                         }
887 #ifdef HAVE_SIN6_SCOPE_ID
888                         sin6->sin6_scope_id = scopeid;
889 #endif
890                 }
891         }
892
893         free(hostname2);
894
895         return error;
896 #endif
897 }
898
899 static int
900 get_canonname(pai, ai, str)
901         const struct addrinfo *pai;
902         struct addrinfo *ai;
903         const char *str;
904 {
905         if ((pai->ai_flags & AI_CANONNAME) != 0) {
906                 ai->ai_canonname = (char *)malloc(strlen(str) + 1);
907                 if (ai->ai_canonname == NULL)
908                         return EAI_MEMORY;
909                 strcpy(ai->ai_canonname, str);
910         }
911         return 0;
912 }
913
914 static struct addrinfo *
915 get_ai(pai, afd, addr)
916         const struct addrinfo *pai;
917         const struct afd *afd;
918         const char *addr;
919 {
920         char *p;
921         struct addrinfo *ai;
922
923         ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
924                 + (afd->a_socklen));
925         if (ai == NULL)
926                 return NULL;
927
928         memcpy(ai, pai, sizeof(struct addrinfo));
929         ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
930         memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
931 #ifdef HAVE_SA_LEN
932         ai->ai_addr->sa_len = afd->a_socklen;
933 #endif
934         ai->ai_addrlen = afd->a_socklen;
935         ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
936         p = (char *)(void *)(ai->ai_addr);
937         memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
938         return ai;
939 }
940
941 /* XXX need to malloc() the same way we do from other functions! */
942 static struct addrinfo *
943 copy_ai(pai)
944         const struct addrinfo *pai;
945 {
946         struct addrinfo *ai;
947         size_t l;
948
949         l = sizeof(*ai) + pai->ai_addrlen;
950         if ((ai = (struct addrinfo *)malloc(l)) == NULL)
951                 return NULL;
952         memset(ai, 0, l);
953         memcpy(ai, pai, sizeof(*ai));
954         ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
955         memcpy(ai->ai_addr, pai->ai_addr, pai->ai_addrlen);
956
957         if (pai->ai_canonname) {
958                 l = strlen(pai->ai_canonname) + 1;
959                 if ((ai->ai_canonname = malloc(l)) == NULL) {
960                         free(ai);
961                         return NULL;
962                 }
963                 strcpy(ai->ai_canonname, pai->ai_canonname);    /* (checked) */
964         } else {
965                 /* just to make sure */
966                 ai->ai_canonname = NULL;
967         }
968
969         ai->ai_next = NULL;
970
971         return ai;
972 }
973
974 static int
975 get_portmatch(const struct addrinfo *ai, const char *servname) {
976
977         /* get_port does not touch first argument. when matchonly == 1. */
978         /* LINTED const cast */
979         return get_port((const struct addrinfo *)ai, servname, 1);
980 }
981
982 static int
983 get_port(const struct addrinfo *ai, const char *servname, int matchonly) {
984         const char *proto;
985         struct servent *sp;
986         int port;
987         int allownumeric;
988
989         if (servname == NULL)
990                 return 0;
991         switch (ai->ai_family) {
992         case AF_INET:
993 #ifdef AF_INET6
994         case AF_INET6:
995 #endif
996                 break;
997         default:
998                 return 0;
999         }
1000
1001         switch (ai->ai_socktype) {
1002         case SOCK_RAW:
1003                 return EAI_SERVICE;
1004         case SOCK_DGRAM:
1005         case SOCK_STREAM:
1006                 allownumeric = 1;
1007                 break;
1008         case ANY:
1009                 switch (ai->ai_family) {
1010                 case AF_INET:
1011 #ifdef AF_INET6
1012                 case AF_INET6:
1013 #endif
1014                         allownumeric = 1;
1015                         break;
1016                 default:
1017                         allownumeric = 0;
1018                         break;
1019                 }
1020                 break;
1021         default:
1022                 return EAI_SOCKTYPE;
1023         }
1024
1025         if (str_isnumber(servname)) {
1026                 if (!allownumeric)
1027                         return EAI_SERVICE;
1028                 port = atoi(servname);
1029                 if (port < 0 || port > 65535)
1030                         return EAI_SERVICE;
1031                 port = htons(port);
1032         } else {
1033                 switch (ai->ai_socktype) {
1034                 case SOCK_DGRAM:
1035                         proto = "udp";
1036                         break;
1037                 case SOCK_STREAM:
1038                         proto = "tcp";
1039                         break;
1040                 default:
1041                         proto = NULL;
1042                         break;
1043                 }
1044
1045                 if ((sp = getservbyname(servname, proto)) == NULL)
1046                         return EAI_SERVICE;
1047                 port = sp->s_port;
1048         }
1049
1050         if (!matchonly) {
1051                 switch (ai->ai_family) {
1052                 case AF_INET:
1053                         ((struct sockaddr_in *)(void *)
1054                             ai->ai_addr)->sin_port = port;
1055                         break;
1056                 case AF_INET6:
1057                         ((struct sockaddr_in6 *)(void *)
1058                             ai->ai_addr)->sin6_port = port;
1059                         break;
1060                 }
1061         }
1062
1063         return 0;
1064 }
1065
1066 static const struct afd *
1067 find_afd(af)
1068         int af;
1069 {
1070         const struct afd *afd;
1071
1072         if (af == PF_UNSPEC)
1073                 return NULL;
1074         for (afd = afdl; afd->a_af; afd++) {
1075                 if (afd->a_af == af)
1076                         return afd;
1077         }
1078         return NULL;
1079 }
1080
1081 /*
1082  * post-2553: AI_ADDRCONFIG check.  if we use getipnodeby* as backend, backend
1083  * will take care of it.
1084  * the semantics of AI_ADDRCONFIG is not defined well.  we are not sure
1085  * if the code is right or not.
1086  */
1087 static int
1088 addrconfig(af)
1089         int af;
1090 {
1091         int s;
1092
1093         /* XXX errno */
1094         s = socket(af, SOCK_DGRAM, 0);
1095         if (s < 0) {
1096                 if (errno != EMFILE)
1097                         return 0;
1098         } else
1099                 close(s);
1100         return 1;
1101 }
1102
1103 /* convert a string to a scope identifier. XXX: IPv6 specific */
1104 static int
1105 ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6,
1106                 u_int32_t *scopeidp)
1107 {
1108         u_int32_t scopeid;
1109         u_long lscopeid;
1110         struct in6_addr *a6 = &sin6->sin6_addr;
1111         char *ep;
1112         
1113         /* empty scopeid portion is invalid */
1114         if (*scope == '\0')
1115                 return (0);
1116
1117 #ifdef USE_IFNAMELINKID
1118         if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6) ||
1119             IN6_IS_ADDR_MC_NODELOCAL(a6)) {
1120                 /*
1121                  * Using interface names as link indices can be allowed
1122                  * only when we can assume a one-to-one mappings between
1123                  * links and interfaces.  See comments in getnameinfo.c.
1124                  */
1125                 scopeid = if_nametoindex(scope);
1126                 if (scopeid == 0)
1127                         goto trynumeric;
1128                 *scopeidp = scopeid;
1129                 return (1);
1130         }
1131 #endif
1132
1133         /* still unclear about literal, allow numeric only - placeholder */
1134         if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1135                 goto trynumeric;
1136         if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1137                 goto trynumeric;
1138         else
1139                 goto trynumeric;        /* global */
1140
1141         /* try to convert to a numeric id as a last resort */
1142 trynumeric:
1143         errno = 0;
1144         lscopeid = strtoul(scope, &ep, 10);
1145         scopeid = lscopeid & 0xffffffff;
1146         if (errno == 0 && ep && *ep == '\0' && scopeid == lscopeid) {
1147                 *scopeidp = scopeid;
1148                 return (1);
1149         } else
1150                 return (0);
1151 }
1152
1153 struct addrinfo *
1154 hostent2addrinfo(hp, pai)
1155         struct hostent *hp;
1156         const struct addrinfo *pai;
1157 {
1158         int i, af, error = 0;
1159         char **aplist = NULL, *ap;
1160         struct addrinfo sentinel, *cur;
1161         const struct afd *afd;
1162
1163         af = hp->h_addrtype;
1164         if (pai->ai_family != AF_UNSPEC && af != pai->ai_family)
1165                 return(NULL);
1166
1167         afd = find_afd(af);
1168         if (afd == NULL)
1169                 return(NULL);
1170
1171         aplist = hp->h_addr_list;
1172
1173         memset(&sentinel, 0, sizeof(sentinel));
1174         cur = &sentinel;
1175
1176         for (i = 0; (ap = aplist[i]) != NULL; i++) {
1177 #if 0                           /* the trick seems too much */
1178                 af = hp->h_addr_list;
1179                 if (af == AF_INET6 &&
1180                     IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) {
1181                         af = AF_INET;
1182                         ap = ap + sizeof(struct in6_addr)
1183                                 - sizeof(struct in_addr);
1184                 }
1185                 afd = find_afd(af);
1186                 if (afd == NULL)
1187                         continue;
1188 #endif /* 0 */
1189
1190                 GET_AI(cur->ai_next, afd, ap);
1191
1192                 /* GET_PORT(cur->ai_next, servname); */
1193                 if ((pai->ai_flags & AI_CANONNAME) != 0) {
1194                         /*
1195                          * RFC2553 says that ai_canonname will be set only for
1196                          * the first element.  we do it for all the elements,
1197                          * just for convenience.
1198                          */
1199                         GET_CANONNAME(cur->ai_next, hp->h_name);
1200                 }
1201                 while (cur->ai_next) /* no need to loop, actually. */
1202                         cur = cur->ai_next;
1203                 continue;
1204
1205         free:
1206                 if (cur->ai_next)
1207                         freeaddrinfo(cur->ai_next);
1208                 cur->ai_next = NULL;
1209                 /* continue, without tht pointer CUR advanced. */
1210         }
1211
1212         return(sentinel.ai_next);
1213 }
1214
1215 struct addrinfo *
1216 addr2addrinfo(pai, cp)
1217         const struct addrinfo *pai;
1218         const char *cp;
1219 {
1220         const struct afd *afd;
1221
1222         afd = find_afd(pai->ai_family);
1223         if (afd == NULL)
1224                 return(NULL);
1225
1226         return(get_ai(pai, afd, cp));
1227 }
1228
1229 static struct net_data *
1230 init()
1231 {
1232         struct net_data *net_data;
1233
1234         if (!(net_data = net_data_init(NULL)))
1235                 goto error;
1236         if (!net_data->ho) {
1237                 net_data->ho = (*net_data->irs->ho_map)(net_data->irs);
1238                 if (!net_data->ho || !net_data->res) {
1239 error:
1240                         errno = EIO;
1241                         if (net_data && net_data->res)
1242                                 RES_SET_H_ERRNO(net_data->res, NETDB_INTERNAL);
1243                         return (NULL);
1244                 }
1245
1246                 (*net_data->ho->res_set)(net_data->ho, net_data->res, NULL);
1247         }
1248
1249         return (net_data);
1250 }