xref: /openbsd/usr.sbin/dhcpd/dispatch.c (revision 17df1aa7)
1 /*	$OpenBSD: dispatch.c,v 1.26 2010/04/19 12:22:09 claudio Exp $ */
2 
3 /*
4  * Copyright (c) 1995, 1996, 1997, 1998, 1999
5  * The Internet Software Consortium.   All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of The Internet Software Consortium nor the names
17  *    of its contributors may be used to endorse or promote products derived
18  *    from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
21  * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
22  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
23  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24  * DISCLAIMED.  IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
25  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
29  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * This software has been written for the Internet Software Consortium
35  * by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
36  * Enterprises.  To learn more about the Internet Software Consortium,
37  * see ``http://www.vix.com/isc''.  To learn more about Vixie
38  * Enterprises, see ``http://www.vix.com''.
39  */
40 
41 #include "dhcpd.h"
42 #include "sync.h"
43 #include <ifaddrs.h>
44 #include <sys/ioctl.h>
45 #include <poll.h>
46 #include <net/if_media.h>
47 
48 extern int syncfd;
49 
50 struct interface_info *interfaces;
51 struct protocol *protocols;
52 struct dhcpd_timeout *timeouts;
53 static struct dhcpd_timeout *free_timeouts;
54 static int interfaces_invalidated;
55 void (*bootp_packet_handler)(struct interface_info *,
56     struct dhcp_packet *, int, unsigned int, struct iaddr, struct hardware *);
57 
58 static int interface_status(struct interface_info *ifinfo);
59 int get_rdomain(char *);
60 
61 /* Use getifaddrs() to get a list of all the attached interfaces.
62    For each interface that's of type INET and not the loopback interface,
63    register that interface with the network I/O software, figure out what
64    subnet it's on, and add it to the list of interfaces. */
65 
66 void
67 discover_interfaces(int *rdomain)
68 {
69 	struct interface_info *tmp;
70 	struct interface_info *last, *next;
71 	struct subnet *subnet;
72 	struct shared_network *share;
73 	struct sockaddr_in foo;
74 	int ir = 0, ird;
75 	struct ifreq *tif;
76 	struct ifaddrs *ifap, *ifa;
77 
78 	if (getifaddrs(&ifap) != 0)
79 		error("getifaddrs failed");
80 
81 	/*
82 	 * If we already have a list of interfaces, the interfaces were
83 	 * requested.
84 	 */
85 	if (interfaces != NULL)
86 		ir = 1;
87 	else
88 		/* must specify an interface when rdomains are used */
89 		*rdomain = 0;
90 
91 	/* Cycle through the list of interfaces looking for IP addresses. */
92 	for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
93 		/*
94 		 * See if this is the sort of interface we want to
95 		 * deal with.  Skip loopback, point-to-point and down
96 		 * interfaces, except don't skip down interfaces if we're
97 		 * trying to get a list of configurable interfaces.
98 		 */
99 		if ((ifa->ifa_flags & IFF_LOOPBACK) ||
100 		    (ifa->ifa_flags & IFF_POINTOPOINT) ||
101 		    (!(ifa->ifa_flags & IFF_UP)))
102 			continue;
103 
104 		/* See if we've seen an interface that matches this one. */
105 		for (tmp = interfaces; tmp; tmp = tmp->next)
106 			if (!strcmp(tmp->name, ifa->ifa_name))
107 				break;
108 
109 		/* If we are looking for specific interfaces, ignore others. */
110 		if (tmp == NULL && ir)
111 			continue;
112 
113 		ird = get_rdomain(ifa->ifa_name);
114 		if (*rdomain == -1)
115 			*rdomain = ird;
116 		else if (*rdomain != ird && ir)
117 			error("Interface %s is not in rdomain %d",
118 			    tmp->name, *rdomain);
119 		else if (*rdomain != ird && !ir)
120 			continue;
121 
122 		/* If there isn't already an interface by this name,
123 		   allocate one. */
124 		if (tmp == NULL) {
125 			tmp = calloc(1, sizeof *tmp);
126 			if (!tmp)
127 				error("Insufficient memory to %s %s",
128 				    "record interface", ifa->ifa_name);
129 			strlcpy(tmp->name, ifa->ifa_name, sizeof(tmp->name));
130 			tmp->next = interfaces;
131 			tmp->noifmedia = tmp->dead = tmp->errors = 0;
132 			interfaces = tmp;
133 		}
134 
135 		/* If we have the capability, extract link information
136 		   and record it in a linked list. */
137 		if (ifa->ifa_addr->sa_family == AF_LINK) {
138 			struct sockaddr_dl *foo =
139 			    ((struct sockaddr_dl *)(ifa->ifa_addr));
140 			tmp->index = foo->sdl_index;
141 			tmp->hw_address.hlen = foo->sdl_alen;
142 			tmp->hw_address.htype = HTYPE_ETHER; /* XXX */
143 			memcpy(tmp->hw_address.haddr,
144 			    LLADDR(foo), foo->sdl_alen);
145 		} else if (ifa->ifa_addr->sa_family == AF_INET) {
146 			struct iaddr addr;
147 
148 			/* Get a pointer to the address... */
149 			bcopy(ifa->ifa_addr, &foo, sizeof(foo));
150 
151 			/* We don't want the loopback interface. */
152 			if (foo.sin_addr.s_addr == htonl (INADDR_LOOPBACK))
153 				continue;
154 
155 			/* If this is the first real IP address we've
156 			   found, keep a pointer to ifreq structure in
157 			   which we found it. */
158 			if (!tmp->ifp) {
159 				int len = (IFNAMSIZ + ifa->ifa_addr->sa_len);
160 				tif = (struct ifreq *)malloc(len);
161 				if (!tif)
162 					error("no space to remember ifp.");
163 				strlcpy(tif->ifr_name, ifa->ifa_name, IFNAMSIZ);
164 				memcpy(&tif->ifr_addr, ifa->ifa_addr,
165 				    ifa->ifa_addr->sa_len);
166 				tmp->ifp = tif;
167 				tmp->primary_address = foo.sin_addr;
168 			}
169 
170 			/* Grab the address... */
171 			addr.len = 4;
172 			memcpy(addr.iabuf, &foo.sin_addr.s_addr, addr.len);
173 
174 			/* If there's a registered subnet for this address,
175 			   connect it together... */
176 			if ((subnet = find_subnet(addr))) {
177 				/* If this interface has multiple aliases
178 				   on the same subnet, ignore all but the
179 				   first we encounter. */
180 				if (!subnet->interface) {
181 					subnet->interface = tmp;
182 					subnet->interface_address = addr;
183 				} else if (subnet->interface != tmp) {
184 					warning("Multiple %s %s: %s %s",
185 					    "interfaces match the",
186 					    "same subnet",
187 					    subnet->interface->name,
188 					    tmp->name);
189 				}
190 				share = subnet->shared_network;
191 				if (tmp->shared_network &&
192 				    tmp->shared_network != share) {
193 					warning("Interface %s matches %s",
194 					    tmp->name,
195 					    "multiple shared networks");
196 				} else {
197 					tmp->shared_network = share;
198 				}
199 
200 				if (!share->interface) {
201 					share->interface = tmp;
202 				} else if (share->interface != tmp) {
203 					warning("Multiple %s %s: %s %s",
204 					    "interfaces match the",
205 					    "same shared network",
206 					    share->interface->name,
207 					    tmp->name);
208 				}
209 			}
210 		}
211 	}
212 
213 	/* Discard interfaces we can't listen on. */
214 	last = NULL;
215 	for (tmp = interfaces; tmp; tmp = next) {
216 		next = tmp->next;
217 
218 		if (!tmp->ifp) {
219 			warning("Can't listen on %s - it has no IP address.",
220 			    tmp->name);
221 			/* Remove tmp from the list of interfaces. */
222 			if (!last)
223 				interfaces = interfaces->next;
224 			else
225 				last->next = tmp->next;
226 			continue;
227 		}
228 
229 		memcpy(&foo, &tmp->ifp->ifr_addr, sizeof tmp->ifp->ifr_addr);
230 
231 		if (!tmp->shared_network) {
232 			warning("Can't listen on %s - dhcpd.conf has no subnet "
233 			    "declaration for %s.", tmp->name,
234 			    inet_ntoa(foo.sin_addr));
235 			/* Remove tmp from the list of interfaces. */
236 			if (!last)
237 				interfaces = interfaces->next;
238 			else
239 				last->next = tmp->next;
240 			continue;
241 		}
242 
243 		last = tmp;
244 
245 		/* Find subnets that don't have valid interface addresses. */
246 		for (subnet = (tmp->shared_network ? tmp->shared_network->subnets :
247 		    NULL); subnet; subnet = subnet->next_sibling) {
248 			if (!subnet->interface_address.len) {
249 				/*
250 				 * Set the interface address for this subnet
251 				 * to the first address we found.
252 				 */
253 				subnet->interface_address.len = 4;
254 				memcpy(subnet->interface_address.iabuf,
255 				    &foo.sin_addr.s_addr, 4);
256 			}
257 		}
258 
259 		/* Register the interface... */
260 		if_register_receive(tmp);
261 		if_register_send(tmp);
262 	}
263 
264 	if (interfaces == NULL)
265 		error("No interfaces to listen on.");
266 
267 	/* Now register all the remaining interfaces as protocols. */
268 	for (tmp = interfaces; tmp; tmp = tmp->next)
269 		add_protocol(tmp->name, tmp->rfdesc, got_one, tmp);
270 
271 	freeifaddrs(ifap);
272 }
273 
274 /*
275  * Wait for packets to come in using poll().  When a packet comes in,
276  * call receive_packet to receive the packet and possibly strip hardware
277  * addressing information from it, and then call through the
278  * bootp_packet_handler hook to try to do something with it.
279  */
280 void
281 dispatch(void)
282 {
283 	int nfds, i, to_msec;
284 	struct protocol *l;
285 	static struct pollfd *fds;
286 	static int nfds_max;
287 	time_t howlong;
288 
289 	for (nfds = 0, l = protocols; l; l = l->next)
290 		nfds++;
291 	if (syncfd != -1)
292 		nfds++;
293 	if (nfds > nfds_max) {
294 		fds = realloc(fds, nfds * sizeof(struct pollfd));
295 		if (fds == NULL)
296 			error("Can't allocate poll structures.");
297 		nfds_max = nfds;
298 	}
299 
300 	for (;;) {
301 		/*
302 		 * Call any expired timeouts, and then if there's
303 		 * still a timeout registered, time out the poll
304 		 * call then.
305 		 */
306 		time(&cur_time);
307 another:
308 		if (timeouts) {
309 			if (timeouts->when <= cur_time) {
310 				struct dhcpd_timeout *t = timeouts;
311 				timeouts = timeouts->next;
312 				(*(t->func))(t->what);
313 				t->next = free_timeouts;
314 				free_timeouts = t;
315 				goto another;
316 			}
317 
318 			/*
319 			 * Figure timeout in milliseconds, and check for
320 			 * potential overflow, so we can cram into an int
321 			 * for poll, while not polling with a negative
322 			 * timeout and blocking indefinitely.
323 			 */
324 			howlong = timeouts->when - cur_time;
325 			if (howlong > INT_MAX / 1000)
326 				howlong = INT_MAX / 1000;
327 			to_msec = howlong * 1000;
328 		} else
329 			to_msec = -1;
330 
331 		/* Set up the descriptors to be polled. */
332 		for (i = 0, l = protocols; l; l = l->next) {
333 			struct interface_info *ip = l->local;
334 
335 			if (ip && (l->handler != got_one || !ip->dead)) {
336 				fds[i].fd = l->fd;
337 				fds[i].events = POLLIN;
338 				++i;
339 			}
340 		}
341 
342 		if (i == 0)
343 			error("No live interfaces to poll on - exiting.");
344 
345 		if (syncfd != -1) {
346 			/* add syncer */
347 			fds[i].fd = syncfd;
348 			fds[i].events = POLLIN;
349 		}
350 
351 		/* Wait for a packet or a timeout... */
352 		switch (poll(fds, nfds, to_msec)) {
353 		case -1:
354 			if (errno != EAGAIN && errno != EINTR)
355 				error("poll: %m");
356 			/* FALLTHROUGH */
357 		case 0:
358 			continue;	/* no packets */
359 		}
360 
361 		for (i = 0, l = protocols; l; l = l->next) {
362 			struct interface_info *ip = l->local;
363 
364 			if ((fds[i].revents & (POLLIN | POLLHUP))) {
365 				if (ip && (l->handler != got_one ||
366 				    !ip->dead))
367 					(*(l->handler))(l);
368 				if (interfaces_invalidated)
369 					break;
370 			}
371 			++i;
372 		}
373 		if ((syncfd != -1) && (fds[i].revents & (POLLIN | POLLHUP)))
374 			sync_recv();
375 		interfaces_invalidated = 0;
376 	}
377 }
378 
379 
380 void
381 got_one(struct protocol *l)
382 {
383 	struct sockaddr_in from;
384 	struct hardware hfrom;
385 	struct iaddr ifrom;
386 	ssize_t result;
387 	union {
388 		unsigned char packbuf[4095];
389 		struct dhcp_packet packet;
390 	} u;
391 	struct interface_info *ip = l->local;
392 
393 	if ((result = receive_packet(ip, u.packbuf, sizeof u,
394 	    &from, &hfrom)) == -1) {
395 		warning("receive_packet failed on %s: %s", ip->name,
396 		    strerror(errno));
397 		ip->errors++;
398 		if ((!interface_status(ip)) ||
399 		    (ip->noifmedia && ip->errors > 20)) {
400 			/* our interface has gone away. */
401 			warning("Interface %s no longer appears valid.",
402 			    ip->name);
403 			ip->dead = 1;
404 			interfaces_invalidated = 1;
405 			close(l->fd);
406 			remove_protocol(l);
407 			free(ip);
408 		}
409 		return;
410 	}
411 	if (result == 0)
412 		return;
413 
414 	if (bootp_packet_handler) {
415 		ifrom.len = 4;
416 		memcpy(ifrom.iabuf, &from.sin_addr, ifrom.len);
417 
418 		(*bootp_packet_handler)(ip, &u.packet, result,
419 		    from.sin_port, ifrom, &hfrom);
420 	}
421 }
422 
423 int
424 interface_status(struct interface_info *ifinfo)
425 {
426 	char * ifname = ifinfo->name;
427 	int ifsock = ifinfo->rfdesc;
428 	struct ifreq ifr;
429 	struct ifmediareq ifmr;
430 
431 	/* get interface flags */
432 	memset(&ifr, 0, sizeof(ifr));
433 	strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
434 	if (ioctl(ifsock, SIOCGIFFLAGS, &ifr) == -1) {
435 		syslog(LOG_ERR, "ioctl(SIOCGIFFLAGS) on %s: %m", ifname);
436 		goto inactive;
437 	}
438 	/*
439 	 * if one of UP and RUNNING flags is dropped,
440 	 * the interface is not active.
441 	 */
442 	if ((ifr.ifr_flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
443 		goto inactive;
444 
445 	/* Next, check carrier on the interface, if possible */
446 	if (ifinfo->noifmedia)
447 		goto active;
448 	memset(&ifmr, 0, sizeof(ifmr));
449 	strlcpy(ifmr.ifm_name, ifname, sizeof(ifmr.ifm_name));
450 	if (ioctl(ifsock, SIOCGIFMEDIA, (caddr_t)&ifmr) == -1) {
451 		if (errno != EINVAL) {
452 			syslog(LOG_DEBUG, "ioctl(SIOCGIFMEDIA) on %s: %m",
453 			    ifname);
454 			ifinfo->noifmedia = 1;
455 			goto active;
456 		}
457 		/*
458 		 * EINVAL (or ENOTTY) simply means that the interface
459 		 * does not support the SIOCGIFMEDIA ioctl. We regard it alive.
460 		 */
461 		ifinfo->noifmedia = 1;
462 		goto active;
463 	}
464 	if (ifmr.ifm_status & IFM_AVALID) {
465 		switch (ifmr.ifm_active & IFM_NMASK) {
466 		case IFM_ETHER:
467 			if (ifmr.ifm_status & IFM_ACTIVE)
468 				goto active;
469 			else
470 				goto inactive;
471 			break;
472 		default:
473 			goto inactive;
474 		}
475 	}
476  inactive:
477 	return (0);
478  active:
479 	return (1);
480 }
481 
482 int
483 locate_network(struct packet *packet)
484 {
485 	struct iaddr ia;
486 
487 	/* If this came through a gateway, find the corresponding subnet... */
488 	if (packet->raw->giaddr.s_addr) {
489 		struct subnet *subnet;
490 
491 		ia.len = 4;
492 		memcpy(ia.iabuf, &packet->raw->giaddr, 4);
493 		subnet = find_subnet(ia);
494 		if (subnet)
495 			packet->shared_network = subnet->shared_network;
496 		else
497 			packet->shared_network = NULL;
498 	} else {
499 		packet->shared_network = packet->interface->shared_network;
500 	}
501 	if (packet->shared_network)
502 		return 1;
503 	return 0;
504 }
505 
506 void
507 add_timeout(time_t when, void (*where)(void *), void *what)
508 {
509 	struct dhcpd_timeout *t, *q;
510 
511 	/* See if this timeout supersedes an existing timeout. */
512 	t = NULL;
513 	for (q = timeouts; q; q = q->next) {
514 		if (q->func == where && q->what == what) {
515 			if (t)
516 				t->next = q->next;
517 			else
518 				timeouts = q->next;
519 			break;
520 		}
521 		t = q;
522 	}
523 
524 	/* If we didn't supersede a timeout, allocate a timeout
525 	   structure now. */
526 	if (!q) {
527 		if (free_timeouts) {
528 			q = free_timeouts;
529 			free_timeouts = q->next;
530 			q->func = where;
531 			q->what = what;
532 		} else {
533 			q = (struct dhcpd_timeout *)malloc(sizeof (struct dhcpd_timeout));
534 			if (!q)
535 				error("Can't allocate timeout structure!");
536 			q->func = where;
537 			q->what = what;
538 		}
539 	}
540 
541 	q->when = when;
542 
543 	/* Now sort this timeout into the timeout list. */
544 
545 	/* Beginning of list? */
546 	if (!timeouts || timeouts->when > q->when) {
547 		q->next = timeouts;
548 		timeouts = q;
549 		return;
550 	}
551 
552 	/* Middle of list? */
553 	for (t = timeouts; t->next; t = t->next) {
554 		if (t->next->when > q->when) {
555 			q->next = t->next;
556 			t->next = q;
557 			return;
558 		}
559 	}
560 
561 	/* End of list. */
562 	t->next = q;
563 	q->next = NULL;
564 }
565 
566 void
567 cancel_timeout(void (*where)(void *), void *what)
568 {
569 	struct dhcpd_timeout *t, *q;
570 
571 	/* Look for this timeout on the list, and unlink it if we find it. */
572 	t = NULL;
573 	for (q = timeouts; q; q = q->next) {
574 		if (q->func == where && q->what == what) {
575 			if (t)
576 				t->next = q->next;
577 			else
578 				timeouts = q->next;
579 			break;
580 		}
581 		t = q;
582 	}
583 
584 	/* If we found the timeout, put it on the free list. */
585 	if (q) {
586 		q->next = free_timeouts;
587 		free_timeouts = q;
588 	}
589 }
590 
591 /* Add a protocol to the list of protocols... */
592 void
593 add_protocol(char *name, int fd, void (*handler)(struct protocol *),
594     void *local)
595 {
596 	struct protocol *p;
597 
598 	p = (struct protocol *)malloc(sizeof *p);
599 	if (!p)
600 		error("can't allocate protocol struct for %s", name);
601 	p->fd = fd;
602 	p->handler = handler;
603 	p->local = local;
604 	p->next = protocols;
605 	protocols = p;
606 }
607 
608 void
609 remove_protocol(struct protocol *proto)
610 {
611 	struct protocol *p, *next, *prev = NULL;
612 
613 	for (p = protocols; p; p = next) {
614 		next = p->next;
615 		if (p == proto) {
616 			if (prev)
617 				prev->next = p->next;
618 			else
619 				protocols = p->next;
620 			free(p);
621 		}
622 	}
623 }
624 
625 int
626 get_rdomain(char *name)
627 {
628 	int rv = 0, s;
629 	struct  ifreq ifr;
630 
631 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
632 		error("get_rdomain socket: %m");
633 
634 	bzero(&ifr, sizeof(ifr));
635 	strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
636 	if (ioctl(s, SIOCGIFRTABLEID, (caddr_t)&ifr) != -1)
637 		rv = ifr.ifr_rdomainid;
638 
639 	close(s);
640 	return rv;
641 }
642