xref: /freebsd/sbin/dhclient/dispatch.c (revision 1e413cf93298b5b97441a21d9a50fdcd0ee9945e)
1 /*	$OpenBSD: dispatch.c,v 1.31 2004/09/21 04:07:03 david Exp $	*/
2 
3 /*
4  * Copyright 2004 Henning Brauer <henning@openbsd.org>
5  * Copyright (c) 1995, 1996, 1997, 1998, 1999
6  * The Internet Software Consortium.   All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of The Internet Software Consortium nor the names
18  *    of its contributors may be used to endorse or promote products derived
19  *    from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
22  * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
23  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25  * DISCLAIMED.  IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
26  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
29  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  * This software has been written for the Internet Software Consortium
36  * by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
37  * Enterprises.  To learn more about the Internet Software Consortium,
38  * see ``http://www.vix.com/isc''.  To learn more about Vixie
39  * Enterprises, see ``http://www.vix.com''.
40  */
41 
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 #include "dhcpd.h"
46 
47 #include <sys/ioctl.h>
48 
49 #include <net/if_media.h>
50 #include <ifaddrs.h>
51 #include <poll.h>
52 
53 struct protocol *protocols;
54 struct timeout *timeouts;
55 static struct timeout *free_timeouts;
56 static int interfaces_invalidated;
57 void (*bootp_packet_handler)(struct interface_info *,
58     struct dhcp_packet *, int, unsigned int,
59     struct iaddr, struct hardware *);
60 
61 static int interface_status(struct interface_info *ifinfo);
62 
63 /*
64  * Use getifaddrs() to get a list of all the attached interfaces.  For
65  * each interface that's of type INET and not the loopback interface,
66  * register that interface with the network I/O software, figure out
67  * what subnet it's on, and add it to the list of interfaces.
68  */
69 void
70 discover_interfaces(struct interface_info *iface)
71 {
72 	struct ifaddrs *ifap, *ifa;
73 	struct sockaddr_in foo;
74 	struct ifreq *tif;
75 
76 	if (getifaddrs(&ifap) != 0)
77 		error("getifaddrs failed");
78 
79 	for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
80 		if ((ifa->ifa_flags & IFF_LOOPBACK) ||
81 		    (ifa->ifa_flags & IFF_POINTOPOINT) ||
82 		    (!(ifa->ifa_flags & IFF_UP)))
83 			continue;
84 
85 		if (strcmp(iface->name, ifa->ifa_name))
86 			continue;
87 
88 		/*
89 		 * If we have the capability, extract link information
90 		 * and record it in a linked list.
91 		 */
92 		if (ifa->ifa_addr->sa_family == AF_LINK) {
93 			struct sockaddr_dl *foo =
94 			    (struct sockaddr_dl *)ifa->ifa_addr;
95 
96 			iface->index = foo->sdl_index;
97 			iface->hw_address.hlen = foo->sdl_alen;
98 			iface->hw_address.htype = HTYPE_ETHER; /* XXX */
99 			memcpy(iface->hw_address.haddr,
100 			    LLADDR(foo), foo->sdl_alen);
101 		} else if (ifa->ifa_addr->sa_family == AF_INET) {
102 			struct iaddr addr;
103 
104 			memcpy(&foo, ifa->ifa_addr, sizeof(foo));
105 			if (foo.sin_addr.s_addr == htonl(INADDR_LOOPBACK))
106 				continue;
107 			if (!iface->ifp) {
108 				int len = IFNAMSIZ + ifa->ifa_addr->sa_len;
109 				if ((tif = malloc(len)) == NULL)
110 					error("no space to remember ifp");
111 				strlcpy(tif->ifr_name, ifa->ifa_name, IFNAMSIZ);
112 				memcpy(&tif->ifr_addr, ifa->ifa_addr,
113 				    ifa->ifa_addr->sa_len);
114 				iface->ifp = tif;
115 				iface->primary_address = foo.sin_addr;
116 			}
117 			addr.len = 4;
118 			memcpy(addr.iabuf, &foo.sin_addr.s_addr, addr.len);
119 		}
120 	}
121 
122 	if (!iface->ifp)
123 		error("%s: not found", iface->name);
124 
125 	/* Register the interface... */
126 	if_register_receive(iface);
127 	if_register_send(iface);
128 	add_protocol(iface->name, iface->rfdesc, got_one, iface);
129 	freeifaddrs(ifap);
130 }
131 
132 void
133 reinitialize_interfaces(void)
134 {
135 	interfaces_invalidated = 1;
136 }
137 
138 /*
139  * Wait for packets to come in using poll().  When a packet comes in,
140  * call receive_packet to receive the packet and possibly strip hardware
141  * addressing information from it, and then call through the
142  * bootp_packet_handler hook to try to do something with it.
143  */
144 void
145 dispatch(void)
146 {
147 	int count, i, to_msec, nfds = 0;
148 	struct protocol *l;
149 	struct pollfd *fds;
150 	time_t howlong;
151 
152 	for (l = protocols; l; l = l->next)
153 		nfds++;
154 
155 	fds = malloc(nfds * sizeof(struct pollfd));
156 	if (fds == NULL)
157 		error("Can't allocate poll structures.");
158 
159 	do {
160 		/*
161 		 * Call any expired timeouts, and then if there's still
162 		 * a timeout registered, time out the select call then.
163 		 */
164 another:
165 		if (timeouts) {
166 			struct timeout *t;
167 
168 			if (timeouts->when <= cur_time) {
169 				t = timeouts;
170 				timeouts = timeouts->next;
171 				(*(t->func))(t->what);
172 				t->next = free_timeouts;
173 				free_timeouts = t;
174 				goto another;
175 			}
176 
177 			/*
178 			 * Figure timeout in milliseconds, and check for
179 			 * potential overflow, so we can cram into an
180 			 * int for poll, while not polling with a
181 			 * negative timeout and blocking indefinitely.
182 			 */
183 			howlong = timeouts->when - cur_time;
184 			if (howlong > INT_MAX / 1000)
185 				howlong = INT_MAX / 1000;
186 			to_msec = howlong * 1000;
187 		} else
188 			to_msec = -1;
189 
190 		/* Set up the descriptors to be polled. */
191 		for (i = 0, l = protocols; l; l = l->next) {
192 			struct interface_info *ip = l->local;
193 
194 			if (ip && (l->handler != got_one || !ip->dead)) {
195 				fds[i].fd = l->fd;
196 				fds[i].events = POLLIN;
197 				fds[i].revents = 0;
198 				i++;
199 			}
200 		}
201 
202 		if (i == 0)
203 			error("No live interfaces to poll on - exiting.");
204 
205 		/* Wait for a packet or a timeout... XXX */
206 		count = poll(fds, nfds, to_msec);
207 
208 		/* Not likely to be transitory... */
209 		if (count == -1) {
210 			if (errno == EAGAIN || errno == EINTR) {
211 				time(&cur_time);
212 				continue;
213 			} else
214 				error("poll: %m");
215 		}
216 
217 		/* Get the current time... */
218 		time(&cur_time);
219 
220 		i = 0;
221 		for (l = protocols; l; l = l->next) {
222 			struct interface_info *ip;
223 			ip = l->local;
224 			if ((fds[i].revents & (POLLIN | POLLHUP))) {
225 				fds[i].revents = 0;
226 				if (ip && (l->handler != got_one ||
227 				    !ip->dead))
228 					(*(l->handler))(l);
229 				if (interfaces_invalidated)
230 					break;
231 			}
232 			i++;
233 		}
234 		interfaces_invalidated = 0;
235 	} while (1);
236 }
237 
238 
239 void
240 got_one(struct protocol *l)
241 {
242 	struct sockaddr_in from;
243 	struct hardware hfrom;
244 	struct iaddr ifrom;
245 	ssize_t result;
246 	union {
247 		/*
248 		 * Packet input buffer.  Must be as large as largest
249 		 * possible MTU.
250 		 */
251 		unsigned char packbuf[4095];
252 		struct dhcp_packet packet;
253 	} u;
254 	struct interface_info *ip = l->local;
255 
256 	if ((result = receive_packet(ip, u.packbuf, sizeof(u), &from,
257 	    &hfrom)) == -1) {
258 		warning("receive_packet failed on %s: %s", ip->name,
259 		    strerror(errno));
260 		ip->errors++;
261 		if ((!interface_status(ip)) ||
262 		    (ip->noifmedia && ip->errors > 20)) {
263 			/* our interface has gone away. */
264 			warning("Interface %s no longer appears valid.",
265 			    ip->name);
266 			ip->dead = 1;
267 			interfaces_invalidated = 1;
268 			close(l->fd);
269 			remove_protocol(l);
270 			free(ip);
271 		}
272 		return;
273 	}
274 	if (result == 0)
275 		return;
276 
277 	if (bootp_packet_handler) {
278 		ifrom.len = 4;
279 		memcpy(ifrom.iabuf, &from.sin_addr, ifrom.len);
280 
281 		(*bootp_packet_handler)(ip, &u.packet, result,
282 		    from.sin_port, ifrom, &hfrom);
283 	}
284 }
285 
286 int
287 interface_status(struct interface_info *ifinfo)
288 {
289 	char *ifname = ifinfo->name;
290 	int ifsock = ifinfo->rfdesc;
291 	struct ifreq ifr;
292 	struct ifmediareq ifmr;
293 
294 	/* get interface flags */
295 	memset(&ifr, 0, sizeof(ifr));
296 	strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
297 	if (ioctl(ifsock, SIOCGIFFLAGS, &ifr) < 0) {
298 		syslog(LOG_ERR, "ioctl(SIOCGIFFLAGS) on %s: %m", ifname);
299 		goto inactive;
300 	}
301 
302 	/*
303 	 * if one of UP and RUNNING flags is dropped,
304 	 * the interface is not active.
305 	 */
306 	if ((ifr.ifr_flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
307 		goto inactive;
308 
309 	/* Next, check carrier on the interface, if possible */
310 	if (ifinfo->noifmedia)
311 		goto active;
312 	memset(&ifmr, 0, sizeof(ifmr));
313 	strlcpy(ifmr.ifm_name, ifname, sizeof(ifmr.ifm_name));
314 	if (ioctl(ifsock, SIOCGIFMEDIA, (caddr_t)&ifmr) < 0) {
315 		if (errno != EINVAL) {
316 			syslog(LOG_DEBUG, "ioctl(SIOCGIFMEDIA) on %s: %m",
317 			    ifname);
318 
319 			ifinfo->noifmedia = 1;
320 			goto active;
321 		}
322 		/*
323 		 * EINVAL (or ENOTTY) simply means that the interface
324 		 * does not support the SIOCGIFMEDIA ioctl. We regard it alive.
325 		 */
326 		ifinfo->noifmedia = 1;
327 		goto active;
328 	}
329 	if (ifmr.ifm_status & IFM_AVALID) {
330 		switch (ifmr.ifm_active & IFM_NMASK) {
331 		case IFM_ETHER:
332 		case IFM_IEEE80211:
333 			if (ifmr.ifm_status & IFM_ACTIVE)
334 				goto active;
335 			else
336 				goto inactive;
337 			break;
338 		default:
339 			goto inactive;
340 		}
341 	}
342 inactive:
343 	return (0);
344 active:
345 	return (1);
346 }
347 
348 void
349 add_timeout(time_t when, void (*where)(void *), void *what)
350 {
351 	struct timeout *t, *q;
352 
353 	/* See if this timeout supersedes an existing timeout. */
354 	t = NULL;
355 	for (q = timeouts; q; q = q->next) {
356 		if (q->func == where && q->what == what) {
357 			if (t)
358 				t->next = q->next;
359 			else
360 				timeouts = q->next;
361 			break;
362 		}
363 		t = q;
364 	}
365 
366 	/* If we didn't supersede a timeout, allocate a timeout
367 	   structure now. */
368 	if (!q) {
369 		if (free_timeouts) {
370 			q = free_timeouts;
371 			free_timeouts = q->next;
372 			q->func = where;
373 			q->what = what;
374 		} else {
375 			q = malloc(sizeof(struct timeout));
376 			if (!q)
377 				error("Can't allocate timeout structure!");
378 			q->func = where;
379 			q->what = what;
380 		}
381 	}
382 
383 	q->when = when;
384 
385 	/* Now sort this timeout into the timeout list. */
386 
387 	/* Beginning of list? */
388 	if (!timeouts || timeouts->when > q->when) {
389 		q->next = timeouts;
390 		timeouts = q;
391 		return;
392 	}
393 
394 	/* Middle of list? */
395 	for (t = timeouts; t->next; t = t->next) {
396 		if (t->next->when > q->when) {
397 			q->next = t->next;
398 			t->next = q;
399 			return;
400 		}
401 	}
402 
403 	/* End of list. */
404 	t->next = q;
405 	q->next = NULL;
406 }
407 
408 void
409 cancel_timeout(void (*where)(void *), void *what)
410 {
411 	struct timeout *t, *q;
412 
413 	/* Look for this timeout on the list, and unlink it if we find it. */
414 	t = NULL;
415 	for (q = timeouts; q; q = q->next) {
416 		if (q->func == where && q->what == what) {
417 			if (t)
418 				t->next = q->next;
419 			else
420 				timeouts = q->next;
421 			break;
422 		}
423 		t = q;
424 	}
425 
426 	/* If we found the timeout, put it on the free list. */
427 	if (q) {
428 		q->next = free_timeouts;
429 		free_timeouts = q;
430 	}
431 }
432 
433 /* Add a protocol to the list of protocols... */
434 void
435 add_protocol(char *name, int fd, void (*handler)(struct protocol *),
436     void *local)
437 {
438 	struct protocol *p;
439 
440 	p = malloc(sizeof(*p));
441 	if (!p)
442 		error("can't allocate protocol struct for %s", name);
443 
444 	p->fd = fd;
445 	p->handler = handler;
446 	p->local = local;
447 	p->next = protocols;
448 	protocols = p;
449 }
450 
451 void
452 remove_protocol(struct protocol *proto)
453 {
454 	struct protocol *p, *next, *prev;
455 
456 	prev = NULL;
457 	for (p = protocols; p; p = next) {
458 		next = p->next;
459 		if (p == proto) {
460 			if (prev)
461 				prev->next = p->next;
462 			else
463 				protocols = p->next;
464 			free(p);
465 		}
466 	}
467 }
468 
469 int
470 interface_link_status(char *ifname)
471 {
472 	struct ifmediareq ifmr;
473 	int sock;
474 
475 	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
476 		error("Can't create socket");
477 
478 	memset(&ifmr, 0, sizeof(ifmr));
479 	strlcpy(ifmr.ifm_name, ifname, sizeof(ifmr.ifm_name));
480 	if (ioctl(sock, SIOCGIFMEDIA, (caddr_t)&ifmr) == -1) {
481 		/* EINVAL -> link state unknown. treat as active */
482 		if (errno != EINVAL)
483 			syslog(LOG_DEBUG, "ioctl(SIOCGIFMEDIA) on %s: %m",
484 			    ifname);
485 		close(sock);
486 		return (1);
487 	}
488 	close(sock);
489 
490 	if (ifmr.ifm_status & IFM_AVALID) {
491 		switch (ifmr.ifm_active & IFM_NMASK) {
492 		case IFM_ETHER:
493 		case IFM_IEEE80211:
494 			if (ifmr.ifm_status & IFM_ACTIVE)
495 				return (1);
496 			else
497 				return (0);
498 		}
499 	}
500 	return (1);
501 }
502