1 /*	$NetBSD: interfaceiter.c,v 1.6 2014/12/10 04:38:01 christos Exp $	*/
2 
3 /*
4  * Copyright (C) 2004, 2007-2009, 2013, 2014  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.15 2009/01/18 23:48:14 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 	SOCKET			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;
74 	isc_interface_t		current;	/* Current interface data. */
75 	isc_result_t		result;		/* Last result code. */
76 };
77 
78 
79 /*
80  * Size of buffer for SIO_GET_INTERFACE_LIST, in number of interfaces.
81  * We assume no sane system will have more than than 1K of IP addresses on
82  * all of its adapters.
83  */
84 #define IFCONF_SIZE_INITIAL	  16
85 #define IFCONF_SIZE_INCREMENT	  64
86 #define IFCONF_SIZE_MAX		1040
87 
88 static void
89 get_addr(unsigned int family, isc_netaddr_t *dst, struct sockaddr *src) {
90 	dst->family = family;
91 	switch (family) {
92 	case AF_INET:
93 		memmove(&dst->type.in,
94 			&((struct sockaddr_in *) src)->sin_addr,
95 			sizeof(struct in_addr));
96 		break;
97 	case	AF_INET6:
98 		memmove(&dst->type.in6,
99 			&((struct sockaddr_in6 *) src)->sin6_addr,
100 			sizeof(struct in6_addr));
101 		dst->zone = ((struct sockaddr_in6 *) src)->sin6_scope_id;
102 		break;
103 	default:
104 		INSIST(0);
105 		break;
106 	}
107 }
108 
109 isc_result_t
110 isc_interfaceiter_create(isc_mem_t *mctx, isc_interfaceiter_t **iterp) {
111 	char strbuf[ISC_STRERRORSIZE];
112 	isc_interfaceiter_t *iter;
113 	isc_result_t result;
114 	int error;
115 	unsigned long bytesReturned = 0;
116 
117 	REQUIRE(mctx != NULL);
118 	REQUIRE(iterp != NULL);
119 	REQUIRE(*iterp == NULL);
120 
121 	iter = isc_mem_get(mctx, sizeof(*iter));
122 	if (iter == NULL)
123 		return (ISC_R_NOMEMORY);
124 
125 	InitSockets();
126 
127 	iter->mctx = mctx;
128 	iter->buf4 = NULL;
129 	iter->buf6 = NULL;
130 	iter->pos4 = NULL;
131 	iter->pos6 = 0;
132 	iter->buf6size = 0;
133 	iter->buf4size = 0;
134 	iter->result = ISC_R_FAILURE;
135 	iter->numIF = 0;
136 	iter->v4IF = 0;
137 
138 	/*
139 	 * Create an unbound datagram socket to do the
140 	 * SIO_GET_INTERFACE_LIST WSAIoctl on.
141 	 */
142 	iter->socket = socket(AF_INET, SOCK_DGRAM, 0);
143 	if (iter->socket == INVALID_SOCKET) {
144 		error = WSAGetLastError();
145 		if (error == WSAEAFNOSUPPORT)
146 			goto inet6_only;
147 		isc__strerror(error, strbuf, sizeof(strbuf));
148 		UNEXPECTED_ERROR(__FILE__, __LINE__,
149 				"making interface scan socket: %s",
150 				strbuf);
151 		result = ISC_R_UNEXPECTED;
152 		goto socket_failure;
153 	}
154 
155 	/*
156 	 * Get the interface configuration, allocating more memory if
157 	 * necessary.
158 	 */
159 	iter->buf4size = IFCONF_SIZE_INITIAL*sizeof(INTERFACE_INFO);
160 
161 	for (;;) {
162 		iter->buf4 = isc_mem_get(mctx, iter->buf4size);
163 		if (iter->buf4 == NULL) {
164 			result = ISC_R_NOMEMORY;
165 			goto alloc_failure;
166 		}
167 
168 		if (WSAIoctl(iter->socket, SIO_GET_INTERFACE_LIST,
169 			     0, 0, iter->buf4, iter->buf4size,
170 			     &bytesReturned, 0, 0) == SOCKET_ERROR)
171 		{
172 			error = WSAGetLastError();
173 			if (error != WSAEFAULT && error != WSAENOBUFS) {
174 				errno = error;
175 				isc__strerror(error, strbuf, sizeof(strbuf));
176 				UNEXPECTED_ERROR(__FILE__, __LINE__,
177 						"get interface configuration: %s",
178 						strbuf);
179 				result = ISC_R_UNEXPECTED;
180 				goto ioctl_failure;
181 			}
182 			/*
183 			 * EINVAL.  Retry with a bigger buffer.
184 			 */
185 		} else {
186 			/*
187 			 * The WSAIoctl succeeded.
188 			 * If the number of the returned bytes is the same
189 			 * as the buffer size, we will grow it just in
190 			 * case and retry.
191 			 */
192 			if (bytesReturned > 0 &&
193 			    (bytesReturned < iter->buf4size))
194 				break;
195 		}
196 		if (iter->buf4size >= IFCONF_SIZE_MAX*sizeof(INTERFACE_INFO)) {
197 			UNEXPECTED_ERROR(__FILE__, __LINE__,
198 					 "get interface configuration: "
199 					 "maximum buffer size exceeded");
200 			result = ISC_R_UNEXPECTED;
201 			goto ioctl_failure;
202 		}
203 		isc_mem_put(mctx, iter->buf4, iter->buf4size);
204 
205 		iter->buf4size += IFCONF_SIZE_INCREMENT *
206 			sizeof(INTERFACE_INFO);
207 	}
208 
209 	/*
210 	 * A newly created iterator has an undefined position
211 	 * until isc_interfaceiter_first() is called.
212 	 */
213 	iter->v4IF = bytesReturned/sizeof(INTERFACE_INFO);
214 
215 	/* We don't need the socket any more, so close it */
216 	closesocket(iter->socket);
217 
218  inet6_only:
219 	/*
220 	 * Create an unbound datagram socket to do the
221 	 * SIO_ADDRESS_LIST_QUERY WSAIoctl on.
222 	 */
223 	iter->socket = socket(AF_INET6, SOCK_DGRAM, 0);
224 	if (iter->socket == INVALID_SOCKET) {
225 		error = WSAGetLastError();
226 		if (error == WSAEAFNOSUPPORT)
227 			goto inet_only;
228 		isc__strerror(error, strbuf, sizeof(strbuf));
229 		UNEXPECTED_ERROR(__FILE__, __LINE__,
230 				"making interface scan socket: %s",
231 				strbuf);
232 		result = ISC_R_UNEXPECTED;
233 		goto ioctl_failure;
234 	}
235 
236 	/*
237 	 * Get the interface configuration, allocating more memory if
238 	 * necessary.
239 	 */
240 	iter->buf6size = sizeof(SOCKET_ADDRESS_LIST) +
241 			 IFCONF_SIZE_INITIAL*sizeof(SOCKET_ADDRESS);
242 
243 	for (;;) {
244 		iter->buf6 = isc_mem_get(mctx, iter->buf6size);
245 		if (iter->buf6 == NULL) {
246 			result = ISC_R_NOMEMORY;
247 			goto ioctl_failure;
248 		}
249 
250 		if (WSAIoctl(iter->socket, SIO_ADDRESS_LIST_QUERY,
251 			     0, 0, iter->buf6, iter->buf6size,
252 			     &bytesReturned, 0, 0) == SOCKET_ERROR)
253 		{
254 			error = WSAGetLastError();
255 			if (error != WSAEFAULT && error != WSAENOBUFS) {
256 				errno = error;
257 				isc__strerror(error, strbuf, sizeof(strbuf));
258 				UNEXPECTED_ERROR(__FILE__, __LINE__,
259 						 "sio address list query: %s",
260 						 strbuf);
261 				result = ISC_R_UNEXPECTED;
262 				goto ioctl6_failure;
263 			}
264 			/*
265 			 * EINVAL.  Retry with a bigger buffer.
266 			 */
267 		} else
268 			break;
269 
270 		if (iter->buf6size >= IFCONF_SIZE_MAX*sizeof(SOCKET_ADDRESS)) {
271 			UNEXPECTED_ERROR(__FILE__, __LINE__,
272 					 "get interface configuration: "
273 					 "maximum buffer size exceeded");
274 			result = ISC_R_UNEXPECTED;
275 			goto ioctl6_failure;
276 		}
277 		isc_mem_put(mctx, iter->buf6, iter->buf6size);
278 
279 		iter->buf6size += IFCONF_SIZE_INCREMENT *
280 			sizeof(SOCKET_ADDRESS);
281 	}
282 
283 	closesocket(iter->socket);
284 
285  inet_only:
286 	iter->magic = IFITER_MAGIC;
287 	*iterp = iter;
288 	return (ISC_R_SUCCESS);
289 
290  ioctl6_failure:
291 	isc_mem_put(mctx, iter->buf6, iter->buf6size);
292 
293  ioctl_failure:
294 	if (iter->buf4 != NULL)
295 		isc_mem_put(mctx, iter->buf4, iter->buf4size);
296 
297  alloc_failure:
298 	if (iter->socket != INVALID_SOCKET)
299 		(void) closesocket(iter->socket);
300 
301  socket_failure:
302 	isc_mem_put(mctx, iter, sizeof(*iter));
303 	return (result);
304 }
305 
306 /*
307  * Get information about the current interface to iter->current.
308  * If successful, return ISC_R_SUCCESS.
309  * If the interface has an unsupported address family, or if
310  * some operation on it fails, return ISC_R_IGNORE to make
311  * the higher-level iterator code ignore it.
312  */
313 
314 static isc_result_t
315 internal_current(isc_interfaceiter_t *iter) {
316 	BOOL ifNamed = FALSE;
317 	unsigned long flags;
318 
319 	REQUIRE(VALID_IFITER(iter));
320 	REQUIRE(iter->numIF >= 0);
321 
322 	memset(&iter->current, 0, sizeof(iter->current));
323 	iter->current.af = AF_INET;
324 
325 	get_addr(AF_INET, &iter->current.address,
326 		 (struct sockaddr *)&(iter->IFData.iiAddress));
327 
328 	/*
329 	 * Get interface flags.
330 	 */
331 
332 	iter->current.flags = 0;
333 	flags = iter->IFData.iiFlags;
334 
335 	if ((flags & IFF_UP) != 0)
336 		iter->current.flags |= INTERFACE_F_UP;
337 
338 	if ((flags & IFF_POINTTOPOINT) != 0) {
339 		iter->current.flags |= INTERFACE_F_POINTTOPOINT;
340 		sprintf(iter->current.name, "PPP Interface %d", iter->numIF);
341 		ifNamed = TRUE;
342 	}
343 
344 	if ((flags & IFF_LOOPBACK) != 0) {
345 		iter->current.flags |= INTERFACE_F_LOOPBACK;
346 		sprintf(iter->current.name, "Loopback Interface %d",
347 			iter->numIF);
348 		ifNamed = TRUE;
349 	}
350 
351 	/*
352 	 * If the interface is point-to-point, get the destination address.
353 	 */
354 	if ((iter->current.flags & INTERFACE_F_POINTTOPOINT) != 0) {
355 		get_addr(AF_INET, &iter->current.dstaddress,
356 		(struct sockaddr *)&(iter->IFData.iiBroadcastAddress));
357 	}
358 
359 	if (ifNamed == FALSE)
360 		sprintf(iter->current.name,
361 			"TCP/IP Interface %d", iter->numIF);
362 
363 	/*
364 	 * Get the network mask.
365 	 */
366 	get_addr(AF_INET, &iter->current.netmask,
367 		 (struct sockaddr *)&(iter->IFData.iiNetmask));
368 
369 	return (ISC_R_SUCCESS);
370 }
371 
372 static isc_result_t
373 internal_current6(isc_interfaceiter_t *iter) {
374 	BOOL ifNamed = FALSE;
375 	int i;
376 
377 	REQUIRE(VALID_IFITER(iter));
378 	REQUIRE(iter->pos6 >= 0);
379 	REQUIRE(iter->buf6 != 0);
380 
381 	memset(&iter->current, 0, sizeof(iter->current));
382 	iter->current.af = AF_INET6;
383 
384 	get_addr(AF_INET6, &iter->current.address,
385 		 iter->buf6->Address[iter->pos6].lpSockaddr);
386 
387 	/*
388 	 * Get interface flags.
389 	 */
390 
391 	iter->current.flags = INTERFACE_F_UP;
392 
393 	if (ifNamed == FALSE)
394 		sprintf(iter->current.name,
395 			"TCP/IPv6 Interface %d", iter->pos6 + 1);
396 
397 	for (i = 0; i< 16; i++)
398 		iter->current.netmask.type.in6.s6_addr[i] = 0xff;
399 	iter->current.netmask.family = AF_INET6;
400 	return (ISC_R_SUCCESS);
401 }
402 
403 /*
404  * Step the iterator to the next interface.  Unlike
405  * isc_interfaceiter_next(), this may leave the iterator
406  * positioned on an interface that will ultimately
407  * be ignored.  Return ISC_R_NOMORE if there are no more
408  * interfaces, otherwise ISC_R_SUCCESS.
409  */
410 static isc_result_t
411 internal_next(isc_interfaceiter_t *iter) {
412 	if (iter->numIF >= iter->v4IF)
413 		return (ISC_R_NOMORE);
414 
415 	/*
416 	 * The first one needs to be set up to point to the last
417 	 * Element of the array.  Go to the end and back up
418 	 * Microsoft's implementation is peculiar for returning
419 	 * the list in reverse order
420 	 */
421 
422 	if (iter->numIF == 0)
423 		iter->pos4 = (INTERFACE_INFO *)(iter->buf4 + (iter->v4IF));
424 
425 	iter->pos4--;
426 	if (&(iter->pos4) < &(iter->buf4))
427 		return (ISC_R_NOMORE);
428 
429 	memset(&(iter->IFData), 0, sizeof(INTERFACE_INFO));
430 	memmove(&(iter->IFData), iter->pos4, sizeof(INTERFACE_INFO));
431 	iter->numIF++;
432 
433 	return (ISC_R_SUCCESS);
434 }
435 
436 static isc_result_t
437 internal_next6(isc_interfaceiter_t *iter) {
438 	if (iter->pos6 == 0)
439 		return (ISC_R_NOMORE);
440 	iter->pos6--;
441 	return (ISC_R_SUCCESS);
442 }
443 
444 isc_result_t
445 isc_interfaceiter_current(isc_interfaceiter_t *iter,
446 			  isc_interface_t *ifdata) {
447 	REQUIRE(iter->result == ISC_R_SUCCESS);
448 	memmove(ifdata, &iter->current, sizeof(*ifdata));
449 	return (ISC_R_SUCCESS);
450 }
451 
452 isc_result_t
453 isc_interfaceiter_first(isc_interfaceiter_t *iter) {
454 
455 	REQUIRE(VALID_IFITER(iter));
456 
457 	if (iter->buf6 != NULL)
458 		iter->pos6 = iter->buf6->iAddressCount;
459 	iter->result = ISC_R_SUCCESS;
460 	return (isc_interfaceiter_next(iter));
461 }
462 
463 isc_result_t
464 isc_interfaceiter_next(isc_interfaceiter_t *iter) {
465 	isc_result_t result;
466 
467 	REQUIRE(VALID_IFITER(iter));
468 	REQUIRE(iter->result == ISC_R_SUCCESS);
469 
470 	for (;;) {
471 		result = internal_next(iter);
472 		if (result == ISC_R_NOMORE) {
473 			result = internal_next6(iter);
474 			if (result != ISC_R_SUCCESS)
475 				break;
476 			result = internal_current6(iter);
477 			if (result != ISC_R_IGNORE)
478 				break;
479 		} else if (result != ISC_R_SUCCESS)
480 			break;
481 		result = internal_current(iter);
482 		if (result != ISC_R_IGNORE)
483 			break;
484 	}
485 	iter->result = result;
486 	return (result);
487 }
488 
489 void
490 isc_interfaceiter_destroy(isc_interfaceiter_t **iterp) {
491 	isc_interfaceiter_t *iter;
492 	REQUIRE(iterp != NULL);
493 	iter = *iterp;
494 	REQUIRE(VALID_IFITER(iter));
495 
496 	if (iter->buf4 != NULL)
497 		isc_mem_put(iter->mctx, iter->buf4, iter->buf4size);
498 	if (iter->buf6 != NULL)
499 		isc_mem_put(iter->mctx, iter->buf6, iter->buf6size);
500 
501 	iter->magic = 0;
502 	isc_mem_put(iter->mctx, iter, sizeof(*iter));
503 	*iterp = NULL;
504 }
505