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