1 /*	$NetBSD: interfaceiter.c,v 1.1.1.1 2009/12/13 16:54:40 kardel Exp $	*/
2 
3 /*
4  * Copyright (C) 2004, 2007-2009  Internet Systems Consortium, Inc. ("ISC")
5  * Copyright (C) 1999-2001  Internet Software Consortium.
6  *
7  * Permission to use, copy, modify, and/or distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
12  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
14  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
16  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17  * PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 /* Id: interfaceiter.c,v 1.13.110.2 2009/01/18 23:47:41 tbox Exp */
21 
22 /*
23  * Note that this code will need to be revisited to support IPv6 Interfaces.
24  * For now we just iterate through IPv4 interfaces.
25  */
26 
27 #include <config.h>
28 #include <winsock2.h>
29 #include <ws2tcpip.h>
30 #include <sys/types.h>
31 
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <errno.h>
35 
36 #include <isc/interfaceiter.h>
37 #include <isc/mem.h>
38 #include <isc/result.h>
39 #include <isc/string.h>
40 #include <isc/strerror.h>
41 #include <isc/types.h>
42 #include <isc/util.h>
43 
44 void InitSockets(void);
45 
46 /* Common utility functions */
47 
48 /*
49  * Extract the network address part from a "struct sockaddr".
50  *
51  * The address family is given explicitly
52  * instead of using src->sa_family, because the latter does not work
53  * for copying a network mask obtained by SIOCGIFNETMASK (it does
54  * not have a valid address family).
55  */
56 
57 
58 #define IFITER_MAGIC		0x49464954U	/* IFIT. */
59 #define VALID_IFITER(t)		((t) != NULL && (t)->magic == IFITER_MAGIC)
60 
61 struct isc_interfaceiter {
62 	unsigned int		magic;		/* Magic number. */
63 	isc_mem_t		*mctx;
64 	int			socket;
65 	INTERFACE_INFO		IFData;		/* Current Interface Info */
66 	int			numIF;		/* Current Interface count */
67 	int			v4IF;		/* Number of IPv4 Interfaces */
68 	INTERFACE_INFO		*buf4;		/* Buffer for WSAIoctl data. */
69 	unsigned int		buf4size;	/* Bytes allocated. */
70 	INTERFACE_INFO		*pos4;		/* Current offset in IF List */
71 	SOCKET_ADDRESS_LIST	*buf6;
72 	unsigned int		buf6size;	/* Bytes allocated. */
73 	unsigned int		pos6;		/* buf6 index, counts down */
74 	struct in6_addr		loop__1;	/* ::1 node-scope localhost */
75 	struct in6_addr		loopfe80__1;	/* fe80::1 link-scope localhost */
76 	isc_interface_t		current;	/* Current interface data. */
77 	isc_result_t		result;		/* Last result code. */
78 };
79 
80 
81 /*
82  * Size of buffer for SIO_GET_INTERFACE_LIST, in number of interfaces.
83  * We assume no sane system will have more than than 1K of IP addresses on
84  * all of its adapters.
85  */
86 #define IFCONF_SIZE_INITIAL	  16
87 #define IFCONF_SIZE_INCREMENT	  64
88 #define IFCONF_SIZE_MAX		1040
89 
90 static void
91 get_addr(unsigned int family, isc_netaddr_t *dst, struct sockaddr *src) {
92 	dst->family = family;
93 	switch (family) {
94 	case AF_INET:
95 		memcpy(&dst->type.in,
96 		       &((struct sockaddr_in *) src)->sin_addr,
97 		       sizeof(struct in_addr));
98 		break;
99 	case	AF_INET6:
100 		memcpy(&dst->type.in6,
101 		       &((struct sockaddr_in6 *) src)->sin6_addr,
102 		       sizeof(struct in6_addr));
103 		dst->zone = ((struct sockaddr_in6 *) src)->sin6_scope_id;
104 		break;
105 	default:
106 		INSIST(0);
107 		break;
108 	}
109 }
110 
111 /*
112  * Windows always provides 255.255.255.255 as the the broadcast
113  * address.  ntpd needs to know the broadcast address which will target
114  * only that network interface, not all.  Reconstruct it from the
115  * address and mask.
116  */
117 static void
118 get_broadcastaddr(isc_netaddr_t *bcastaddr, isc_netaddr_t *addr, isc_netaddr_t *netmask) {
119 
120 	isc_uint32_t *	b;
121 	isc_uint32_t	a, n;
122 
123 	b = (isc_uint32_t *)&bcastaddr->type.in;
124 	a = *(isc_uint32_t *)&addr->type.in;
125 	n = *(isc_uint32_t *)&netmask->type.in;
126 
127 	*b = a | ~n;
128 }
129 
130 isc_result_t
131 isc_interfaceiter_create(isc_mem_t *mctx, isc_interfaceiter_t **iterp) {
132 	char strbuf[ISC_STRERRORSIZE];
133 	isc_interfaceiter_t *iter;
134 	isc_result_t result;
135 	int error;
136 	unsigned long bytesReturned = 0;
137 
138 	REQUIRE(mctx != NULL);
139 	REQUIRE(iterp != NULL);
140 	REQUIRE(*iterp == NULL);
141 
142 	iter = isc_mem_get(mctx, sizeof(*iter));
143 	if (iter == NULL)
144 		return (ISC_R_NOMEMORY);
145 
146 	InitSockets();
147 
148 	iter->mctx = mctx;
149 	iter->buf4 = NULL;
150 	iter->buf6 = NULL;
151 	iter->pos4 = NULL;
152 	iter->pos6 = 0;
153 	iter->buf6size = 0;
154 	iter->buf4size = 0;
155 	iter->result = ISC_R_FAILURE;
156 	iter->numIF = 0;
157 	iter->v4IF = 0;
158 
159 	/*
160 	 * Create an unbound datagram socket to do the
161 	 * SIO_GET_INTERFACE_LIST WSAIoctl on.
162 	 */
163 	if ((iter->socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
164 		error = WSAGetLastError();
165 		if (error == WSAEAFNOSUPPORT)
166 			goto inet6_only;
167 		isc__strerror(error, strbuf, sizeof(strbuf));
168 		UNEXPECTED_ERROR(__FILE__, __LINE__,
169 				"making interface scan socket: %s",
170 				strbuf);
171 		result = ISC_R_UNEXPECTED;
172 		goto socket_failure;
173 	}
174 
175 	/*
176 	 * Get the interface configuration, allocating more memory if
177 	 * necessary.
178 	 */
179 	iter->buf4size = IFCONF_SIZE_INITIAL*sizeof(INTERFACE_INFO);
180 
181 	for (;;) {
182 		iter->buf4 = isc_mem_get(mctx, iter->buf4size);
183 		if (iter->buf4 == NULL) {
184 			result = ISC_R_NOMEMORY;
185 			goto alloc_failure;
186 		}
187 
188 		if (WSAIoctl(iter->socket, SIO_GET_INTERFACE_LIST,
189 			     0, 0, iter->buf4, iter->buf4size,
190 			     &bytesReturned, 0, 0) == SOCKET_ERROR)
191 		{
192 			error = WSAGetLastError();
193 			if (error != WSAEFAULT && error != WSAENOBUFS) {
194 				errno = error;
195 				isc__strerror(error, strbuf, sizeof(strbuf));
196 				UNEXPECTED_ERROR(__FILE__, __LINE__,
197 						"get interface configuration: %s",
198 						strbuf);
199 				result = ISC_R_UNEXPECTED;
200 				goto ioctl_failure;
201 			}
202 			/*
203 			 * EINVAL.  Retry with a bigger buffer.
204 			 */
205 		} else {
206 			/*
207 			 * The WSAIoctl succeeded.
208 			 * If the number of the returned bytes is the same
209 			 * as the buffer size, we will grow it just in
210 			 * case and retry.
211 			 */
212 			if (bytesReturned > 0 &&
213 			    (bytesReturned < iter->buf4size))
214 				break;
215 		}
216 		if (iter->buf4size >= IFCONF_SIZE_MAX*sizeof(INTERFACE_INFO)) {
217 			UNEXPECTED_ERROR(__FILE__, __LINE__,
218 					 "get interface configuration: "
219 					 "maximum buffer size exceeded");
220 			result = ISC_R_UNEXPECTED;
221 			goto ioctl_failure;
222 		}
223 		isc_mem_put(mctx, iter->buf4, iter->buf4size);
224 
225 		iter->buf4size += IFCONF_SIZE_INCREMENT *
226 			sizeof(INTERFACE_INFO);
227 	}
228 
229 	/*
230 	 * A newly created iterator has an undefined position
231 	 * until isc_interfaceiter_first() is called.
232 	 */
233 	iter->v4IF = bytesReturned/sizeof(INTERFACE_INFO);
234 
235 	/* We don't need the socket any more, so close it */
236 	closesocket(iter->socket);
237 
238  inet6_only:
239 	/*
240 	 * Create an unbound datagram socket to do the
241 	 * SIO_ADDRESS_LIST_QUERY WSAIoctl on.
242 	 */
243 	if ((iter->socket = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
244 		error = WSAGetLastError();
245 		if (error == WSAEAFNOSUPPORT)
246 			goto inet_only;
247 		isc__strerror(error, strbuf, sizeof(strbuf));
248 		UNEXPECTED_ERROR(__FILE__, __LINE__,
249 				"making interface scan socket: %s",
250 				strbuf);
251 		result = ISC_R_UNEXPECTED;
252 		goto ioctl_failure;
253 	}
254 
255 	/*
256 	 * Get the interface configuration, allocating more memory if
257 	 * necessary.
258 	 */
259 	iter->buf6size = sizeof(SOCKET_ADDRESS_LIST) +
260 			 IFCONF_SIZE_INITIAL*sizeof(SOCKET_ADDRESS);
261 
262 	for (;;) {
263 		iter->buf6 = isc_mem_get(mctx, iter->buf6size);
264 		if (iter->buf6 == NULL) {
265 			result = ISC_R_NOMEMORY;
266 			goto ioctl_failure;
267 		}
268 
269 		if (WSAIoctl(iter->socket, SIO_ADDRESS_LIST_QUERY,
270 			     0, 0, iter->buf6, iter->buf6size,
271 			     &bytesReturned, 0, 0) == SOCKET_ERROR)
272 		{
273 			error = WSAGetLastError();
274 			if (error != WSAEFAULT && error != WSAENOBUFS) {
275 				errno = error;
276 				isc__strerror(error, strbuf, sizeof(strbuf));
277 				UNEXPECTED_ERROR(__FILE__, __LINE__,
278 						 "sio address list query: %s",
279 						 strbuf);
280 				result = ISC_R_UNEXPECTED;
281 				goto ioctl6_failure;
282 			}
283 			/*
284 			 * EINVAL.  Retry with a bigger buffer.
285 			 */
286 		} else
287 			break;
288 
289 		if (iter->buf6size >= IFCONF_SIZE_MAX*sizeof(SOCKET_ADDRESS)) {
290 			UNEXPECTED_ERROR(__FILE__, __LINE__,
291 					 "get interface configuration: "
292 					 "maximum buffer size exceeded");
293 			result = ISC_R_UNEXPECTED;
294 			goto ioctl6_failure;
295 		}
296 		isc_mem_put(mctx, iter->buf6, iter->buf6size);
297 
298 		iter->buf6size += IFCONF_SIZE_INCREMENT *
299 			sizeof(SOCKET_ADDRESS);
300 	}
301 
302 	/*
303 	 * initialize loop__1 to [::1] and loopfe80__1 to [fe80::1].
304 	 * used by internal_current6().
305 	 */
306 	memset(&iter->loop__1, 0, sizeof(iter->loop__1));
307 	memset(&iter->loopfe80__1, 0, sizeof(iter->loopfe80__1));
308 	iter->loop__1.s6_addr[15] = 1;
309 	iter->loopfe80__1.s6_addr[15] = 1;
310 	iter->loopfe80__1.s6_addr[0] = 0xfe;
311 	iter->loopfe80__1.s6_addr[1] = 0x80;
312 
313 	closesocket(iter->socket);
314 
315  inet_only:
316 	iter->magic = IFITER_MAGIC;
317 	*iterp = iter;
318 	return (ISC_R_SUCCESS);
319 
320  ioctl6_failure:
321 	isc_mem_put(mctx, iter->buf6, iter->buf6size);
322 
323  ioctl_failure:
324 	if (iter->buf4 != NULL)
325 		isc_mem_put(mctx, iter->buf4, iter->buf4size);
326 
327  alloc_failure:
328 	if (iter->socket >= 0)
329 		(void) closesocket(iter->socket);
330 
331  socket_failure:
332 	isc_mem_put(mctx, iter, sizeof(*iter));
333 	return (result);
334 }
335 
336 /*
337  * Get information about the current interface to iter->current.
338  * If successful, return ISC_R_SUCCESS.
339  * If the interface has an unsupported address family, or if
340  * some operation on it fails, return ISC_R_IGNORE to make
341  * the higher-level iterator code ignore it.
342  */
343 
344 static isc_result_t
345 internal_current(isc_interfaceiter_t *iter) {
346 	BOOL ifNamed = FALSE;
347 	unsigned long flags;
348 
349 	REQUIRE(VALID_IFITER(iter));
350 	REQUIRE(iter->numIF >= 0);
351 
352 	memset(&iter->current, 0, sizeof(iter->current));
353 	iter->current.af = AF_INET;
354 
355 	get_addr(AF_INET, &iter->current.address,
356 		 (struct sockaddr *)&(iter->IFData.iiAddress));
357 
358 	/*
359 	 * Get interface flags.
360 	 */
361 
362 	iter->current.flags = 0;
363 	flags = iter->IFData.iiFlags;
364 
365 	if ((flags & IFF_UP) != 0)
366 		iter->current.flags |= INTERFACE_F_UP;
367 
368 	if ((flags & IFF_BROADCAST) != 0)
369 		iter->current.flags |= INTERFACE_F_BROADCAST;
370 
371 	if ((flags & IFF_MULTICAST) != 0)
372 		iter->current.flags |= INTERFACE_F_MULTICAST;
373 
374 	if ((flags & IFF_POINTTOPOINT) != 0) {
375 		iter->current.flags |= INTERFACE_F_POINTTOPOINT;
376 		sprintf(iter->current.name, "PPP %d", iter->numIF);
377 		ifNamed = TRUE;
378 	}
379 
380 	if ((flags & IFF_LOOPBACK) != 0) {
381 		iter->current.flags |= INTERFACE_F_LOOPBACK;
382 		sprintf(iter->current.name, "v4loop %d",
383 			iter->numIF);
384 		ifNamed = TRUE;
385 	}
386 
387 	/*
388 	 * If the interface is point-to-point, get the destination address.
389 	 */
390 	if ((iter->current.flags & INTERFACE_F_POINTTOPOINT) != 0) {
391 		get_addr(AF_INET, &iter->current.dstaddress,
392 		(struct sockaddr *)&(iter->IFData.iiBroadcastAddress));
393 	}
394 
395 	/*
396 	 * Get the network mask.
397 	 */
398 	get_addr(AF_INET, &iter->current.netmask,
399 		 (struct sockaddr *)&(iter->IFData.iiNetmask));
400 
401 	/*
402 	 * If the interface is broadcast, get the broadcast address,
403 	 * based on the unicast address and network mask.
404 	 */
405 	if ((iter->current.flags & INTERFACE_F_BROADCAST) != 0)
406 		get_broadcastaddr(&iter->current.broadcast,
407 				  &iter->current.address,
408 				  &iter->current.netmask);
409 
410 	if (ifNamed == FALSE)
411 		sprintf(iter->current.name,
412 			"IPv4 %d", iter->numIF);
413 
414 	return (ISC_R_SUCCESS);
415 }
416 
417 static isc_result_t
418 internal_current6(isc_interfaceiter_t *iter) {
419 	BOOL ifNamed = FALSE;
420 	struct sockaddr_in6 *psa6;
421 	BOOL localhostSeen;
422 	int i;
423 
424 	REQUIRE(VALID_IFITER(iter));
425 	REQUIRE(iter->pos6 >= 0);
426 	REQUIRE(iter->buf6 != 0);
427 
428 	memset(&iter->current, 0, sizeof(iter->current));
429 	iter->current.af = AF_INET6;
430 
431 	/*
432 	 * synthesize localhost ::1 before returning the rest, if ::1
433 	 * is not on the list.
434 	 */
435 	if (iter->pos6 >= (unsigned)iter->buf6->iAddressCount) {
436 		localhostSeen = FALSE;
437 		for (i = 0; i < iter->buf6->iAddressCount; i++) {
438 			psa6 = (struct sockaddr_in6 *)
439 			       iter->buf6->Address[i].lpSockaddr;
440 			if (!memcmp(&iter->loop__1, &psa6->sin6_addr,
441 				    sizeof(iter->loop__1))) {
442 				localhostSeen = TRUE;
443 				break;
444 			}
445 		}
446 		if (localhostSeen)
447 			iter->pos6 = iter->buf6->iAddressCount - 1;
448 	}
449 
450 	if (iter->pos6 < (unsigned)iter->buf6->iAddressCount)
451 		get_addr(AF_INET6, &iter->current.address,
452 			 iter->buf6->Address[iter->pos6].lpSockaddr);
453 	else {
454 		iter->current.address.family = AF_INET6;
455 		memcpy(&iter->current.address.type.in6, &iter->loop__1,
456 		       sizeof(iter->current.address.type.in6));
457 	}
458 
459 	/*
460 	 * Get interface flags.
461 	 */
462 
463 	iter->current.flags = INTERFACE_F_UP | INTERFACE_F_MULTICAST;
464 
465 	if (!memcmp(&iter->current.address.type.in6, &iter->loop__1,
466 		    sizeof(iter->current.address.type.in6)) ||
467 	    !memcmp(&iter->current.address.type.in6, &iter->loopfe80__1,
468 	            sizeof(iter->current.address.type.in6))) {
469 
470 		iter->current.flags |= INTERFACE_F_LOOPBACK;
471 		sprintf(iter->current.name, "v6loop %d",
472 			iter->buf6->iAddressCount - iter->pos6);
473 		ifNamed = TRUE;
474 	}
475 
476 	if (ifNamed == FALSE)
477 		sprintf(iter->current.name, "IPv6 %d",
478 			iter->buf6->iAddressCount - iter->pos6);
479 
480 	memset(iter->current.netmask.type.in6.s6_addr, 0xff,
481 	       sizeof(iter->current.netmask.type.in6.s6_addr));
482 	iter->current.netmask.family = AF_INET6;
483 	return (ISC_R_SUCCESS);
484 }
485 
486 /*
487  * Step the iterator to the next interface.  Unlike
488  * isc_interfaceiter_next(), this may leave the iterator
489  * positioned on an interface that will ultimately
490  * be ignored.  Return ISC_R_NOMORE if there are no more
491  * interfaces, otherwise ISC_R_SUCCESS.
492  */
493 static isc_result_t
494 internal_next(isc_interfaceiter_t *iter) {
495 	if (iter->numIF >= iter->v4IF)
496 		return (ISC_R_NOMORE);
497 
498 	/*
499 	 * The first one needs to be set up to point to the last
500 	 * Element of the array.  Go to the end and back up
501 	 * Microsoft's implementation is peculiar for returning
502 	 * the list in reverse order
503 	 */
504 
505 	if (iter->numIF == 0)
506 		iter->pos4 = (INTERFACE_INFO *)(iter->buf4 + (iter->v4IF));
507 
508 	iter->pos4--;
509 	if (&(iter->pos4) < &(iter->buf4))
510 		return (ISC_R_NOMORE);
511 
512 	memset(&(iter->IFData), 0, sizeof(INTERFACE_INFO));
513 	memcpy(&(iter->IFData), iter->pos4, sizeof(INTERFACE_INFO));
514 	iter->numIF++;
515 
516 	return (ISC_R_SUCCESS);
517 }
518 
519 static isc_result_t
520 internal_next6(isc_interfaceiter_t *iter) {
521 	if (iter->pos6 == 0)
522 		return (ISC_R_NOMORE);
523 	iter->pos6--;
524 	return (ISC_R_SUCCESS);
525 }
526 
527 isc_result_t
528 isc_interfaceiter_current(isc_interfaceiter_t *iter,
529 			  isc_interface_t *ifdata) {
530 	REQUIRE(iter->result == ISC_R_SUCCESS);
531 	memcpy(ifdata, &iter->current, sizeof(*ifdata));
532 	return (ISC_R_SUCCESS);
533 }
534 
535 isc_result_t
536 isc_interfaceiter_first(isc_interfaceiter_t *iter) {
537 
538 	REQUIRE(VALID_IFITER(iter));
539 
540 	/*
541 	 * SIO_ADDRESS_LIST_QUERY (used to query IPv6 addresses)
542 	 * intentionally omits localhost addresses ::1 and ::fe80 in
543 	 * some cases.  ntpd depends on enumerating ::1 to listen on
544 	 * it, and ntpq and ntpdc default to "localhost" as the target,
545 	 * so they will attempt to talk to [::1]:123 and fail. This
546 	 * means we need to synthesize ::1, which we will do first,
547 	 * hence + 1.
548 	 */
549 	if (iter->buf6 != NULL)
550 		iter->pos6 = iter->buf6->iAddressCount + 1;
551 
552 	iter->result = ISC_R_SUCCESS;
553 	return (isc_interfaceiter_next(iter));
554 }
555 
556 isc_result_t
557 isc_interfaceiter_next(isc_interfaceiter_t *iter) {
558 	isc_result_t result;
559 
560 	REQUIRE(VALID_IFITER(iter));
561 	REQUIRE(iter->result == ISC_R_SUCCESS);
562 
563 	for (;;) {
564 		result = internal_next(iter);
565 		if (result == ISC_R_NOMORE) {
566 			result = internal_next6(iter);
567 			if (result != ISC_R_SUCCESS)
568 				break;
569 			result = internal_current6(iter);
570 			if (result != ISC_R_IGNORE)
571 				break;
572 		} else if (result != ISC_R_SUCCESS)
573 			break;
574 		result = internal_current(iter);
575 		if (result != ISC_R_IGNORE)
576 			break;
577 	}
578 	iter->result = result;
579 	return (result);
580 }
581 
582 void
583 isc_interfaceiter_destroy(isc_interfaceiter_t **iterp) {
584 	isc_interfaceiter_t *iter;
585 	REQUIRE(iterp != NULL);
586 	iter = *iterp;
587 	REQUIRE(VALID_IFITER(iter));
588 
589 	if (iter->buf4 != NULL)
590 		isc_mem_put(iter->mctx, iter->buf4, iter->buf4size);
591 	if (iter->buf6 != NULL)
592 		isc_mem_put(iter->mctx, iter->buf6, iter->buf6size);
593 
594 	iter->magic = 0;
595 	isc_mem_put(iter->mctx, iter, sizeof(*iter));
596 	*iterp = NULL;
597 }
598