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