xref: /freebsd/sbin/dhclient/dispatch.c (revision e168b357aa7fe7ae2bb9b56373a3aada3ebf56d7)
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 "dhcpd.h"
43 
44 #include <sys/ioctl.h>
45 
46 #include <net/if_media.h>
47 #include <ifaddrs.h>
48 #include <poll.h>
49 
50 struct protocol *protocols;
51 struct timeout *timeouts;
52 static struct timeout *free_timeouts;
53 static int interfaces_invalidated;
54 void (*bootp_packet_handler)(struct interface_info *,
55     struct dhcp_packet *, int, unsigned int,
56     struct iaddr, struct hardware *);
57 
58 static int interface_status(struct interface_info *ifinfo);
59 
60 /*
61  * Use getifaddrs() to get a list of all the attached interfaces.  For
62  * each interface that's of type INET and not the loopback interface,
63  * register that interface with the network I/O software, figure out
64  * what subnet it's on, and add it to the list of interfaces.
65  */
66 void
67 discover_interfaces(struct interface_info *iface)
68 {
69 	struct ifaddrs *ifap, *ifa;
70 	struct sockaddr_in foo;
71 	struct ifreq *tif;
72 
73 	if (getifaddrs(&ifap) != 0)
74 		error("getifaddrs failed");
75 
76 	for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
77 		if ((ifa->ifa_flags & IFF_LOOPBACK) ||
78 		    (ifa->ifa_flags & IFF_POINTOPOINT) ||
79 		    (!(ifa->ifa_flags & IFF_UP)))
80 			continue;
81 
82 		if (strcmp(iface->name, ifa->ifa_name))
83 			continue;
84 
85 		/*
86 		 * If we have the capability, extract link information
87 		 * and record it in a linked list.
88 		 */
89 		if (ifa->ifa_addr->sa_family == AF_LINK) {
90 			struct sockaddr_dl *foo =
91 			    (struct sockaddr_dl *)ifa->ifa_addr;
92 
93 			iface->index = foo->sdl_index;
94 			iface->hw_address.hlen = foo->sdl_alen;
95 			iface->hw_address.htype = HTYPE_ETHER; /* XXX */
96 			memcpy(iface->hw_address.haddr,
97 			    LLADDR(foo), foo->sdl_alen);
98 		} else if (ifa->ifa_addr->sa_family == AF_INET) {
99 			struct iaddr addr;
100 
101 			memcpy(&foo, ifa->ifa_addr, sizeof(foo));
102 			if (foo.sin_addr.s_addr == htonl(INADDR_LOOPBACK))
103 				continue;
104 			if (!iface->ifp) {
105 				int len = IFNAMSIZ + ifa->ifa_addr->sa_len;
106 				if ((tif = malloc(len)) == NULL)
107 					error("no space to remember ifp");
108 				strlcpy(tif->ifr_name, ifa->ifa_name, IFNAMSIZ);
109 				memcpy(&tif->ifr_addr, ifa->ifa_addr,
110 				    ifa->ifa_addr->sa_len);
111 				iface->ifp = tif;
112 				iface->primary_address = foo.sin_addr;
113 			}
114 			addr.len = 4;
115 			memcpy(addr.iabuf, &foo.sin_addr.s_addr, addr.len);
116 		}
117 	}
118 
119 	if (!iface->ifp)
120 		error("%s: not found", iface->name);
121 
122 	/* Register the interface... */
123 	if_register_receive(iface);
124 	if_register_send(iface);
125 	add_protocol(iface->name, iface->rfdesc, got_one, iface);
126 	freeifaddrs(ifap);
127 }
128 
129 void
130 reinitialize_interfaces(void)
131 {
132 	interfaces_invalidated = 1;
133 }
134 
135 /*
136  * Wait for packets to come in using poll().  When a packet comes in,
137  * call receive_packet to receive the packet and possibly strip hardware
138  * addressing information from it, and then call through the
139  * bootp_packet_handler hook to try to do something with it.
140  */
141 void
142 dispatch(void)
143 {
144 	int count, i, to_msec, nfds = 0;
145 	struct protocol *l;
146 	struct pollfd *fds;
147 	time_t howlong;
148 
149 	for (l = protocols; l; l = l->next)
150 		nfds++;
151 
152 	fds = malloc(nfds * sizeof(struct pollfd));
153 	if (fds == NULL)
154 		error("Can't allocate poll structures.");
155 
156 	do {
157 		/*
158 		 * Call any expired timeouts, and then if there's still
159 		 * a timeout registered, time out the select call then.
160 		 */
161 another:
162 		if (timeouts) {
163 			struct timeout *t;
164 
165 			if (timeouts->when <= cur_time) {
166 				t = timeouts;
167 				timeouts = timeouts->next;
168 				(*(t->func))(t->what);
169 				t->next = free_timeouts;
170 				free_timeouts = t;
171 				goto another;
172 			}
173 
174 			/*
175 			 * Figure timeout in milliseconds, and check for
176 			 * potential overflow, so we can cram into an
177 			 * int for poll, while not polling with a
178 			 * negative timeout and blocking indefinitely.
179 			 */
180 			howlong = timeouts->when - cur_time;
181 			if (howlong > INT_MAX / 1000)
182 				howlong = INT_MAX / 1000;
183 			to_msec = howlong * 1000;
184 		} else
185 			to_msec = -1;
186 
187 		/* Set up the descriptors to be polled. */
188 		for (i = 0, l = protocols; l; l = l->next) {
189 			struct interface_info *ip = l->local;
190 
191 			if (ip && (l->handler != got_one || !ip->dead)) {
192 				fds[i].fd = l->fd;
193 				fds[i].events = POLLIN;
194 				fds[i].revents = 0;
195 				i++;
196 			}
197 		}
198 
199 		if (i == 0)
200 			error("No live interfaces to poll on - exiting.");
201 
202 		/* Wait for a packet or a timeout... XXX */
203 		count = poll(fds, nfds, to_msec);
204 
205 		/* Not likely to be transitory... */
206 		if (count == -1) {
207 			if (errno == EAGAIN || errno == EINTR) {
208 				time(&cur_time);
209 				continue;
210 			} else
211 				error("poll: %m");
212 		}
213 
214 		/* Get the current time... */
215 		time(&cur_time);
216 
217 		i = 0;
218 		for (l = protocols; l; l = l->next) {
219 			struct interface_info *ip;
220 			ip = l->local;
221 			if ((fds[i].revents & (POLLIN | POLLHUP))) {
222 				fds[i].revents = 0;
223 				if (ip && (l->handler != got_one ||
224 				    !ip->dead))
225 					(*(l->handler))(l);
226 				if (interfaces_invalidated)
227 					break;
228 			}
229 			i++;
230 		}
231 		interfaces_invalidated = 0;
232 	} while (1);
233 }
234 
235 
236 void
237 got_one(struct protocol *l)
238 {
239 	struct sockaddr_in from;
240 	struct hardware hfrom;
241 	struct iaddr ifrom;
242 	ssize_t result;
243 	union {
244 		/*
245 		 * Packet input buffer.  Must be as large as largest
246 		 * possible MTU.
247 		 */
248 		unsigned char packbuf[4095];
249 		struct dhcp_packet packet;
250 	} u;
251 	struct interface_info *ip = l->local;
252 
253 	if ((result = receive_packet(ip, u.packbuf, sizeof(u), &from,
254 	    &hfrom)) == -1) {
255 		warning("receive_packet failed on %s: %s", ip->name,
256 		    strerror(errno));
257 		ip->errors++;
258 		if ((!interface_status(ip)) ||
259 		    (ip->noifmedia && ip->errors > 20)) {
260 			/* our interface has gone away. */
261 			warning("Interface %s no longer appears valid.",
262 			    ip->name);
263 			ip->dead = 1;
264 			interfaces_invalidated = 1;
265 			close(l->fd);
266 			remove_protocol(l);
267 			free(ip);
268 		}
269 		return;
270 	}
271 	if (result == 0)
272 		return;
273 
274 	if (bootp_packet_handler) {
275 		ifrom.len = 4;
276 		memcpy(ifrom.iabuf, &from.sin_addr, ifrom.len);
277 
278 		(*bootp_packet_handler)(ip, &u.packet, result,
279 		    from.sin_port, ifrom, &hfrom);
280 	}
281 }
282 
283 int
284 interface_status(struct interface_info *ifinfo)
285 {
286 	char *ifname = ifinfo->name;
287 	int ifsock = ifinfo->rfdesc;
288 	struct ifreq ifr;
289 	struct ifmediareq ifmr;
290 
291 	/* get interface flags */
292 	memset(&ifr, 0, sizeof(ifr));
293 	strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
294 	if (ioctl(ifsock, SIOCGIFFLAGS, &ifr) < 0) {
295 		syslog(LOG_ERR, "ioctl(SIOCGIFFLAGS) on %s: %m", ifname);
296 		goto inactive;
297 	}
298 
299 	/*
300 	 * if one of UP and RUNNING flags is dropped,
301 	 * the interface is not active.
302 	 */
303 	if ((ifr.ifr_flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
304 		goto inactive;
305 
306 	/* Next, check carrier on the interface, if possible */
307 	if (ifinfo->noifmedia)
308 		goto active;
309 	memset(&ifmr, 0, sizeof(ifmr));
310 	strlcpy(ifmr.ifm_name, ifname, sizeof(ifmr.ifm_name));
311 	if (ioctl(ifsock, SIOCGIFMEDIA, (caddr_t)&ifmr) < 0) {
312 		if (errno != EINVAL) {
313 			syslog(LOG_DEBUG, "ioctl(SIOCGIFMEDIA) on %s: %m",
314 			    ifname);
315 
316 			ifinfo->noifmedia = 1;
317 			goto active;
318 		}
319 		/*
320 		 * EINVAL (or ENOTTY) simply means that the interface
321 		 * does not support the SIOCGIFMEDIA ioctl. We regard it alive.
322 		 */
323 		ifinfo->noifmedia = 1;
324 		goto active;
325 	}
326 	if (ifmr.ifm_status & IFM_AVALID) {
327 		switch (ifmr.ifm_active & IFM_NMASK) {
328 		case IFM_ETHER:
329 			if (ifmr.ifm_status & IFM_ACTIVE)
330 				goto active;
331 			else
332 				goto inactive;
333 			break;
334 		default:
335 			goto inactive;
336 		}
337 	}
338 inactive:
339 	return (0);
340 active:
341 	return (1);
342 }
343 
344 void
345 add_timeout(time_t when, void (*where)(void *), void *what)
346 {
347 	struct timeout *t, *q;
348 
349 	/* See if this timeout supersedes an existing timeout. */
350 	t = NULL;
351 	for (q = timeouts; q; q = q->next) {
352 		if (q->func == where && q->what == what) {
353 			if (t)
354 				t->next = q->next;
355 			else
356 				timeouts = q->next;
357 			break;
358 		}
359 		t = q;
360 	}
361 
362 	/* If we didn't supersede a timeout, allocate a timeout
363 	   structure now. */
364 	if (!q) {
365 		if (free_timeouts) {
366 			q = free_timeouts;
367 			free_timeouts = q->next;
368 			q->func = where;
369 			q->what = what;
370 		} else {
371 			q = malloc(sizeof(struct timeout));
372 			if (!q)
373 				error("Can't allocate timeout structure!");
374 			q->func = where;
375 			q->what = what;
376 		}
377 	}
378 
379 	q->when = when;
380 
381 	/* Now sort this timeout into the timeout list. */
382 
383 	/* Beginning of list? */
384 	if (!timeouts || timeouts->when > q->when) {
385 		q->next = timeouts;
386 		timeouts = q;
387 		return;
388 	}
389 
390 	/* Middle of list? */
391 	for (t = timeouts; t->next; t = t->next) {
392 		if (t->next->when > q->when) {
393 			q->next = t->next;
394 			t->next = q;
395 			return;
396 		}
397 	}
398 
399 	/* End of list. */
400 	t->next = q;
401 	q->next = NULL;
402 }
403 
404 void
405 cancel_timeout(void (*where)(void *), void *what)
406 {
407 	struct timeout *t, *q;
408 
409 	/* Look for this timeout on the list, and unlink it if we find it. */
410 	t = NULL;
411 	for (q = timeouts; q; q = q->next) {
412 		if (q->func == where && q->what == what) {
413 			if (t)
414 				t->next = q->next;
415 			else
416 				timeouts = q->next;
417 			break;
418 		}
419 		t = q;
420 	}
421 
422 	/* If we found the timeout, put it on the free list. */
423 	if (q) {
424 		q->next = free_timeouts;
425 		free_timeouts = q;
426 	}
427 }
428 
429 /* Add a protocol to the list of protocols... */
430 void
431 add_protocol(char *name, int fd, void (*handler)(struct protocol *),
432     void *local)
433 {
434 	struct protocol *p;
435 
436 	p = malloc(sizeof(*p));
437 	if (!p)
438 		error("can't allocate protocol struct for %s", name);
439 
440 	p->fd = fd;
441 	p->handler = handler;
442 	p->local = local;
443 	p->next = protocols;
444 	protocols = p;
445 }
446 
447 void
448 remove_protocol(struct protocol *proto)
449 {
450 	struct protocol *p, *next, *prev;
451 
452 	prev = NULL;
453 	for (p = protocols; p; p = next) {
454 		next = p->next;
455 		if (p == proto) {
456 			if (prev)
457 				prev->next = p->next;
458 			else
459 				protocols = p->next;
460 			free(p);
461 		}
462 	}
463 }
464 
465 int
466 interface_link_status(char *ifname)
467 {
468 	struct ifmediareq ifmr;
469 	int sock;
470 
471 	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
472 		error("Can't create socket");
473 
474 	memset(&ifmr, 0, sizeof(ifmr));
475 	strlcpy(ifmr.ifm_name, ifname, sizeof(ifmr.ifm_name));
476 	if (ioctl(sock, SIOCGIFMEDIA, (caddr_t)&ifmr) == -1) {
477 		/* EINVAL -> link state unknown. treat as active */
478 		if (errno != EINVAL)
479 			syslog(LOG_DEBUG, "ioctl(SIOCGIFMEDIA) on %s: %m",
480 			    ifname);
481 		close(sock);
482 		return (1);
483 	}
484 	close(sock);
485 
486 	if (ifmr.ifm_status & IFM_AVALID) {
487 		if ((ifmr.ifm_active & IFM_NMASK) == IFM_ETHER) {
488 			if (ifmr.ifm_status & IFM_ACTIVE)
489 				return (1);
490 			else
491 				return (0);
492 		}
493 	}
494 	return (1);
495 }
496