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