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