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