xref: /openbsd-src/usr.sbin/dhcrelay/dispatch.c (revision d59bb9942320b767f2a19aaa7690c8c6e30b724c)
1 /*	$OpenBSD: dispatch.c,v 1.19 2017/02/13 22:49:38 krw 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 
53 #include <errno.h>
54 #include <ifaddrs.h>
55 #include <limits.h>
56 #include <poll.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <syslog.h>
60 #include <time.h>
61 #include <unistd.h>
62 
63 #include "dhcp.h"
64 #include "dhcpd.h"
65 #include "log.h"
66 
67 struct protocol *protocols;
68 struct timeout *timeouts;
69 static struct timeout *free_timeouts;
70 static int interfaces_invalidated;
71 
72 void (*bootp_packet_handler)(struct interface_info *,
73     struct dhcp_packet *, int, struct packet_ctx *);
74 
75 static int interface_status(struct interface_info *ifinfo);
76 
77 struct interface_info *
78 get_interface(const char *ifname, void (*handler)(struct protocol *),
79     int isserver)
80 {
81 	struct interface_info		*iface;
82 	struct ifaddrs			*ifap, *ifa;
83 	struct sockaddr_in		*sin;
84 	int				 found = 0;
85 
86 	if ((iface = calloc(1, sizeof(*iface))) == NULL)
87 		fatalx("failed to allocate memory");
88 
89 	if (strlcpy(iface->name, ifname, sizeof(iface->name)) >=
90 	    sizeof(iface->name))
91 		fatalx("interface name '%s' too long", ifname);
92 
93 	if (getifaddrs(&ifap) != 0)
94 		fatalx("getifaddrs failed");
95 
96 	for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
97 		if ((ifa->ifa_flags & IFF_LOOPBACK) ||
98 		    (ifa->ifa_flags & IFF_POINTOPOINT) ||
99 		    (!(ifa->ifa_flags & IFF_UP)))
100 			continue;
101 
102 		if (strcmp(ifname, ifa->ifa_name))
103 			continue;
104 
105 		found = 1;
106 
107 		/*
108 		 * If we have the capability, extract link information
109 		 * and record it in a linked list.
110 		 */
111 		if (ifa->ifa_addr->sa_family == AF_LINK) {
112 			struct sockaddr_dl *foo =
113 			    (struct sockaddr_dl *)ifa->ifa_addr;
114 			struct if_data *ifi =
115 			    (struct if_data *)ifa->ifa_data;
116 
117 			iface->index = foo->sdl_index;
118 			iface->hw_address.hlen = foo->sdl_alen;
119 			if (ifi->ifi_type == IFT_ENC)
120 				iface->hw_address.htype = HTYPE_IPSEC_TUNNEL;
121 			else
122 				iface->hw_address.htype = HTYPE_ETHER; /*XXX*/
123 			memcpy(iface->hw_address.haddr,
124 			    LLADDR(foo), foo->sdl_alen);
125 		} else if (ifa->ifa_addr->sa_family == AF_INET) {
126 			/* We already have the primary address. */
127 			if (iface->primary_address.s_addr != 0)
128 				continue;
129 
130 			sin = (struct sockaddr_in *)ifa->ifa_addr;
131 			if (sin->sin_addr.s_addr == htonl(INADDR_LOOPBACK))
132 				continue;
133 
134 			iface->primary_address = sin->sin_addr;
135 		}
136 	}
137 
138 	freeifaddrs(ifap);
139 
140 	if (!found) {
141 		free(iface);
142 		return (NULL);
143 	}
144 
145 	if (strlcpy(iface->ifr.ifr_name, ifname,
146 	    sizeof(iface->ifr.ifr_name)) >= sizeof(iface->ifr.ifr_name))
147 		fatalx("interface name '%s' too long", ifname);
148 
149 	/* Register the interface... */
150 	if_register_receive(iface, isserver);
151 	if_register_send(iface);
152 	add_protocol(iface->name, iface->rfdesc, handler, iface);
153 
154 	return (iface);
155 }
156 
157 /*
158  * Wait for packets to come in using poll().  When a packet comes in,
159  * call receive_packet to receive the packet and possibly strip hardware
160  * addressing information from it, and then call through the
161  * bootp_packet_handler hook to try to do something with it.
162  */
163 void
164 dispatch(void)
165 {
166 	int count, i, to_msec, nfds = 0;
167 	struct protocol *l;
168 	struct pollfd *fds;
169 	time_t howlong;
170 
171 	nfds = 0;
172 	for (l = protocols; l; l = l->next)
173 		nfds++;
174 
175 	fds = calloc(nfds, sizeof(struct pollfd));
176 	if (fds == NULL)
177 		fatalx("Can't allocate poll structures.");
178 
179 	do {
180 		/*
181 		 * Call any expired timeouts, and then if there's still
182 		 * a timeout registered, time out the select call then.
183 		 */
184 another:
185 		if (timeouts) {
186 			if (timeouts->when <= cur_time) {
187 				struct timeout *t = timeouts;
188 
189 				timeouts = timeouts->next;
190 				(*(t->func))(t->what);
191 				t->next = free_timeouts;
192 				free_timeouts = t;
193 				goto another;
194 			}
195 
196 			/*
197 			 * Figure timeout in milliseconds, and check for
198 			 * potential overflow, so we can cram into an
199 			 * int for poll, while not polling with a
200 			 * negative timeout and blocking indefinitely.
201 			 */
202 			howlong = timeouts->when - cur_time;
203 			if (howlong > INT_MAX / 1000)
204 				howlong = INT_MAX / 1000;
205 			to_msec = howlong * 1000;
206 		} else
207 			to_msec = -1;
208 
209 		/* Set up the descriptors to be polled. */
210 		i = 0;
211 
212 		for (l = protocols; l; l = l->next) {
213 			struct interface_info *ip = l->local;
214 
215 			if (ip && (l->handler != got_one || !ip->dead)) {
216 				fds[i].fd = l->fd;
217 				fds[i].events = POLLIN;
218 				fds[i].revents = 0;
219 				i++;
220 			}
221 		}
222 
223 		if (i == 0)
224 			fatalx("No live interfaces to poll on - exiting.");
225 
226 		/* Wait for a packet or a timeout... XXX */
227 		count = poll(fds, nfds, to_msec);
228 
229 		/* Not likely to be transitory... */
230 		if (count == -1) {
231 			if (errno == EAGAIN || errno == EINTR) {
232 				time(&cur_time);
233 				continue;
234 			}
235 			else
236 				fatal("poll");
237 		}
238 
239 		/* Get the current time... */
240 		time(&cur_time);
241 
242 		i = 0;
243 		for (l = protocols; l; l = l->next) {
244 			struct interface_info *ip = l->local;
245 
246 			if ((fds[i].revents & (POLLIN | POLLHUP))) {
247 				fds[i].revents = 0;
248 				if (ip && (l->handler != got_one ||
249 				    !ip->dead))
250 					(*(l->handler))(l);
251 				if (interfaces_invalidated)
252 					break;
253 			}
254 			i++;
255 		}
256 		interfaces_invalidated = 0;
257 	} while (1);
258 }
259 
260 
261 void
262 got_one(struct protocol *l)
263 {
264 	struct packet_ctx pc;
265 	size_t result;
266 	union {
267 		/*
268 		 * Packet input buffer.  Must be as large as largest
269 		 * possible MTU.
270 		 */
271 		unsigned char packbuf[4095];
272 		struct dhcp_packet packet;
273 	} u;
274 	struct interface_info *ip = l->local;
275 
276 	memset(&pc, 0, sizeof(pc));
277 
278 	if ((result = receive_packet(ip, u.packbuf, sizeof(u), &pc)) == -1) {
279 		log_warn("receive_packet failed on %s", ip->name);
280 		ip->errors++;
281 		if ((!interface_status(ip)) ||
282 		    (ip->noifmedia && ip->errors > 20)) {
283 			/* our interface has gone away. */
284 			log_warnx("Interface %s no longer appears valid.",
285 			    ip->name);
286 			ip->dead = 1;
287 			interfaces_invalidated = 1;
288 			close(l->fd);
289 			remove_protocol(l);
290 			free(ip);
291 		}
292 		return;
293 	}
294 	if (result == 0)
295 		return;
296 
297 	if (bootp_packet_handler)
298 		(*bootp_packet_handler)(ip, &u.packet, result, &pc);
299 }
300 
301 int
302 interface_status(struct interface_info *ifinfo)
303 {
304 	char *ifname = ifinfo->name;
305 	int ifsock = ifinfo->rfdesc;
306 	struct ifreq ifr;
307 	struct ifmediareq ifmr;
308 
309 	/* get interface flags */
310 	memset(&ifr, 0, sizeof(ifr));
311 	strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
312 	if (ioctl(ifsock, SIOCGIFFLAGS, &ifr) == -1) {
313 		log_warn("ioctl(SIOCGIFFLAGS) on %s", ifname);
314 		goto inactive;
315 	}
316 	/*
317 	 * if one of UP and RUNNING flags is dropped,
318 	 * the interface is not active.
319 	 */
320 	if ((ifr.ifr_flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING)) {
321 		goto inactive;
322 	}
323 	/* Next, check carrier on the interface, if possible */
324 	if (ifinfo->noifmedia)
325 		goto active;
326 	memset(&ifmr, 0, sizeof(ifmr));
327 	strlcpy(ifmr.ifm_name, ifname, sizeof(ifmr.ifm_name));
328 	if (ioctl(ifsock, SIOCGIFMEDIA, (caddr_t)&ifmr) == -1) {
329 		if (errno != EINVAL) {
330 			log_debug("ioctl(SIOCGIFMEDIA) on %s", ifname);
331 			ifinfo->noifmedia = 1;
332 			goto active;
333 		}
334 		/*
335 		 * EINVAL (or ENOTTY) simply means that the interface
336 		 * does not support the SIOCGIFMEDIA ioctl. We regard it alive.
337 		 */
338 		ifinfo->noifmedia = 1;
339 		goto active;
340 	}
341 	if (ifmr.ifm_status & IFM_AVALID) {
342 		switch (ifmr.ifm_active & IFM_NMASK) {
343 		case IFM_ETHER:
344 			if (ifmr.ifm_status & IFM_ACTIVE)
345 				goto active;
346 			else
347 				goto inactive;
348 			break;
349 		default:
350 			goto inactive;
351 		}
352 	}
353 inactive:
354 	return (0);
355 active:
356 	return (1);
357 }
358 
359 /* Add a protocol to the list of protocols... */
360 void
361 add_protocol(char *name, int fd, void (*handler)(struct protocol *),
362     void *local)
363 {
364 	struct protocol *p;
365 
366 	p = malloc(sizeof(*p));
367 	if (!p)
368 		fatalx("can't allocate protocol struct for %s", name);
369 
370 	p->fd = fd;
371 	p->handler = handler;
372 	p->local = local;
373 	p->next = protocols;
374 	protocols = p;
375 }
376 
377 void
378 remove_protocol(struct protocol *proto)
379 {
380 	struct protocol *p, *next, *prev;
381 
382 	prev = NULL;
383 	for (p = protocols; p; p = next) {
384 		next = p->next;
385 		if (p == proto) {
386 			if (prev)
387 				prev->next = p->next;
388 			else
389 				protocols = p->next;
390 			free(p);
391 		}
392 	}
393 }
394