xref: /openbsd-src/usr.sbin/dhcrelay6/dispatch.c (revision be691f3bb6417f04a68938fadbcaee2d5795e764)
1 /*	$OpenBSD: dispatch.c,v 1.2 2021/01/17 13:41:24 claudio 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 <sys/types.h>
43 #include <sys/ioctl.h>
44 #include <sys/socket.h>
45 
46 #include <net/if.h>
47 #include <net/if_dl.h>
48 #include <net/if_media.h>
49 #include <net/if_types.h>
50 
51 #include <netinet/in.h>
52 #include <netinet/if_ether.h>
53 
54 #include <errno.h>
55 #include <ifaddrs.h>
56 #include <limits.h>
57 #include <poll.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 "dhcpd.h"
66 #include "log.h"
67 
68 /*
69  * Macros implementation used to generate link-local addresses. This
70  * code was copied from: sys/netinet6/in6_ifattach.c.
71  */
72 #define EUI64_UBIT		0x02
73 #define EUI64_TO_IFID(in6) \
74 	do { (in6)->s6_addr[8] ^= EUI64_UBIT; } while (0)
75 
76 struct protocol *protocols;
77 struct timeout *timeouts;
78 static struct timeout *free_timeouts;
79 static int interfaces_invalidated;
80 
81 void (*bootp_packet_handler)(struct interface_info *,
82     void *, size_t, struct packet_ctx *);
83 
84 static int interface_status(struct interface_info *ifinfo);
85 
86 struct interface_info *
87 iflist_getbyindex(unsigned int index)
88 {
89 	struct interface_info	*intf;
90 
91 	TAILQ_FOREACH(intf, &intflist, entry) {
92 		if (intf->index != index)
93 			continue;
94 
95 		return intf;
96 	}
97 
98 	return NULL;
99 }
100 
101 struct interface_info *
102 iflist_getbyname(const char *name)
103 {
104 	struct interface_info	*intf;
105 
106 	TAILQ_FOREACH(intf, &intflist, entry) {
107 		if (strcmp(intf->name, name) != 0)
108 			continue;
109 
110 		return intf;
111 	}
112 
113 	return NULL;
114 }
115 
116 struct interface_info *
117 iflist_getbyaddr6(struct in6_addr *addr)
118 {
119 	struct interface_info	*intf;
120 
121 	TAILQ_FOREACH(intf, &intflist, entry) {
122 		/* Look for link-layer address. */
123 		if (memcmp(&intf->linklocal, addr, sizeof(*addr)) == 0)
124 			return intf;
125 	}
126 
127 	return NULL;
128 }
129 
130 void
131 setup_iflist(void)
132 {
133 	struct interface_info		*intf;
134 	struct sockaddr_dl		*sdl;
135 	struct ifaddrs			*ifap, *ifa;
136 	struct if_data			*ifi;
137 	struct sockaddr_in		*sin;
138 	struct sockaddr_in6		*sin6;
139 
140 	TAILQ_INIT(&intflist);
141 	if (getifaddrs(&ifap))
142 		fatalx("getifaddrs failed");
143 
144 	for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
145 		if ((ifa->ifa_flags & IFF_LOOPBACK) ||
146 		    (ifa->ifa_flags & IFF_POINTOPOINT))
147 			continue;
148 
149 		/* Find interface or create it. */
150 		intf = iflist_getbyname(ifa->ifa_name);
151 		if (intf == NULL) {
152 			intf = calloc(1, sizeof(*intf));
153 			if (intf == NULL)
154 				fatal("calloc");
155 
156 			strlcpy(intf->name, ifa->ifa_name,
157 			    sizeof(intf->name));
158 			TAILQ_INSERT_HEAD(&intflist, intf, entry);
159 		}
160 
161 		/* Signal disabled interface. */
162 		if ((ifa->ifa_flags & IFF_UP) == 0)
163 			intf->dead = 1;
164 
165 		if (ifa->ifa_addr->sa_family == AF_LINK) {
166 			sdl = (struct sockaddr_dl *)ifa->ifa_addr;
167 			ifi = (struct if_data *)ifa->ifa_data;
168 
169 			/* Skip non ethernet interfaces. */
170 			if (ifi->ifi_type != IFT_ETHER &&
171 			    ifi->ifi_type != IFT_ENC) {
172 				TAILQ_REMOVE(&intflist, intf, entry);
173 				free(intf);
174 				continue;
175 			}
176 
177 			intf->index = sdl->sdl_index;
178 			intf->hw_address.hlen = sdl->sdl_alen;
179 			memcpy(intf->hw_address.haddr,
180 			    LLADDR(sdl), sdl->sdl_alen);
181 		} else if (ifa->ifa_addr->sa_family == AF_INET) {
182 			sin = (struct sockaddr_in *)ifa->ifa_addr;
183 			if (sin->sin_addr.s_addr == htonl(INADDR_LOOPBACK) ||
184 			    intf->primary_address.s_addr != INADDR_ANY)
185 				continue;
186 
187 			intf->primary_address = sin->sin_addr;
188 		} else if (ifa->ifa_addr->sa_family == AF_INET6) {
189 			sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
190 			if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
191 				intf->linklocal = sin6->sin6_addr;
192 #ifdef __KAME__
193 				/*
194 				 * Remove possible scope from address if
195 				 * link-local.
196 				 */
197 				intf->linklocal.s6_addr[2] = 0;
198 				intf->linklocal.s6_addr[3] = 0;
199 #endif
200 			} else
201 				intf->gipv6 = 1;
202 
203 			/* At least one IPv6 address was found. */
204 			intf->ipv6 = 1;
205 		}
206 	}
207 
208 	freeifaddrs(ifap);
209 
210 	/*
211 	 * Generate link-local IPv6 address for interfaces without it.
212 	 *
213 	 * For IPv6 DHCP Relay it doesn't matter what is used for
214 	 * link-addr field, so let's generate an address that won't
215 	 * change during execution so we can always find the interface
216 	 * to relay packets back. This is only used for layer 2 relaying
217 	 * when the interface might not have an address.
218 	 */
219 	TAILQ_FOREACH(intf, &intflist, entry) {
220 		if (memcmp(&intf->linklocal, &in6addr_any,
221 		    sizeof(in6addr_any)) != 0)
222 			continue;
223 
224 		intf->linklocal.s6_addr[0] = 0xfe;
225 		intf->linklocal.s6_addr[1] = 0x80;
226 		intf->linklocal.s6_addr[8] = intf->hw_address.haddr[0];
227 		intf->linklocal.s6_addr[9] = intf->hw_address.haddr[1];
228 		intf->linklocal.s6_addr[10] = intf->hw_address.haddr[2];
229 		intf->linklocal.s6_addr[11] = 0xff;
230 		intf->linklocal.s6_addr[12] = 0xfe;
231 		intf->linklocal.s6_addr[13] = intf->hw_address.haddr[3];
232 		intf->linklocal.s6_addr[14] = intf->hw_address.haddr[4];
233 		intf->linklocal.s6_addr[15] = intf->hw_address.haddr[5];
234 		EUI64_TO_IFID(&intf->linklocal);
235 	}
236 }
237 
238 struct interface_info *
239 register_interface(const char *ifname, void (*handler)(struct protocol *))
240 {
241 	struct interface_info		*intf;
242 
243 	if ((intf = iflist_getbyname(ifname)) == NULL)
244 		return NULL;
245 
246 	/* Don't register disabled interfaces. */
247 	if (intf->dead)
248 		return NULL;
249 
250 	/* Check if we already registered the interface. */
251 	if (intf->ifr.ifr_name[0] != 0)
252 		return intf;
253 
254 	if (strlcpy(intf->ifr.ifr_name, ifname,
255 	    sizeof(intf->ifr.ifr_name)) >= sizeof(intf->ifr.ifr_name))
256 		fatalx("interface name '%s' too long", ifname);
257 
258 	if_register_receive(intf);
259 	if_register_send(intf);
260 	add_protocol(intf->name, intf->rfdesc, handler, intf);
261 
262 	return intf;
263 }
264 
265 /*
266  * Wait for packets to come in using poll().  When a packet comes in,
267  * call receive_packet to receive the packet and possibly strip hardware
268  * addressing information from it, and then call through the
269  * bootp_packet_handler hook to try to do something with it.
270  */
271 void
272 dispatch(void)
273 {
274 	int count, i, to_msec, nfds = 0;
275 	struct protocol *l;
276 	struct pollfd *fds;
277 	time_t howlong;
278 
279 	nfds = 0;
280 	for (l = protocols; l; l = l->next)
281 		nfds++;
282 
283 	fds = calloc(nfds, sizeof(struct pollfd));
284 	if (fds == NULL)
285 		fatalx("Can't allocate poll structures.");
286 
287 	do {
288 		/*
289 		 * Call any expired timeouts, and then if there's still
290 		 * a timeout registered, time out the select call then.
291 		 */
292 another:
293 		if (timeouts) {
294 			if (timeouts->when <= cur_time) {
295 				struct timeout *t = timeouts;
296 
297 				timeouts = timeouts->next;
298 				(*(t->func))(t->what);
299 				t->next = free_timeouts;
300 				free_timeouts = t;
301 				goto another;
302 			}
303 
304 			/*
305 			 * Figure timeout in milliseconds, and check for
306 			 * potential overflow, so we can cram into an
307 			 * int for poll, while not polling with a
308 			 * negative timeout and blocking indefinitely.
309 			 */
310 			howlong = timeouts->when - cur_time;
311 			if (howlong > INT_MAX / 1000)
312 				howlong = INT_MAX / 1000;
313 			to_msec = howlong * 1000;
314 		} else
315 			to_msec = -1;
316 
317 		/* Set up the descriptors to be polled. */
318 		i = 0;
319 
320 		for (l = protocols; l; l = l->next) {
321 			struct interface_info *ip = l->local;
322 
323 			if (ip && (l->handler != got_one || !ip->dead)) {
324 				fds[i].fd = l->fd;
325 				fds[i].events = POLLIN;
326 				fds[i].revents = 0;
327 				i++;
328 			}
329 		}
330 
331 		if (i == 0)
332 			fatalx("No live interfaces to poll on - exiting.");
333 
334 		/* Wait for a packet or a timeout... XXX */
335 		count = poll(fds, nfds, to_msec);
336 
337 		/* Not likely to be transitory... */
338 		if (count == -1) {
339 			if (errno == EAGAIN || errno == EINTR) {
340 				time(&cur_time);
341 				continue;
342 			}
343 			else
344 				fatal("poll");
345 		}
346 
347 		/* Get the current time... */
348 		time(&cur_time);
349 
350 		i = 0;
351 		for (l = protocols; l; l = l->next) {
352 			struct interface_info *ip = l->local;
353 
354 			if ((fds[i].revents & (POLLIN | POLLHUP))) {
355 				fds[i].revents = 0;
356 				if (ip && (l->handler != got_one ||
357 				    !ip->dead))
358 					(*(l->handler))(l);
359 				if (interfaces_invalidated)
360 					break;
361 			}
362 			i++;
363 		}
364 		interfaces_invalidated = 0;
365 	} while (1);
366 }
367 
368 
369 void
370 got_one(struct protocol *l)
371 {
372 	struct packet_ctx pc;
373 	ssize_t result;
374 	uint8_t buf[4096];
375 	struct interface_info *ip = l->local;
376 
377 	memset(&pc, 0, sizeof(pc));
378 
379 	if ((result = receive_packet(ip, buf, sizeof(buf), &pc)) == -1) {
380 		log_warn("receive_packet failed on %s", ip->name);
381 		ip->errors++;
382 		if ((!interface_status(ip)) ||
383 		    (ip->noifmedia && ip->errors > 20)) {
384 			/* our interface has gone away. */
385 			log_warnx("Interface %s no longer appears valid.",
386 			    ip->name);
387 			ip->dead = 1;
388 			interfaces_invalidated = 1;
389 			close(l->fd);
390 			remove_protocol(l);
391 			free(ip);
392 		}
393 		return;
394 	}
395 	if (result == 0)
396 		return;
397 
398 	if (bootp_packet_handler)
399 		(*bootp_packet_handler)(ip, buf, result, &pc);
400 }
401 
402 int
403 interface_status(struct interface_info *ifinfo)
404 {
405 	char *ifname = ifinfo->name;
406 	int ifsock = ifinfo->rfdesc;
407 	struct ifreq ifr;
408 	struct ifmediareq ifmr;
409 
410 	/* get interface flags */
411 	memset(&ifr, 0, sizeof(ifr));
412 	strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
413 	if (ioctl(ifsock, SIOCGIFFLAGS, &ifr) == -1) {
414 		log_warn("ioctl(SIOCGIFFLAGS) on %s", ifname);
415 		goto inactive;
416 	}
417 	/*
418 	 * if one of UP and RUNNING flags is dropped,
419 	 * the interface is not active.
420 	 */
421 	if ((ifr.ifr_flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING)) {
422 		goto inactive;
423 	}
424 	/* Next, check carrier on the interface, if possible */
425 	if (ifinfo->noifmedia)
426 		goto active;
427 	memset(&ifmr, 0, sizeof(ifmr));
428 	strlcpy(ifmr.ifm_name, ifname, sizeof(ifmr.ifm_name));
429 	if (ioctl(ifsock, SIOCGIFMEDIA, (caddr_t)&ifmr) == -1) {
430 		if (errno != EINVAL) {
431 			log_debug("ioctl(SIOCGIFMEDIA) on %s", ifname);
432 			ifinfo->noifmedia = 1;
433 			goto active;
434 		}
435 		/*
436 		 * EINVAL (or ENOTTY) simply means that the interface
437 		 * does not support the SIOCGIFMEDIA ioctl. We regard it alive.
438 		 */
439 		ifinfo->noifmedia = 1;
440 		goto active;
441 	}
442 	if (ifmr.ifm_status & IFM_AVALID) {
443 		switch (ifmr.ifm_active & IFM_NMASK) {
444 		case IFM_ETHER:
445 			if (ifmr.ifm_status & IFM_ACTIVE)
446 				goto active;
447 			else
448 				goto inactive;
449 			break;
450 		default:
451 			goto inactive;
452 		}
453 	}
454 inactive:
455 	return (0);
456 active:
457 	return (1);
458 }
459 
460 /* Add a protocol to the list of protocols... */
461 void
462 add_protocol(char *name, int fd, void (*handler)(struct protocol *),
463     void *local)
464 {
465 	struct protocol *p;
466 
467 	p = malloc(sizeof(*p));
468 	if (!p)
469 		fatalx("can't allocate protocol struct for %s", name);
470 
471 	p->fd = fd;
472 	p->handler = handler;
473 	p->local = local;
474 	p->next = protocols;
475 	protocols = p;
476 }
477 
478 void
479 remove_protocol(struct protocol *proto)
480 {
481 	struct protocol *p, *next, *prev;
482 
483 	prev = NULL;
484 	for (p = protocols; p; p = next) {
485 		next = p->next;
486 		if (p == proto) {
487 			if (prev)
488 				prev->next = p->next;
489 			else
490 				protocols = p->next;
491 			free(p);
492 		}
493 	}
494 }
495