Merge from vendor branch NTPD:
[dragonfly.git] / contrib / bind-9.2.4rc7 / 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 #define ERR(err) \
248 do { \
249         /* external reference: error, and label bad */ \
250         error = (err); \
251         goto bad; \
252         /*NOTREACHED*/ \
253 } while (/*CONSTCOND*/0)
254
255 #define MATCH_FAMILY(x, y, w) \
256         ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
257 #define MATCH(x, y, w) \
258         ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
259
260 #if 0                           /* bind8 has its own version */
261 char *
262 gai_strerror(ecode)
263         int ecode;
264 {
265         if (ecode < 0 || ecode > EAI_MAX)
266                 ecode = EAI_MAX;
267         return ai_errlist[ecode];
268 }
269 #endif
270
271 void
272 freeaddrinfo(ai)
273         struct addrinfo *ai;
274 {
275         struct addrinfo *next;
276
277         do {
278                 next = ai->ai_next;
279                 if (ai->ai_canonname)
280                         free(ai->ai_canonname);
281                 /* no need to free(ai->ai_addr) */
282                 free(ai);
283                 ai = next;
284         } while (ai);
285 }
286
287 static int
288 str_isnumber(p)
289         const char *p;
290 {
291         char *ep;
292
293         if (*p == '\0')
294                 return NO;
295         ep = NULL;
296         errno = 0;
297         (void)strtoul(p, &ep, 10);
298         if (errno == 0 && ep && *ep == '\0')
299                 return YES;
300         else
301                 return NO;
302 }
303
304 int
305 getaddrinfo(hostname, servname, hints, res)
306         const char *hostname, *servname;
307         const struct addrinfo *hints;
308         struct addrinfo **res;
309 {
310         struct addrinfo sentinel;
311         struct addrinfo *cur;
312         int error = 0;
313         struct addrinfo ai, ai0, *afai = NULL;
314         struct addrinfo *pai;
315         const struct explore *ex;
316
317         memset(&sentinel, 0, sizeof(sentinel));
318         cur = &sentinel;
319         pai = &ai;
320         pai->ai_flags = 0;
321         pai->ai_family = PF_UNSPEC;
322         pai->ai_socktype = ANY;
323         pai->ai_protocol = ANY;
324         pai->ai_addrlen = 0;
325         pai->ai_canonname = NULL;
326         pai->ai_addr = NULL;
327         pai->ai_next = NULL;
328
329         if (hostname == NULL && servname == NULL)
330                 return EAI_NONAME;
331         if (hints) {
332                 /* error check for hints */
333                 if (hints->ai_addrlen || hints->ai_canonname ||
334                     hints->ai_addr || hints->ai_next)
335                         ERR(EAI_BADHINTS); /* xxx */
336                 if (hints->ai_flags & ~AI_MASK)
337                         ERR(EAI_BADFLAGS);
338                 switch (hints->ai_family) {
339                 case PF_UNSPEC:
340                 case PF_INET:
341                 case PF_INET6:
342                         break;
343                 default:
344                         ERR(EAI_FAMILY);
345                 }
346                 memcpy(pai, hints, sizeof(*pai));
347
348                 /*
349                  * if both socktype/protocol are specified, check if they
350                  * are meaningful combination.
351                  */
352                 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
353                         for (ex = explore; ex->e_af >= 0; ex++) {
354                                 if (pai->ai_family != ex->e_af)
355                                         continue;
356                                 if (ex->e_socktype == ANY)
357                                         continue;
358                                 if (ex->e_protocol == ANY)
359                                         continue;
360                                 if (pai->ai_socktype == ex->e_socktype &&
361                                     pai->ai_protocol != ex->e_protocol) {
362                                         ERR(EAI_BADHINTS);
363                                 }
364                         }
365                 }
366         }
367
368         /*
369          * post-2553: AI_ALL and AI_V4MAPPED are effective only against
370          * AF_INET6 query.  They needs to be ignored if specified in other
371          * occassions.
372          */
373         switch (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) {
374         case AI_V4MAPPED:
375         case AI_ALL | AI_V4MAPPED:
376                 if (pai->ai_family != AF_INET6)
377                         pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
378                 break;
379         case AI_ALL:
380 #if 1
381                 /* illegal */
382                 ERR(EAI_BADFLAGS);
383 #else
384                 pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
385                 break;
386 #endif
387         }
388
389         /*
390          * check for special cases.  (1) numeric servname is disallowed if
391          * socktype/protocol are left unspecified. (2) servname is disallowed
392          * for raw and other inet{,6} sockets.
393          */
394         if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
395 #ifdef PF_INET6
396          || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
397 #endif
398             ) {
399                 ai0 = *pai;     /* backup *pai */
400
401                 if (pai->ai_family == PF_UNSPEC) {
402 #ifdef PF_INET6
403                         pai->ai_family = PF_INET6;
404 #else
405                         pai->ai_family = PF_INET;
406 #endif
407                 }
408                 error = get_portmatch(pai, servname);
409                 if (error)
410                         ERR(error);
411
412                 *pai = ai0;
413         }
414
415         ai0 = *pai;
416
417         /* NULL hostname, or numeric hostname */
418         for (ex = explore; ex->e_af >= 0; ex++) {
419                 *pai = ai0;
420
421                 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
422                         continue;
423                 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
424                         continue;
425                 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
426                         continue;
427
428                 if (pai->ai_family == PF_UNSPEC)
429                         pai->ai_family = ex->e_af;
430                 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
431                         pai->ai_socktype = ex->e_socktype;
432                 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
433                         pai->ai_protocol = ex->e_protocol;
434
435                 /*
436                  * if the servname does not match socktype/protocol, ignore it.
437                  */
438                 if (get_portmatch(pai, servname) != 0)
439                         continue;
440
441                 if (hostname == NULL) {
442                         /*
443                          * filter out AFs that are not supported by the kernel
444                          * XXX errno?
445                          */
446                         if (!addrconfig(pai->ai_family))
447                                 continue;
448                         error = explore_null(pai, servname, &cur->ai_next);
449                 } else
450                         error = explore_numeric_scope(pai, hostname, servname,
451                             &cur->ai_next);
452
453                 if (error)
454                         goto free;
455
456                 while (cur && cur->ai_next)
457                         cur = cur->ai_next;
458         }
459
460         /*
461          * XXX
462          * If numreic representation of AF1 can be interpreted as FQDN
463          * representation of AF2, we need to think again about the code below.
464          */
465         if (sentinel.ai_next)
466                 goto good;
467
468         if (pai->ai_flags & AI_NUMERICHOST)
469                 ERR(EAI_NONAME);
470         if (hostname == NULL)
471                 ERR(EAI_NONAME);
472
473         /*
474          * hostname as alphabetical name.
475          * We'll make sure that
476          * - if returning addrinfo list is empty, return non-zero error
477          *   value (already known one or EAI_NONAME).
478          * - otherwise, 
479          *   + if we haven't had any errors, return 0 (i.e. success).
480          *   + if we've had an error, free the list and return the error.
481          * without any assumption on the behavior of explore_fqdn().
482          */
483
484         /* first, try to query DNS for all possible address families. */
485         *pai = ai0;
486         error = explore_fqdn(pai, hostname, servname, &afai);
487         if (error) {
488                 if (afai != NULL)
489                         freeaddrinfo(afai);
490                 goto free;
491         }
492         if (afai == NULL) {
493                 error = EAI_NONAME; /* we've had no errors. */
494                 goto free;
495         }
496
497         /*
498          * we would like to prefer AF_INET6 than AF_INET, so we'll make an
499          * outer loop by AFs.
500          */
501         for (ex = explore; ex->e_af >= 0; ex++) {
502                 *pai = ai0;
503
504                 if (pai->ai_family == PF_UNSPEC)
505                         pai->ai_family = ex->e_af;
506
507                 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
508                         continue;
509                 if (!MATCH(pai->ai_socktype, ex->e_socktype,
510                            WILD_SOCKTYPE(ex))) {
511                         continue;
512                 }
513                 if (!MATCH(pai->ai_protocol, ex->e_protocol,
514                            WILD_PROTOCOL(ex))) {
515                         continue;
516                 }
517
518 #ifdef AI_ADDRCONFIG
519                 /*
520                  * If AI_ADDRCONFIG is specified, check if we are
521                  * expected to return the address family or not.
522                  */
523                 if ((pai->ai_flags & AI_ADDRCONFIG) != 0 &&
524                     !addrconfig(pai->ai_family))
525                         continue;
526 #endif
527
528                 if (pai->ai_family == PF_UNSPEC)
529                         pai->ai_family = ex->e_af;
530                 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
531                         pai->ai_socktype = ex->e_socktype;
532                 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
533                         pai->ai_protocol = ex->e_protocol;
534
535                 /*
536                  * if the servname does not match socktype/protocol, ignore it.
537                  */
538                 if (get_portmatch(pai, servname) != 0)
539                         continue;
540
541                 if ((error = explore_copy(pai, afai, &cur->ai_next)) != 0) {
542                         freeaddrinfo(afai);
543                         goto free;
544                 }
545
546                 while (cur && cur->ai_next)
547                         cur = cur->ai_next;
548         }
549
550         freeaddrinfo(afai);     /* afai must not be NULL at this point. */
551
552         /* we must not have got any errors. */
553         if (error != 0) /* just for diagnosis */
554                 abort();
555
556         if (sentinel.ai_next) {
557 good:
558                 *res = sentinel.ai_next;
559                 return(SUCCESS);
560         } else {
561                 /*
562                  * All the process succeeded, but we've had an empty list. 
563                  * This can happen if the given hints do not match our
564                  * candidates.
565                  */
566                 error = EAI_NONAME;
567         }
568
569 free:
570 bad:
571         if (sentinel.ai_next)
572                 freeaddrinfo(sentinel.ai_next);
573         *res = NULL;
574         return(error);
575 }
576
577 /*
578  * FQDN hostname, DNS lookup
579  */
580 static int
581 explore_fqdn(pai, hostname, servname, res)
582         const struct addrinfo *pai;
583         const char *hostname;
584         const char *servname;
585         struct addrinfo **res;
586 {
587         struct addrinfo *result;
588         struct addrinfo *cur;
589         struct net_data *net_data = init();
590         struct irs_ho *ho;
591         int error = 0;
592         char tmp[NS_MAXDNAME];
593         const char *cp;
594
595         INSIST(res != NULL && *res == NULL);
596
597         /*
598          * if the servname does not match socktype/protocol, ignore it.
599          */
600         if (get_portmatch(pai, servname) != 0)
601                 return(0);
602
603         if (!net_data || !(ho = net_data->ho))
604                 return(0);
605 #if 0                           /* XXX (notyet) */
606         if (net_data->ho_stayopen && net_data->ho_last &&
607             net_data->ho_last->h_addrtype == af) {
608                 if (ns_samename(name, net_data->ho_last->h_name) == 1)
609                         return (net_data->ho_last);
610                 for (hap = net_data->ho_last->h_aliases; hap && *hap; hap++)
611                         if (ns_samename(name, *hap) == 1)
612                                 return (net_data->ho_last);
613         }
614 #endif
615         if (!strchr(hostname, '.') &&
616             (cp = res_hostalias(net_data->res, hostname,
617                                 tmp, sizeof(tmp))))
618                 hostname = cp;
619         result = (*ho->addrinfo)(ho, hostname, pai);
620         if (!net_data->ho_stayopen) {
621                 (*ho->minimize)(ho);
622         }
623         if (result == NULL) {
624                 int e = h_errno;
625
626                 switch(e) {
627                 case NETDB_INTERNAL:
628                         error = EAI_SYSTEM;
629                         break;
630                 case TRY_AGAIN:
631                         error = EAI_AGAIN;
632                         break;
633                 case NO_RECOVERY:
634                         error = EAI_FAIL;
635                         break;
636                 case HOST_NOT_FOUND:
637                 case NO_DATA:
638                         error = EAI_NONAME;
639                         break;
640                 default:
641                 case NETDB_SUCCESS: /* should be impossible... */
642                         error = EAI_NONAME;
643                         break;
644                 }
645                 goto free;
646         }
647
648         for (cur = result; cur; cur = cur->ai_next) {
649                 GET_PORT(cur, servname); /* XXX: redundant lookups... */
650                 /* canonname should already be filled. */
651         }
652
653         *res = result;
654
655         return(0);
656
657 free:
658         if (result)
659                 freeaddrinfo(result);
660         return error;
661 }
662
663 static int
664 explore_copy(pai, src0, res)
665         const struct addrinfo *pai;     /* seed */
666         const struct addrinfo *src0;    /* source */
667         struct addrinfo **res;
668 {
669         int error;
670         struct addrinfo sentinel, *cur;
671         const struct addrinfo *src;
672
673         error = 0;
674         sentinel.ai_next = NULL;
675         cur = &sentinel;
676
677         for (src = src0; src != NULL; src = src->ai_next) {
678                 if (src->ai_family != pai->ai_family)
679                         continue;
680
681                 cur->ai_next = copy_ai(src);
682                 if (!cur->ai_next) {
683                         error = EAI_MEMORY;
684                         goto fail;
685                 }
686
687                 cur->ai_next->ai_socktype = pai->ai_socktype;
688                 cur->ai_next->ai_protocol = pai->ai_protocol;
689                 cur = cur->ai_next;
690         }
691
692         *res = sentinel.ai_next;
693         return 0;
694
695 fail:
696         freeaddrinfo(sentinel.ai_next);
697         return error;
698 }
699
700 /*
701  * hostname == NULL.
702  * passive socket -> anyaddr (0.0.0.0 or ::)
703  * non-passive socket -> localhost (127.0.0.1 or ::1)
704  */
705 static int
706 explore_null(pai, servname, res)
707         const struct addrinfo *pai;
708         const char *servname;
709         struct addrinfo **res;
710 {
711         const struct afd *afd;
712         struct addrinfo *cur;
713         struct addrinfo sentinel;
714         int error;
715
716         *res = NULL;
717         sentinel.ai_next = NULL;
718         cur = &sentinel;
719
720         afd = find_afd(pai->ai_family);
721         if (afd == NULL)
722                 return 0;
723
724         if (pai->ai_flags & AI_PASSIVE) {
725                 GET_AI(cur->ai_next, afd, afd->a_addrany);
726                 /* xxx meaningless?
727                  * GET_CANONNAME(cur->ai_next, "anyaddr");
728                  */
729                 GET_PORT(cur->ai_next, servname);
730         } else {
731                 GET_AI(cur->ai_next, afd, afd->a_loopback);
732                 /* xxx meaningless?
733                  * GET_CANONNAME(cur->ai_next, "localhost");
734                  */
735                 GET_PORT(cur->ai_next, servname);
736         }
737         cur = cur->ai_next;
738
739         *res = sentinel.ai_next;
740         return 0;
741
742 free:
743         if (sentinel.ai_next)
744                 freeaddrinfo(sentinel.ai_next);
745         return error;
746 }
747
748 /*
749  * numeric hostname
750  */
751 static int
752 explore_numeric(pai, hostname, servname, res)
753         const struct addrinfo *pai;
754         const char *hostname;
755         const char *servname;
756         struct addrinfo **res;
757 {
758         const struct afd *afd;
759         struct addrinfo *cur;
760         struct addrinfo sentinel;
761         int error;
762         char pton[PTON_MAX];
763
764         *res = NULL;
765         sentinel.ai_next = NULL;
766         cur = &sentinel;
767
768         afd = find_afd(pai->ai_family);
769         if (afd == NULL)
770                 return 0;
771
772         switch (afd->a_af) {
773 #if 0 /*X/Open spec*/
774         case AF_INET:
775                 if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
776                         if (pai->ai_family == afd->a_af ||
777                             pai->ai_family == PF_UNSPEC /*?*/) {
778                                 GET_AI(cur->ai_next, afd, pton);
779                                 GET_PORT(cur->ai_next, servname);
780                                 while (cur && cur->ai_next)
781                                         cur = cur->ai_next;
782                         } else
783                                 ERR(EAI_FAMILY);        /*xxx*/
784                 }
785                 break;
786 #endif
787         default:
788                 if (inet_pton(afd->a_af, hostname, pton) == 1) {
789                         if (pai->ai_family == afd->a_af ||
790                             pai->ai_family == PF_UNSPEC /*?*/) {
791                                 GET_AI(cur->ai_next, afd, pton);
792                                 GET_PORT(cur->ai_next, servname);
793                                 while (cur && cur->ai_next)
794                                         cur = cur->ai_next;
795                         } else
796                                 ERR(EAI_FAMILY);        /*xxx*/
797                 }
798                 break;
799         }
800
801         *res = sentinel.ai_next;
802         return 0;
803
804 free:
805 bad:
806         if (sentinel.ai_next)
807                 freeaddrinfo(sentinel.ai_next);
808         return error;
809 }
810
811 /*
812  * numeric hostname with scope
813  */
814 static int
815 explore_numeric_scope(pai, hostname, servname, res)
816         const struct addrinfo *pai;
817         const char *hostname;
818         const char *servname;
819         struct addrinfo **res;
820 {
821 #ifndef SCOPE_DELIMITER
822         return explore_numeric(pai, hostname, servname, res);
823 #else
824         const struct afd *afd;
825         struct addrinfo *cur;
826         int error;
827         char *cp, *hostname2 = NULL, *scope, *addr;
828         struct sockaddr_in6 *sin6;
829
830         afd = find_afd(pai->ai_family);
831         if (afd == NULL)
832                 return 0;
833
834         if (!afd->a_scoped)
835                 return explore_numeric(pai, hostname, servname, res);
836
837         cp = strchr(hostname, SCOPE_DELIMITER);
838         if (cp == NULL)
839                 return explore_numeric(pai, hostname, servname, res);
840
841         /*
842          * Handle special case of <scoped_address><delimiter><scope id>
843          */
844         hostname2 = strdup(hostname);
845         if (hostname2 == NULL)
846                 return EAI_MEMORY;
847         /* terminate at the delimiter */
848         hostname2[cp - hostname] = '\0';
849         addr = hostname2;
850         scope = cp + 1;
851
852         error = explore_numeric(pai, addr, servname, res);
853         if (error == 0) {
854                 u_int32_t scopeid = 0;
855
856                 for (cur = *res; cur; cur = cur->ai_next) {
857                         if (cur->ai_family != AF_INET6)
858                                 continue;
859                         sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
860                         if (!ip6_str2scopeid(scope, sin6, &scopeid)) {
861                                 free(hostname2);
862                                 return(EAI_NONAME); /* XXX: is return OK? */
863                         }
864 #ifdef HAVE_SIN6_SCOPE_ID
865                         sin6->sin6_scope_id = scopeid;
866 #endif
867                 }
868         }
869
870         free(hostname2);
871
872         return error;
873 #endif
874 }
875
876 static int
877 get_canonname(pai, ai, str)
878         const struct addrinfo *pai;
879         struct addrinfo *ai;
880         const char *str;
881 {
882         if ((pai->ai_flags & AI_CANONNAME) != 0) {
883                 ai->ai_canonname = (char *)malloc(strlen(str) + 1);
884                 if (ai->ai_canonname == NULL)
885                         return EAI_MEMORY;
886                 strcpy(ai->ai_canonname, str);
887         }
888         return 0;
889 }
890
891 static struct addrinfo *
892 get_ai(pai, afd, addr)
893         const struct addrinfo *pai;
894         const struct afd *afd;
895         const char *addr;
896 {
897         char *p;
898         struct addrinfo *ai;
899
900         ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
901                 + (afd->a_socklen));
902         if (ai == NULL)
903                 return NULL;
904
905         memcpy(ai, pai, sizeof(struct addrinfo));
906         ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
907         memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
908 #ifdef HAVE_SA_LEN
909         ai->ai_addr->sa_len = afd->a_socklen;
910 #endif
911         ai->ai_addrlen = afd->a_socklen;
912         ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
913         p = (char *)(void *)(ai->ai_addr);
914         memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
915         return ai;
916 }
917
918 /* XXX need to malloc() the same way we do from other functions! */
919 static struct addrinfo *
920 copy_ai(pai)
921         const struct addrinfo *pai;
922 {
923         struct addrinfo *ai;
924         size_t l;
925
926         l = sizeof(*ai) + pai->ai_addrlen;
927         if ((ai = (struct addrinfo *)malloc(l)) == NULL)
928                 return NULL;
929         memset(ai, 0, l);
930         memcpy(ai, pai, sizeof(*ai));
931         ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
932         memcpy(ai->ai_addr, pai->ai_addr, pai->ai_addrlen);
933
934         if (pai->ai_canonname) {
935                 l = strlen(pai->ai_canonname) + 1;
936                 if ((ai->ai_canonname = malloc(l)) == NULL) {
937                         free(ai);
938                         return NULL;
939                 }
940                 strcpy(ai->ai_canonname, pai->ai_canonname);    /* (checked) */
941         } else {
942                 /* just to make sure */
943                 ai->ai_canonname = NULL;
944         }
945
946         ai->ai_next = NULL;
947
948         return ai;
949 }
950
951 static int
952 get_portmatch(const struct addrinfo *ai, const char *servname) {
953
954         /* get_port does not touch first argument. when matchonly == 1. */
955         /* LINTED const cast */
956         return get_port((const struct addrinfo *)ai, servname, 1);
957 }
958
959 static int
960 get_port(const struct addrinfo *ai, const char *servname, int matchonly) {
961         const char *proto;
962         struct servent *sp;
963         int port;
964         int allownumeric;
965
966         if (servname == NULL)
967                 return 0;
968         switch (ai->ai_family) {
969         case AF_INET:
970 #ifdef AF_INET6
971         case AF_INET6:
972 #endif
973                 break;
974         default:
975                 return 0;
976         }
977
978         switch (ai->ai_socktype) {
979         case SOCK_RAW:
980                 return EAI_SERVICE;
981         case SOCK_DGRAM:
982         case SOCK_STREAM:
983                 allownumeric = 1;
984                 break;
985         case ANY:
986                 switch (ai->ai_family) {
987                 case AF_INET:
988 #ifdef AF_INET6
989                 case AF_INET6:
990 #endif
991                         allownumeric = 1;
992                         break;
993                 default:
994                         allownumeric = 0;
995                         break;
996                 }
997                 break;
998         default:
999                 return EAI_SOCKTYPE;
1000         }
1001
1002         if (str_isnumber(servname)) {
1003                 if (!allownumeric)
1004                         return EAI_SERVICE;
1005                 port = atoi(servname);
1006                 if (port < 0 || port > 65535)
1007                         return EAI_SERVICE;
1008                 port = htons(port);
1009         } else {
1010                 switch (ai->ai_socktype) {
1011                 case SOCK_DGRAM:
1012                         proto = "udp";
1013                         break;
1014                 case SOCK_STREAM:
1015                         proto = "tcp";
1016                         break;
1017                 default:
1018                         proto = NULL;
1019                         break;
1020                 }
1021
1022                 if ((sp = getservbyname(servname, proto)) == NULL)
1023                         return EAI_SERVICE;
1024                 port = sp->s_port;
1025         }
1026
1027         if (!matchonly) {
1028                 switch (ai->ai_family) {
1029                 case AF_INET:
1030                         ((struct sockaddr_in *)(void *)
1031                             ai->ai_addr)->sin_port = port;
1032                         break;
1033                 case AF_INET6:
1034                         ((struct sockaddr_in6 *)(void *)
1035                             ai->ai_addr)->sin6_port = port;
1036                         break;
1037                 }
1038         }
1039
1040         return 0;
1041 }
1042
1043 static const struct afd *
1044 find_afd(af)
1045         int af;
1046 {
1047         const struct afd *afd;
1048
1049         if (af == PF_UNSPEC)
1050                 return NULL;
1051         for (afd = afdl; afd->a_af; afd++) {
1052                 if (afd->a_af == af)
1053                         return afd;
1054         }
1055         return NULL;
1056 }
1057
1058 /*
1059  * post-2553: AI_ADDRCONFIG check.  if we use getipnodeby* as backend, backend
1060  * will take care of it.
1061  * the semantics of AI_ADDRCONFIG is not defined well.  we are not sure
1062  * if the code is right or not.
1063  */
1064 static int
1065 addrconfig(af)
1066         int af;
1067 {
1068         int s;
1069
1070         /* XXX errno */
1071         s = socket(af, SOCK_DGRAM, 0);
1072         if (s < 0) {
1073                 if (errno != EMFILE)
1074                         return 0;
1075         } else
1076                 close(s);
1077         return 1;
1078 }
1079
1080 /* convert a string to a scope identifier. XXX: IPv6 specific */
1081 static int
1082 ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6,
1083                 u_int32_t *scopeidp)
1084 {
1085         u_int32_t scopeid;
1086         u_long lscopeid;
1087         struct in6_addr *a6 = &sin6->sin6_addr;
1088         char *ep;
1089         
1090         /* empty scopeid portion is invalid */
1091         if (*scope == '\0')
1092                 return (0);
1093
1094 #ifdef USE_IFNAMELINKID
1095         if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1096                 /*
1097                  * Using interface names as link indices can be allowed
1098                  * only when we can assume a one-to-one mappings between
1099                  * links and interfaces.  See comments in getnameinfo.c.
1100                  */
1101                 scopeid = if_nametoindex(scope);
1102                 if (scopeid == 0)
1103                         goto trynumeric;
1104                 *scopeidp = scopeid;
1105                 return (1);
1106         }
1107 #endif
1108
1109         /* still unclear about literal, allow numeric only - placeholder */
1110         if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1111                 goto trynumeric;
1112         if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1113                 goto trynumeric;
1114         else
1115                 goto trynumeric;        /* global */
1116
1117         /* try to convert to a numeric id as a last resort */
1118 trynumeric:
1119         errno = 0;
1120         lscopeid = strtoul(scope, &ep, 10);
1121         scopeid = lscopeid & 0xffffffff;
1122         if (errno == 0 && ep && *ep == '\0' && scopeid == lscopeid) {
1123                 *scopeidp = scopeid;
1124                 return (1);
1125         } else
1126                 return (0);
1127 }
1128
1129 struct addrinfo *
1130 hostent2addrinfo(hp, pai)
1131         struct hostent *hp;
1132         const struct addrinfo *pai;
1133 {
1134         int i, af, error = 0;
1135         char **aplist = NULL, *ap;
1136         struct addrinfo sentinel, *cur;
1137         const struct afd *afd;
1138
1139         af = hp->h_addrtype;
1140         if (pai->ai_family != AF_UNSPEC && af != pai->ai_family)
1141                 return(NULL);
1142
1143         afd = find_afd(af);
1144         if (afd == NULL)
1145                 return(NULL);
1146
1147         aplist = hp->h_addr_list;
1148
1149         memset(&sentinel, 0, sizeof(sentinel));
1150         cur = &sentinel;
1151
1152         for (i = 0; (ap = aplist[i]) != NULL; i++) {
1153 #if 0                           /* the trick seems too much */
1154                 af = hp->h_addr_list;
1155                 if (af == AF_INET6 &&
1156                     IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) {
1157                         af = AF_INET;
1158                         ap = ap + sizeof(struct in6_addr)
1159                                 - sizeof(struct in_addr);
1160                 }
1161                 afd = find_afd(af);
1162                 if (afd == NULL)
1163                         continue;
1164 #endif /* 0 */
1165
1166                 GET_AI(cur->ai_next, afd, ap);
1167
1168                 /* GET_PORT(cur->ai_next, servname); */
1169                 if ((pai->ai_flags & AI_CANONNAME) != 0) {
1170                         /*
1171                          * RFC2553 says that ai_canonname will be set only for
1172                          * the first element.  we do it for all the elements,
1173                          * just for convenience.
1174                          */
1175                         GET_CANONNAME(cur->ai_next, hp->h_name);
1176                 }
1177                 while (cur && cur->ai_next) /* no need to loop, actually. */
1178                         cur = cur->ai_next;
1179                 continue;
1180
1181         free:
1182                 if (cur->ai_next)
1183                         freeaddrinfo(cur->ai_next);
1184                 cur->ai_next = NULL;
1185                 /* continue, without tht pointer CUR advanced. */
1186         }
1187
1188         return(sentinel.ai_next);
1189 }
1190
1191 struct addrinfo *
1192 addr2addrinfo(pai, cp)
1193         const struct addrinfo *pai;
1194         const char *cp;
1195 {
1196         const struct afd *afd;
1197
1198         afd = find_afd(pai->ai_family);
1199         if (afd == NULL)
1200                 return(NULL);
1201
1202         return(get_ai(pai, afd, cp));
1203 }
1204
1205 static struct net_data *
1206 init()
1207 {
1208         struct net_data *net_data;
1209
1210         if (!(net_data = net_data_init(NULL)))
1211                 goto error;
1212         if (!net_data->ho) {
1213                 net_data->ho = (*net_data->irs->ho_map)(net_data->irs);
1214                 if (!net_data->ho || !net_data->res) {
1215 error:
1216                         errno = EIO;
1217                         if (net_data && net_data->res)
1218                                 RES_SET_H_ERRNO(net_data->res, NETDB_INTERNAL);
1219                         return (NULL);
1220                 }
1221
1222                 (*net_data->ho->res_set)(net_data->ho, net_data->res, NULL);
1223         }
1224
1225         return (net_data);
1226 }