xref: /illumos-gate/usr/src/lib/libnsl/nss/getipnodeby.c (revision ba1637f8b78b432c41b36839c92aecf1f5f9fafb)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
25  * Use is subject to license terms.
26  *
27  * This file defines and implements the re-entrant getipnodebyname(),
28  * getipnodebyaddr(), and freehostent() routines for IPv6. These routines
29  * follow use the netdir_getbyYY() (see netdir_inet.c).
30  *
31  * lib/libnsl/nss/getipnodeby.c
32  */
33 
34 #pragma ident	"%Z%%M%	%I%	%E% SMI"
35 
36 #include "mt.h"
37 #include <stdlib.h>
38 #include <unistd.h>
39 #include <stropts.h>
40 #include <ctype.h>
41 #include <string.h>
42 #include <strings.h>
43 #include <netdb.h>
44 #include <stdio.h>
45 #include <arpa/inet.h>
46 #include <nss_dbdefs.h>
47 #include <netinet/in.h>
48 #include <sys/socket.h>
49 #include <sys/sockio.h>
50 #include <nss_netdir.h>
51 #include <net/if.h>
52 #include <netinet/in.h>
53 #include <netdir.h>
54 #include <thread.h>
55 #include <synch.h>
56 #include <fcntl.h>
57 #include <sys/time.h>
58 #include "nss.h"
59 
60 #define	IPV6_LITERAL_CHAR	':'
61 
62 /*
63  * The number of nanoseconds getipnodebyname() waits before getting
64  * fresh interface count information with SIOCGLIFNUM.  The default is
65  * five minutes.
66  */
67 #define	IFNUM_TIMEOUT	((hrtime_t)300 * NANOSEC)
68 
69 /*
70  * Bits in the bitfield returned by getipnodebyname_processflags().
71  *
72  * IPNODE_WANTIPV6	The user wants IPv6 addresses returned.
73  * IPNODE_WANTIPV4	The user wants IPv4 addresses returned.
74  * IPNODE_IPV4IFNOIPV6	The user only wants IPv4 addresses returned if no IPv6
75  *			addresses are returned.
76  * IPNODE_LOOKUPIPNODES	getipnodebyname() needs to lookup the name in ipnodes.
77  * IPNODE_LOOKUPHOSTS	getipnodebyname() needs to lookup the name in hosts.
78  * IPNODE_ISLITERAL	The name supplied is a literal address string.
79  */
80 #define	IPNODE_WANTIPV6		0x00000001u
81 #define	IPNODE_WANTIPV4		0x00000002u
82 #define	IPNODE_IPV4IFNOIPV6	0x00000004u
83 #define	IPNODE_LOOKUPIPNODES	0x00000008u
84 #define	IPNODE_LOOKUPHOSTS	0x00000010u
85 #define	IPNODE_LITERAL		0x00000020u
86 #define	IPNODE_IPV4		(IPNODE_WANTIPV4 | IPNODE_IPV4IFNOIPV6)
87 
88 /*
89  * The default set of bits corresponding to a getipnodebyname() flags
90  * argument of AI_DEFAULT.
91  */
92 #define	IPNODE_DEFAULT (IPNODE_WANTIPV6 | IPNODE_IPV4 | \
93 	IPNODE_LOOKUPIPNODES | IPNODE_LOOKUPHOSTS)
94 
95 extern struct netconfig *__rpc_getconfip(char *);
96 
97 static struct hostent *__mapv4tov6(struct hostent *, struct hostent *,
98     nss_XbyY_buf_t *, int);
99 struct hostent *__mappedtov4(struct hostent *, int *);
100 static struct hostent *__filter_addresses(int, struct hostent *);
101 static int __find_mapped(struct hostent *, int);
102 static nss_XbyY_buf_t *__IPv6_alloc(int);
103 static void __IPv6_cleanup(nss_XbyY_buf_t *);
104 static int __ai_addrconfig(int);
105 
106 
107 #ifdef PIC
108 struct hostent *
109 _uncached_getipnodebyname(const char *nam, struct hostent *result,
110 	char *buffer, int buflen, int af_family, int flags, int *h_errnop)
111 {
112 	return (_switch_getipnodebyname_r(nam, result, buffer, buflen,
113 					af_family, flags, h_errnop));
114 }
115 
116 struct hostent *
117 _uncached_getipnodebyaddr(const char *addr, int length, int type,
118 	struct hostent *result, char *buffer, int buflen, int *h_errnop)
119 {
120 	if (type == AF_INET)
121 		return (_switch_gethostbyaddr_r(addr, length, type,
122 					result, buffer, buflen, h_errnop));
123 	else if (type == AF_INET6)
124 		return (_switch_getipnodebyaddr_r(addr, length, type,
125 					result, buffer, buflen, h_errnop));
126 	return (NULL);
127 }
128 #endif
129 
130 /*
131  * Given a name, an address family, and a set of flags, return a
132  * bitfield that getipnodebyname() will use.
133  */
134 static uint_t
135 getipnodebyname_processflags(const char *name, int af, int flags)
136 {
137 	uint_t		ipnode_bits = IPNODE_DEFAULT;
138 	boolean_t	ipv6configured = B_FALSE;
139 	boolean_t	ipv4configured = B_FALSE;
140 
141 	/*
142 	 * If AI_ADDRCONFIG is specified, we need to determine the number
143 	 * of addresses of each address family configured on the system as
144 	 * appropriate.
145 	 */
146 	if (flags & AI_ADDRCONFIG) {
147 		ipv6configured = (af == AF_INET6 &&
148 		    __ai_addrconfig(AF_INET6) > 0);
149 		ipv4configured = ((af == AF_INET || (flags & AI_V4MAPPED)) &&
150 		    __ai_addrconfig(AF_INET) > 0);
151 	}
152 
153 	/*
154 	 * Determine what kinds of addresses the user is interested
155 	 * in getting back.
156 	 */
157 	switch (af) {
158 	case AF_INET6:
159 		if ((flags & AI_ADDRCONFIG) && !ipv6configured)
160 			ipnode_bits &= ~IPNODE_WANTIPV6;
161 
162 		if (flags & AI_V4MAPPED) {
163 			if ((flags & AI_ADDRCONFIG) && !ipv4configured) {
164 				ipnode_bits &= ~IPNODE_IPV4;
165 			} else if (flags & AI_ALL) {
166 				ipnode_bits &= ~IPNODE_IPV4IFNOIPV6;
167 			}
168 		} else {
169 			ipnode_bits &= ~IPNODE_IPV4;
170 		}
171 		break;
172 	case AF_INET:
173 		if ((flags & AI_ADDRCONFIG) && !ipv4configured)
174 			ipnode_bits &= ~IPNODE_IPV4;
175 		ipnode_bits &= ~IPNODE_WANTIPV6;
176 		ipnode_bits &= ~IPNODE_IPV4IFNOIPV6;
177 		break;
178 	default:
179 		ipnode_bits = 0;
180 		break;
181 	}
182 
183 	/*
184 	 * If we're not looking for IPv4 addresses, don't bother looking
185 	 * in hosts.
186 	 */
187 	if (!(ipnode_bits & IPNODE_WANTIPV4))
188 		ipnode_bits &= ~IPNODE_LOOKUPHOSTS;
189 
190 	/*
191 	 * Determine if name is a literal IP address.  This will
192 	 * further narrow down what type of lookup we're going to do.
193 	 */
194 	if (strchr(name, IPV6_LITERAL_CHAR) != NULL) {
195 		/* Literal IPv6 address */
196 		ipnode_bits |= IPNODE_LITERAL;
197 		/*
198 		 * In s9 we accepted the literal without filtering independent
199 		 * of what family was passed in hints.  We continue to do
200 		 * this.
201 		 */
202 		ipnode_bits |= (IPNODE_WANTIPV6 | IPNODE_WANTIPV4);
203 		ipnode_bits &= ~IPNODE_LOOKUPHOSTS;
204 	} else if (inet_addr(name) != 0xffffffffU) {
205 		/* Literal IPv4 address */
206 		ipnode_bits |= (IPNODE_LITERAL | IPNODE_WANTIPV4);
207 		ipnode_bits &= ~IPNODE_WANTIPV6;
208 		ipnode_bits &= ~IPNODE_LOOKUPIPNODES;
209 	}
210 	return (ipnode_bits);
211 }
212 
213 struct hostent *
214 getipnodebyname(const char *name, int af, int flags, int *error_num)
215 {
216 	struct hostent		*hp = NULL;
217 	nss_XbyY_buf_t		*buf4 = NULL;
218 	nss_XbyY_buf_t		*buf6 = NULL;
219 	struct netconfig	*nconf;
220 	struct nss_netdirbyname_in	nssin;
221 	union nss_netdirbyname_out	nssout;
222 	int			ret;
223 	uint_t			ipnode_bits;
224 
225 	if ((nconf = __rpc_getconfip("udp")) == NULL &&
226 	    (nconf = __rpc_getconfip("tcp")) == NULL) {
227 		*error_num = NO_RECOVERY;
228 		return (NULL);
229 	}
230 
231 	ipnode_bits = getipnodebyname_processflags(name, af, flags);
232 
233 	/* Make sure we have something to look up. */
234 	if (!(ipnode_bits & (IPNODE_WANTIPV6 | IPNODE_WANTIPV4))) {
235 		*error_num = HOST_NOT_FOUND;
236 		goto cleanup;
237 	}
238 
239 	/*
240 	 * Perform the requested lookups.  We always look through
241 	 * ipnodes first for both IPv4 and IPv6 addresses.  Depending
242 	 * on what was returned and what was needed, we either filter
243 	 * out the garbage, or ask for more using hosts.
244 	 */
245 	if (ipnode_bits & IPNODE_LOOKUPIPNODES) {
246 		if ((buf6 = __IPv6_alloc(NSS_BUFLEN_IPNODES)) == NULL) {
247 			*error_num = NO_RECOVERY;
248 			goto cleanup;
249 		}
250 		nssin.op_t = NSS_HOST6;
251 		nssin.arg.nss.host6.name = name;
252 		nssin.arg.nss.host6.buf = buf6->buffer;
253 		nssin.arg.nss.host6.buflen = buf6->buflen;
254 		nssin.arg.nss.host6.af_family = af;
255 		nssin.arg.nss.host6.flags = flags;
256 		nssout.nss.host.hent = buf6->result;
257 		nssout.nss.host.herrno_p = error_num;
258 		ret = _get_hostserv_inetnetdir_byname(nconf, &nssin, &nssout);
259 		if (ret != ND_OK) {
260 			__IPv6_cleanup(buf6);
261 			buf6 = NULL;
262 		} else if (ipnode_bits & IPNODE_WANTIPV4) {
263 			/*
264 			 * buf6 may have all that we need if we either
265 			 * only wanted IPv4 addresses if there were no
266 			 * IPv6 addresses returned, or if there are
267 			 * IPv4-mapped addresses in buf6.  If either
268 			 * of these are true, then there's no need to
269 			 * look in hosts.
270 			 */
271 			if (ipnode_bits & IPNODE_IPV4IFNOIPV6 ||
272 			    __find_mapped(buf6->result, 0) != 0) {
273 				ipnode_bits &= ~IPNODE_LOOKUPHOSTS;
274 			} else if (!(ipnode_bits & IPNODE_WANTIPV6)) {
275 				/*
276 				 * If all we're looking for are IPv4
277 				 * addresses and there are none in
278 				 * buf6 then buf6 is now useless.
279 				 */
280 				__IPv6_cleanup(buf6);
281 				buf6 = NULL;
282 			}
283 		}
284 	}
285 	if (ipnode_bits & IPNODE_LOOKUPHOSTS) {
286 		if ((buf4 = __IPv6_alloc(NSS_BUFLEN_HOSTS)) == NULL) {
287 			*error_num = NO_RECOVERY;
288 			goto cleanup;
289 		}
290 		nssin.op_t = NSS_HOST;
291 		nssin.arg.nss.host.name = name;
292 		nssin.arg.nss.host.buf = buf4->buffer;
293 		nssin.arg.nss.host.buflen = buf4->buflen;
294 		nssout.nss.host.hent = buf4->result;
295 		nssout.nss.host.herrno_p = error_num;
296 		ret = _get_hostserv_inetnetdir_byname(nconf, &nssin, &nssout);
297 		if (ret != ND_OK) {
298 			__IPv6_cleanup(buf4);
299 			buf4 = NULL;
300 		}
301 	}
302 
303 	if (buf6 == NULL && buf4 == NULL) {
304 		*error_num = HOST_NOT_FOUND;
305 		goto cleanup;
306 	}
307 
308 	/* Extract the appropriate addresses from the returned buffer(s). */
309 	switch (af) {
310 	case AF_INET6: {
311 		if (buf4 != NULL) {
312 			nss_XbyY_buf_t *mergebuf;
313 
314 			/*
315 			 * The IPv4 results we have need to be
316 			 * converted to IPv4-mapped addresses,
317 			 * conditionally merged with the IPv6
318 			 * results, and the end result needs to be
319 			 * re-ordered.
320 			 */
321 			mergebuf = __IPv6_alloc(NSS_BUFLEN_IPNODES);
322 			if (mergebuf == NULL) {
323 				*error_num = NO_RECOVERY;
324 				goto cleanup;
325 			}
326 			hp = __mapv4tov6(buf4->result,
327 			    ((buf6 != NULL) ? buf6->result : NULL),
328 			    mergebuf, 1);
329 			if (hp != NULL)
330 				order_haddrlist_af(AF_INET6, hp->h_addr_list);
331 			else
332 				*error_num = NO_RECOVERY;
333 			free(mergebuf);
334 		}
335 
336 		if (buf4 == NULL && buf6 != NULL) {
337 			hp = buf6->result;
338 
339 			/*
340 			 * We have what we need in buf6, but we may need
341 			 * to filter out some addresses depending on what
342 			 * is being asked for.
343 			 */
344 			if (!(ipnode_bits & IPNODE_WANTIPV4))
345 				hp = __filter_addresses(AF_INET, buf6->result);
346 			else if (!(ipnode_bits & IPNODE_WANTIPV6))
347 				hp = __filter_addresses(AF_INET6, buf6->result);
348 
349 			if (hp == NULL)
350 				*error_num = NO_ADDRESS;
351 		}
352 
353 		break;
354 	}
355 
356 	case AF_INET:
357 		/* We could have results in buf6 or buf4, not both */
358 		if (buf6 != NULL) {
359 			/*
360 			 * Extract the IPv4-mapped addresses from buf6
361 			 * into hp.
362 			 */
363 			hp = __mappedtov4(buf6->result, error_num);
364 		} else {
365 			/* We have what we need in buf4. */
366 			hp = buf4->result;
367 			if (ipnode_bits & IPNODE_LITERAL) {
368 				/*
369 				 * There is a special case here for literal
370 				 * IPv4 address strings.  The hosts
371 				 * front-end sets h_aliases to a one
372 				 * element array containing a single NULL
373 				 * pointer (in ndaddr2hent()), while
374 				 * getipnodebyname() requires h_aliases to
375 				 * be a NULL pointer itself.  We're not
376 				 * going to change the front-end since it
377 				 * needs to remain backward compatible for
378 				 * gethostbyname() and friends.  Just set
379 				 * h_aliases to NULL here instead.
380 				 */
381 				hp->h_aliases = NULL;
382 			}
383 		}
384 
385 		break;
386 
387 	default:
388 		break;
389 	}
390 
391 cleanup:
392 	/*
393 	 * Free the memory we allocated, but make sure we don't free
394 	 * the memory we're returning to the caller.
395 	 */
396 	if (buf6 != NULL) {
397 		if (buf6->result == hp)
398 			buf6->result = NULL;
399 		__IPv6_cleanup(buf6);
400 	}
401 	if (buf4 != NULL) {
402 		if (buf4->result == hp)
403 			buf4->result = NULL;
404 		__IPv6_cleanup(buf4);
405 	}
406 	(void) freenetconfigent(nconf);
407 
408 	return (hp);
409 }
410 
411 /*
412  * This is the IPv6 interface for "gethostbyaddr".
413  */
414 struct hostent *
415 getipnodebyaddr(const void *src, size_t len, int type, int *error_num)
416 {
417 	struct in6_addr *addr6 = 0;
418 	struct in_addr *addr4 = 0;
419 	nss_XbyY_buf_t *buf = 0;
420 	nss_XbyY_buf_t *res = 0;
421 	struct netconfig *nconf;
422 	struct hostent *hp = 0;
423 	struct	nss_netdirbyaddr_in nssin;
424 	union	nss_netdirbyaddr_out nssout;
425 	int neterr;
426 	char tmpbuf[64];
427 
428 	if (type == AF_INET6) {
429 		if ((addr6 = (struct in6_addr *)src) == NULL) {
430 			*error_num = HOST_NOT_FOUND;
431 			return (NULL);
432 		}
433 	} else if (type == AF_INET) {
434 		if ((addr4 = (struct in_addr *)src) == NULL) {
435 			*error_num = HOST_NOT_FOUND;
436 			return (NULL);
437 		}
438 	} else {
439 		*error_num = HOST_NOT_FOUND;
440 		return (NULL);
441 	}
442 	/*
443 	 * Specific case: query for "::"
444 	 */
445 	if (type == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED(addr6)) {
446 		*error_num = HOST_NOT_FOUND;
447 		return (NULL);
448 	}
449 	/*
450 	 * Step 1: IPv4-mapped address  or IPv4 Compat
451 	 */
452 	if ((type == AF_INET6 && len == 16) &&
453 		((IN6_IS_ADDR_V4MAPPED(addr6)) ||
454 		(IN6_IS_ADDR_V4COMPAT(addr6)))) {
455 		if ((buf = __IPv6_alloc(NSS_BUFLEN_IPNODES)) == 0) {
456 			*error_num = NO_RECOVERY;
457 			return (NULL);
458 		}
459 		if ((nconf = __rpc_getconfip("udp")) == NULL &&
460 		    (nconf = __rpc_getconfip("tcp")) == NULL) {
461 			*error_num = NO_RECOVERY;
462 			__IPv6_cleanup(buf);
463 			return (NULL);
464 		}
465 		nssin.op_t = NSS_HOST6;
466 		if (IN6_IS_ADDR_V4COMPAT(addr6)) {
467 			(void) memcpy(tmpbuf, addr6, sizeof (*addr6));
468 			tmpbuf[10] = 0xffU;
469 			tmpbuf[11] = 0xffU;
470 			nssin.arg.nss.host.addr = (const char *)tmpbuf;
471 		} else {
472 			nssin.arg.nss.host.addr = (const char *)addr6;
473 		}
474 		nssin.arg.nss.host.len = sizeof (struct in6_addr);
475 		nssin.arg.nss.host.type = AF_INET6;
476 		nssin.arg.nss.host.buf = buf->buffer;
477 		nssin.arg.nss.host.buflen = buf->buflen;
478 
479 		nssout.nss.host.hent = buf->result;
480 		nssout.nss.host.herrno_p = error_num;
481 		/*
482 		 * We pass in nconf and let the implementation of the
483 		 * long-named func decide whether to use the switch based on
484 		 * nc_nlookups.
485 		 */
486 		neterr =
487 			_get_hostserv_inetnetdir_byaddr(nconf, &nssin, &nssout);
488 
489 		(void) freenetconfigent(nconf);
490 		if (neterr != ND_OK) {
491 			/* Failover case, try hosts db for v4 address */
492 			if (!gethostbyaddr_r(((char *)addr6) + 12,
493 				sizeof (in_addr_t), AF_INET, buf->result,
494 				buf->buffer, buf->buflen, error_num)) {
495 				__IPv6_cleanup(buf);
496 				return (NULL);
497 			}
498 			/* Found one, now format it into mapped/compat addr */
499 			if ((res = __IPv6_alloc(NSS_BUFLEN_IPNODES)) == 0) {
500 				__IPv6_cleanup(buf);
501 				*error_num = NO_RECOVERY;
502 				return (NULL);
503 			}
504 			/* Convert IPv4 to mapped/compat address w/name */
505 			hp = res->result;
506 			(void) __mapv4tov6(buf->result, 0, res,
507 						IN6_IS_ADDR_V4MAPPED(addr6));
508 			__IPv6_cleanup(buf);
509 			free(res);
510 			return (hp);
511 		}
512 		/*
513 		 * At this point, we'll have a v4mapped hostent. If that's
514 		 * what was passed in, just return. If the request was a compat,
515 		 * twiggle the two bytes to make the mapped address a compat.
516 		 */
517 		hp = buf->result;
518 		if (IN6_IS_ADDR_V4COMPAT(addr6)) {
519 			/* LINTED pointer cast */
520 			addr6 = (struct in6_addr *)hp->h_addr_list[0];
521 			addr6->s6_addr[10] = 0;
522 			addr6->s6_addr[11] = 0;
523 		}
524 		free(buf);
525 		return (hp);
526 	}
527 	/*
528 	 * Step 2: AF_INET, v4 lookup. Since we're going to search the
529 	 * ipnodes (v6) path first, we need to treat this as a v4mapped
530 	 * address. nscd(1m) caches v4 from ipnodes as mapped v6's. The
531 	 * switch backend knows to lookup v4's (not v4mapped) from the
532 	 * name services.
533 	 */
534 	if (type == AF_INET) {
535 		struct in6_addr v4mapbuf;
536 		addr6 = &v4mapbuf;
537 
538 		IN6_INADDR_TO_V4MAPPED(addr4, addr6);
539 		if ((nconf = __rpc_getconfip("udp")) == NULL &&
540 		    (nconf = __rpc_getconfip("tcp")) == NULL) {
541 			*error_num = NO_RECOVERY;
542 			return (NULL);
543 		}
544 		if ((buf = __IPv6_alloc(NSS_BUFLEN_IPNODES)) == 0) {
545 			*error_num = NO_RECOVERY;
546 			freenetconfigent(nconf);
547 			return (NULL);
548 		}
549 		nssin.op_t = NSS_HOST6;
550 		nssin.arg.nss.host.addr = (const char *)addr6;
551 		nssin.arg.nss.host.len = sizeof (struct in6_addr);
552 		nssin.arg.nss.host.type = AF_INET6;
553 		nssin.arg.nss.host.buf = buf->buffer;
554 		nssin.arg.nss.host.buflen = buf->buflen;
555 
556 		nssout.nss.host.hent = buf->result;
557 		nssout.nss.host.herrno_p = error_num;
558 		/*
559 		 * We pass in nconf and let the implementation of the
560 		 * long-named func decide whether to use the switch based on
561 		 * nc_nlookups.
562 		 */
563 		neterr =
564 			_get_hostserv_inetnetdir_byaddr(nconf, &nssin, &nssout);
565 
566 		(void) freenetconfigent(nconf);
567 		if (neterr != ND_OK) {
568 			/* Failover case, try hosts db for v4 address */
569 			hp = buf->result;
570 			if (!gethostbyaddr_r(src, len, type, buf->result,
571 					buf->buffer, buf->buflen, error_num)) {
572 				__IPv6_cleanup(buf);
573 				return (NULL);
574 			}
575 			free(buf);
576 			return (hp);
577 		}
578 		if ((hp = __mappedtov4(buf->result, error_num)) == NULL) {
579 			__IPv6_cleanup(buf);
580 			return (NULL);
581 		}
582 		__IPv6_cleanup(buf);
583 		return (hp);
584 	}
585 	/*
586 	 * Step 3: AF_INET6, plain vanilla v6 getipnodebyaddr() call.
587 	 */
588 	if (type == AF_INET6) {
589 		if ((nconf = __rpc_getconfip("udp")) == NULL &&
590 		    (nconf = __rpc_getconfip("tcp")) == NULL) {
591 			*error_num = NO_RECOVERY;
592 			return (NULL);
593 		}
594 		if ((buf = __IPv6_alloc(NSS_BUFLEN_IPNODES)) == 0) {
595 			*error_num = NO_RECOVERY;
596 			freenetconfigent(nconf);
597 			return (NULL);
598 		}
599 		nssin.op_t = NSS_HOST6;
600 		nssin.arg.nss.host.addr = (const char *)addr6;
601 		nssin.arg.nss.host.len = len;
602 		nssin.arg.nss.host.type = type;
603 		nssin.arg.nss.host.buf = buf->buffer;
604 		nssin.arg.nss.host.buflen = buf->buflen;
605 
606 		nssout.nss.host.hent = buf->result;
607 		nssout.nss.host.herrno_p = error_num;
608 		/*
609 		 * We pass in nconf and let the implementation of the
610 		 * long-named func decide whether to use the switch based on
611 		 * nc_nlookups.
612 		 */
613 		neterr =
614 			_get_hostserv_inetnetdir_byaddr(nconf, &nssin, &nssout);
615 
616 		(void) freenetconfigent(nconf);
617 		if (neterr != ND_OK) {
618 			__IPv6_cleanup(buf);
619 			return (NULL);
620 		}
621 		free(buf);
622 		return (nssout.nss.host.hent);
623 	}
624 	/*
625 	 * If we got here, unknown type.
626 	 */
627 	*error_num = HOST_NOT_FOUND;
628 	return (NULL);
629 }
630 
631 void
632 freehostent(struct hostent *hent)
633 {
634 	free(hent);
635 }
636 
637 static int
638 __ai_addrconfig(int af)
639 {
640 	struct lifnum	lifn;
641 	hrtime_t	now, *then;
642 	static hrtime_t	then4, then6; /* the last time we updated ifnum# */
643 	static int	ifnum4 = -1, ifnum6 = -1;
644 	int		*num;
645 
646 	switch (af) {
647 	case AF_INET:
648 		num = &ifnum4;
649 		then = &then4;
650 		break;
651 	case AF_INET6:
652 		num = &ifnum6;
653 		then = &then6;
654 		break;
655 	default:
656 		return (0);
657 	}
658 
659 	/*
660 	 * We don't need to check this every time someone does a name
661 	 * lookup.  Do it every IFNUM_TIMEOUT for each address family.
662 	 *
663 	 * There's no need to protect all of this with a lock.  The
664 	 * worst that can happen is that we update the interface count
665 	 * twice instead of once.  That's no big deal.
666 	 */
667 	now = gethrtime();
668 	if (*num == -1 || ((now - *then) >= IFNUM_TIMEOUT)) {
669 		lifn.lifn_family = af;
670 		/*
671 		 * We want to determine if this machine knows anything
672 		 * at all about the address family; the status of the
673 		 * interface is less important. Hence, set
674 		 * 'lifn_flags' to zero.
675 		 */
676 		lifn.lifn_flags = 0;
677 		if (nss_ioctl(af, SIOCGLIFNUM, &lifn) < 0)
678 			return (-1);
679 
680 		*num = lifn.lifn_count;
681 		*then = now;
682 	}
683 
684 	return (*num);
685 }
686 
687 /*
688  * This routine will either convert an IPv4 address to a mapped or compat
689  * IPv6 (if he6 == NULL) or merge IPv6 (he6) addresses with mapped
690  * v4 (he4) addresses. In either case, the results are returned in res.
691  * Caller must provide all buffers.
692  * Inputs:
693  * 		he4	pointer to IPv4 buffer
694  *		he6	pointer to IPv6 buffer (NULL if not merging v4/v6
695  *		res	pointer to results buffer
696  *		mapped	mapped == 1, map IPv4 : mapped == 0, compat IPv4
697  *			mapped flag is ignored if he6 != NULL
698  *
699  * The results are packed into the res->buffer as follows:
700  * <--------------- buffer + buflen -------------------------------------->
701  * |-----------------|-----------------|----------------|----------------|
702  * | pointers vector | pointers vector | aliases grow   | addresses grow |
703  * | for addresses   | for aliases     |                |                |
704  * | this way ->     | this way ->     | <- this way    |<- this way     |
705  * |-----------------|-----------------|----------------|----------------|
706  * | grows in PASS 1 | grows in PASS2  | grows in PASS2 | grows in PASS 1|
707  */
708 static struct hostent *
709 __mapv4tov6(struct hostent *he4, struct hostent *he6, nss_XbyY_buf_t *res,
710 		int mapped)
711 {
712 	char	*buffer, *limit;
713 	int	buflen = res->buflen;
714 	struct	in6_addr *addr6p;
715 	char	*buff_locp;
716 	struct	hostent *host;
717 	int	count = 0, len, i;
718 	char	*h_namep;
719 
720 	if (he4 == NULL || res == NULL) {
721 		return (NULL);
722 	}
723 	limit = res->buffer + buflen;
724 	host = (struct hostent *)res->result;
725 	buffer = res->buffer;
726 
727 	buff_locp = (char *)ROUND_DOWN(limit, sizeof (struct in6_addr));
728 	host->h_addr_list = (char **)ROUND_UP(buffer, sizeof (char **));
729 	if ((char *)host->h_addr_list >= limit ||
730 		buff_locp <= (char *)host->h_addr_list) {
731 		return (NULL);
732 	}
733 	if (he6 == NULL) {
734 		/*
735 		 * If he6==NULL, map the v4 address into the v6 address format.
736 		 * This is used for getipnodebyaddr() (single address, mapped or
737 		 * compatible) or for v4 mapped for getipnodebyname(), which
738 		 * could be multiple addresses. This could also be a literal
739 		 * address string, which is why there is a inet_addr() call.
740 		 */
741 		for (i = 0; he4->h_addr_list[i] != NULL; i++) {
742 			buff_locp -= sizeof (struct in6_addr);
743 			if (buff_locp <=
744 				(char *)&(host->h_addr_list[count + 1])) {
745 			/*
746 			 * Has to be room for the pointer to the address we're
747 			 * about to add, as well as the final NULL ptr.
748 			 */
749 				return (NULL);
750 			}
751 			/* LINTED pointer cast */
752 			addr6p = (struct in6_addr *)buff_locp;
753 			host->h_addr_list[count] = (char *)addr6p;
754 			bzero(addr6p->s6_addr, sizeof (struct in6_addr));
755 			if (mapped) {
756 				addr6p->s6_addr[10] = 0xff;
757 				addr6p->s6_addr[11] = 0xff;
758 			}
759 			bcopy((char *)he4->h_addr_list[i],
760 				&addr6p->s6_addr[12], sizeof (struct in_addr));
761 			++count;
762 		}
763 		/*
764 		 * Set last array element to NULL and add cname as first alias
765 		 */
766 		host->h_addr_list[count] = NULL;
767 		host->h_aliases = host->h_addr_list + count + 1;
768 		count = 0;
769 		if ((int)(inet_addr(he4->h_name)) != -1) {
770 		/*
771 		 * Literal address string, since we're mapping, we need the IPv6
772 		 * V4 mapped literal address string for h_name.
773 		 */
774 			char	tmpstr[128];
775 			(void) inet_ntop(AF_INET6, host->h_addr_list[0], tmpstr,
776 							sizeof (tmpstr));
777 			buff_locp -= (len = strlen(tmpstr) + 1);
778 			h_namep = tmpstr;
779 			if (buff_locp <= (char *)(host->h_aliases))
780 				return (NULL);
781 			bcopy(h_namep, buff_locp, len);
782 			host->h_name = buff_locp;
783 			host->h_aliases = NULL; /* no aliases for literal */
784 			host->h_length = sizeof (struct in6_addr);
785 			host->h_addrtype = AF_INET6;
786 			return (host); 		/* we're done, return result */
787 		}
788 		/*
789 		 * Not a literal address string, so just copy h_name.
790 		 */
791 		buff_locp -= (len = strlen(he4->h_name) + 1);
792 		h_namep = he4->h_name;
793 		if (buff_locp <= (char *)(host->h_aliases))
794 			return (NULL);
795 		bcopy(h_namep, buff_locp, len);
796 		host->h_name = buff_locp;
797 		/*
798 		 * Pass 2 (IPv4 aliases):
799 		 */
800 		for (i = 0; he4->h_aliases[i] != NULL; i++) {
801 			buff_locp -= (len = strlen(he4->h_aliases[i]) + 1);
802 			if (buff_locp <=
803 					(char *)&(host->h_aliases[count + 1])) {
804 			/*
805 			 * Has to be room for the pointer to the address we're
806 			 * about to add, as well as the final NULL ptr.
807 			 */
808 				return (NULL);
809 			}
810 			host->h_aliases[count] = buff_locp;
811 			bcopy((char *)he4->h_aliases[i], buff_locp, len);
812 			++count;
813 		}
814 		host->h_aliases[count] = NULL;
815 		host->h_length = sizeof (struct in6_addr);
816 		host->h_addrtype = AF_INET6;
817 		return (host);
818 	} else {
819 		/*
820 		 * Merge IPv4 mapped addresses with IPv6 addresses. The
821 		 * IPv6 address will go in first, followed by the v4 mapped.
822 		 *
823 		 * Pass 1 (IPv6 addresses):
824 		 */
825 		for (i = 0; he6->h_addr_list[i] != NULL; i++) {
826 			buff_locp -= sizeof (struct in6_addr);
827 			if (buff_locp <=
828 				(char *)&(host->h_addr_list[count + 1])) {
829 			/*
830 			 * Has to be room for the pointer to the address we're
831 			 * about to add, as well as the final NULL ptr.
832 			 */
833 				return (NULL);
834 			}
835 			host->h_addr_list[count] = buff_locp;
836 			bcopy((char *)he6->h_addr_list[i], buff_locp,
837 						sizeof (struct in6_addr));
838 			++count;
839 		}
840 		/*
841 		 * Pass 1 (IPv4 mapped addresses):
842 		 */
843 		for (i = 0; he4->h_addr_list[i] != NULL; i++) {
844 			buff_locp -= sizeof (struct in6_addr);
845 			if (buff_locp <=
846 				(char *)&(host->h_addr_list[count + 1])) {
847 			/*
848 			 * Has to be room for the pointer to the address we're
849 			 * about to add, as well as the final NULL ptr.
850 			 */
851 				return (NULL);
852 			}
853 			/* LINTED pointer cast */
854 			addr6p = (struct in6_addr *)buff_locp;
855 			host->h_addr_list[count] = (char *)addr6p;
856 			bzero(addr6p->s6_addr, sizeof (struct in6_addr));
857 			addr6p->s6_addr[10] = 0xff;
858 			addr6p->s6_addr[11] = 0xff;
859 			bcopy(he4->h_addr_list[i], &addr6p->s6_addr[12],
860 						sizeof (struct in_addr));
861 			++count;
862 		}
863 		/*
864 		 * Pass 2 (IPv6 aliases, host name first). We start h_aliases
865 		 * one after where h_addr_list array ended. This is where cname
866 		 * is put, followed by all aliases. Reset count to 0, for index
867 		 * in the h_aliases array.
868 		 */
869 		host->h_addr_list[count] = NULL;
870 		host->h_aliases = host->h_addr_list + count + 1;
871 		count = 0;
872 		buff_locp -= (len = strlen(he6->h_name) + 1);
873 		if (buff_locp <= (char *)(host->h_aliases))
874 			return (NULL);
875 		bcopy(he6->h_name, buff_locp, len);
876 		host->h_name = buff_locp;
877 		for (i = 0; he6->h_aliases[i] != NULL; i++) {
878 			buff_locp -= (len = strlen(he6->h_aliases[i]) + 1);
879 			if (buff_locp <=
880 					(char *)&(host->h_aliases[count + 1])) {
881 			/*
882 			 * Has to be room for the pointer to the address we're
883 			 * about to add, as well as the final NULL ptr.
884 			 */
885 				return (NULL);
886 			}
887 			host->h_aliases[count] = buff_locp;
888 			bcopy((char *)he6->h_aliases[i], buff_locp, len);
889 			++count;
890 		}
891 		/*
892 		 * Pass 2 (IPv4 aliases):
893 		 */
894 		for (i = 0; he4->h_aliases[i] != NULL; i++) {
895 			buff_locp -= (len = strlen(he4->h_aliases[i]) + 1);
896 			if (buff_locp <=
897 					(char *)&(host->h_aliases[count + 1])) {
898 			/*
899 			 * Has to be room for the pointer to the address we're
900 			 * about to add, as well as the final NULL ptr.
901 			 */
902 				return (NULL);
903 			}
904 			host->h_aliases[count] = buff_locp;
905 			bcopy((char *)he4->h_aliases[i], buff_locp, len);
906 			++count;
907 		}
908 		host->h_aliases[count] = NULL;
909 		host->h_length = sizeof (struct in6_addr);
910 		host->h_addrtype = AF_INET6;
911 		return (host);
912 	}
913 }
914 
915 /*
916  * This routine will convert a mapped v4 hostent (AF_INET6) to a
917  * AF_INET hostent. If no mapped addrs found, then a NULL is returned.
918  * If mapped addrs found, then a new buffer is alloc'd and all the v4 mapped
919  * addresses are extracted and copied to it. On sucess, a pointer to a new
920  * hostent is returned.
921  * There are two possible errors in which case a NULL is returned.
922  * One of two error codes are returned:
923  *
924  * NO_RECOVERY - a malloc failed or the like for which there's no recovery.
925  * NO_ADDRESS - after filtering all the v4, there was nothing left!
926  *
927  * Inputs:
928  *              he              pointer to hostent with mapped v4 addresses
929  *              filter_error    pointer to return error code
930  * Return:
931  *		pointer to a malloc'd hostent with v4 addresses.
932  *
933  * The results are packed into the res->buffer as follows:
934  * <--------------- buffer + buflen -------------------------------------->
935  * |-----------------|-----------------|----------------|----------------|
936  * | pointers vector | pointers vector | aliases grow   | addresses grow |
937  * | for addresses   | for aliases     |                |                |
938  * | this way ->     | this way ->     | <- this way    |<- this way     |
939  * |-----------------|-----------------|----------------|----------------|
940  * | grows in PASS 1 | grows in PASS2  | grows in PASS2 | grows in PASS 1|
941  */
942 struct hostent *
943 __mappedtov4(struct hostent *he, int *extract_error)
944 {
945 	char	*buffer, *limit;
946 	nss_XbyY_buf_t *res;
947 	int	buflen = NSS_BUFLEN_HOSTS;
948 	struct	in_addr *addr4p;
949 	char	*buff_locp;
950 	struct	hostent *host;
951 	int	count = 0, len, i;
952 	char	*h_namep;
953 
954 	if (he == NULL) {
955 		*extract_error = NO_ADDRESS;
956 		return (NULL);
957 	}
958 	if ((__find_mapped(he, 0)) == 0) {
959 		*extract_error = NO_ADDRESS;
960 		return (NULL);
961 	}
962 	if ((res = __IPv6_alloc(NSS_BUFLEN_HOSTS)) == 0) {
963 		*extract_error = NO_RECOVERY;
964 		return (NULL);
965 	}
966 	limit = res->buffer + buflen;
967 	host = (struct hostent *)res->result;
968 	buffer = res->buffer;
969 
970 	buff_locp = (char *)ROUND_DOWN(limit, sizeof (struct in_addr));
971 	host->h_addr_list = (char **)ROUND_UP(buffer, sizeof (char **));
972 	if ((char *)host->h_addr_list >= limit ||
973 		buff_locp <= (char *)host->h_addr_list)
974 		goto cleanup;
975 	/*
976 	 * "Unmap" the v4 mapped address(es) into a v4 hostent format.
977 	 * This is used for getipnodebyaddr() (single address) or for
978 	 * v4 mapped for getipnodebyname(), which could be multiple
979 	 * addresses. This could also be a literal address string,
980 	 * which is why there is a inet_addr() call.
981 	 */
982 		for (i = 0; he->h_addr_list[i] != NULL; i++) {
983 			/* LINTED pointer cast */
984 			if (!IN6_IS_ADDR_V4MAPPED((struct in6_addr *)
985 							he->h_addr_list[i]))
986 			continue;
987 			buff_locp -= sizeof (struct in6_addr);
988 			/*
989 			 * Has to be room for the pointer to the address we're
990 			 * about to add, as well as the final NULL ptr.
991 			 */
992 			if (buff_locp <=
993 				(char *)&(host->h_addr_list[count + 1]))
994 				goto cleanup;
995 			/* LINTED pointer cast */
996 			addr4p = (struct in_addr *)buff_locp;
997 			host->h_addr_list[count] = (char *)addr4p;
998 			bzero((char *)&addr4p->s_addr,
999 						sizeof (struct in_addr));
1000 			/* LINTED pointer cast */
1001 			IN6_V4MAPPED_TO_INADDR(
1002 					(struct in6_addr *)he->h_addr_list[i],
1003 					addr4p);
1004 			++count;
1005 		}
1006 		/*
1007 		 * Set last array element to NULL and add cname as first alias
1008 		 */
1009 		host->h_addr_list[count] = NULL;
1010 		host->h_aliases = host->h_addr_list + count + 1;
1011 		count = 0;
1012 		/* Copy official host name */
1013 		buff_locp -= (len = strlen(he->h_name) + 1);
1014 		h_namep = he->h_name;
1015 		if (buff_locp <= (char *)(host->h_aliases))
1016 			goto cleanup;
1017 		bcopy(h_namep, buff_locp, len);
1018 		host->h_name = buff_locp;
1019 		/*
1020 		 * Pass 2 (IPv4 aliases):
1021 		 */
1022 		for (i = 0; he->h_aliases[i] != NULL; i++) {
1023 			buff_locp -= (len = strlen(he->h_aliases[i]) + 1);
1024 			/*
1025 			 * Has to be room for the pointer to the address we're
1026 			 * about to add, as well as the final NULL ptr.
1027 			 */
1028 			if (buff_locp <=
1029 					(char *)&(host->h_aliases[count + 1]))
1030 				goto cleanup;
1031 			host->h_aliases[count] = buff_locp;
1032 			bcopy((char *)he->h_aliases[i], buff_locp, len);
1033 			++count;
1034 		}
1035 		host->h_aliases[count] = NULL;
1036 		host->h_length = sizeof (struct in_addr);
1037 		host->h_addrtype = AF_INET;
1038 		free(res);
1039 		return (host);
1040 cleanup:
1041 	*extract_error = NO_RECOVERY;
1042 	(void) __IPv6_cleanup(res);
1043 	return (NULL);
1044 }
1045 
1046 /*
1047  * This routine takes as input a pointer to a hostent and filters out
1048  * the type of addresses specified by the af argument.  AF_INET
1049  * indicates that the caller wishes to filter out IPv4-mapped
1050  * addresses, and AF_INET6 indicates that the caller wishes to filter
1051  * out IPv6 addresses which aren't IPv4-mapped.  If filtering would
1052  * result in all addresses being filtered out, a NULL pointer is returned.
1053  * Otherwise, the he pointer passed in is returned, even if no addresses
1054  * were filtered out.
1055  */
1056 static struct hostent *
1057 __filter_addresses(int af, struct hostent *he)
1058 {
1059 	struct in6_addr	**in6addrlist, **in6addr;
1060 	boolean_t	isipv4mapped;
1061 	int		i = 0;
1062 
1063 	if (he == NULL)
1064 		return (NULL);
1065 
1066 	in6addrlist = (struct in6_addr **)he->h_addr_list;
1067 	for (in6addr = in6addrlist; *in6addr != NULL; in6addr++) {
1068 		isipv4mapped = IN6_IS_ADDR_V4MAPPED(*in6addr);
1069 
1070 		if ((af == AF_INET && !isipv4mapped) ||
1071 		    (af == AF_INET6 && isipv4mapped)) {
1072 			if (in6addrlist[i] != *in6addr)
1073 				in6addrlist[i] = *in6addr;
1074 			i++;
1075 		}
1076 	}
1077 
1078 	if (i == 0) {
1079 		/* We filtered everything out. */
1080 		return (NULL);
1081 	} else {
1082 		/* NULL terminate the list and return the hostent */
1083 		in6addrlist[i] = NULL;
1084 		return (he);
1085 	}
1086 }
1087 
1088 /*
1089  * This routine searches a hostent for v4 mapped IPv6 addresses.
1090  * he		hostent structure to seach
1091  * find_both	flag indicating if only want mapped or both map'd and v6
1092  * return values:
1093  * 			0 = No mapped addresses
1094  *			1 = Mapped v4 address found (returns on first one found)
1095  *			2 = Both v6 and v4 mapped are present
1096  *
1097  * If hostent passed in with no addresses, zero will be returned.
1098  */
1099 
1100 static int
1101 __find_mapped(struct hostent *he, int find_both)
1102 {
1103 	int i;
1104 	int mapd_found = 0;
1105 	int v6_found = 0;
1106 
1107 	for (i = 0; he->h_addr_list[i] != NULL; i++) {
1108 		/* LINTED pointer cast */
1109 		if (IN6_IS_ADDR_V4MAPPED(
1110 				(struct in6_addr *)he->h_addr_list[i])) {
1111 			if (find_both)
1112 				mapd_found = 1;
1113 			else
1114 				return (1);
1115 		} else {
1116 			v6_found = 1;
1117 		}
1118 		/* save some iterations once both found */
1119 		if (mapd_found && v6_found)
1120 			return (2);
1121 	}
1122 	return (mapd_found);
1123 }
1124 
1125 /*
1126  * This routine was added specifically for the IPv6 getipnodeby*() APIs. This
1127  * separates the result pointer (ptr to hostent+data buf) from the
1128  * nss_XbyY_buf_t ptr (required for nsswitch API). The returned hostent ptr
1129  * can be passed to freehostent() and freed independently.
1130  *
1131  *   bufp->result    bufp->buffer
1132  *		|		|
1133  *		V		V
1134  *		------------------------------------------------...--
1135  *		|struct hostent	|addresses		     aliases |
1136  *		------------------------------------------------...--
1137  *		|               |<--------bufp->buflen-------------->|
1138  */
1139 
1140 #define	ALIGN(x) ((((long)(x)) + sizeof (long) - 1) & ~(sizeof (long) - 1))
1141 
1142 static nss_XbyY_buf_t *
1143 __IPv6_alloc(int bufsz)
1144 {
1145 	nss_XbyY_buf_t *bufp;
1146 
1147 	if ((bufp = malloc(sizeof (nss_XbyY_buf_t))) == NULL)
1148 		return (NULL);
1149 
1150 	if ((bufp->result = malloc(ALIGN(sizeof (struct hostent)) + bufsz)) ==
1151 	    NULL) {
1152 		free(bufp);
1153 		return (NULL);
1154 	}
1155 	bufp->buffer = (char *)(bufp->result) + sizeof (struct hostent);
1156 	bufp->buflen = bufsz;
1157 	return (bufp);
1158 }
1159 
1160 /*
1161  * This routine is use only for error return cleanup. This will free the
1162  * hostent pointer, so don't use for successful returns.
1163  */
1164 static void
1165 __IPv6_cleanup(nss_XbyY_buf_t *bufp)
1166 {
1167 	if (bufp == NULL)
1168 		return;
1169 	if (bufp->result != NULL)
1170 		free(bufp->result);
1171 	free(bufp);
1172 }
1173