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