1/*	$OpenBSD: dispatch.c,v 1.31 2004/09/21 04:07:03 david 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/cdefs.h>
43__FBSDID("$FreeBSD: stable/11/sbin/dhclient/dispatch.c 336440 2018-07-18 01:57:13Z eugen $");
44
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
58struct protocol *protocols;
59struct timeout *timeouts;
60static struct timeout *free_timeouts;
61static int interfaces_invalidated;
62void (*bootp_packet_handler)(struct interface_info *,
63    struct dhcp_packet *, int, unsigned int,
64    struct iaddr, struct hardware *);
65
66static int interface_status(struct interface_info *ifinfo);
67
68/*
69 * Use getifaddrs() to get a list of all the attached interfaces.  For
70 * each interface that's of type INET and not the loopback interface,
71 * register that interface with the network I/O software, figure out
72 * what subnet it's on, and add it to the list of interfaces.
73 */
74void
75discover_interfaces(struct interface_info *iface)
76{
77	struct ifaddrs *ifap, *ifa;
78	struct ifreq *tif;
79
80	if (getifaddrs(&ifap) != 0)
81		error("getifaddrs failed");
82
83	for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
84		if ((ifa->ifa_flags & IFF_LOOPBACK) ||
85		    (ifa->ifa_flags & IFF_POINTOPOINT) ||
86		    (!(ifa->ifa_flags & IFF_UP)))
87			continue;
88
89		if (strcmp(iface->name, ifa->ifa_name))
90			continue;
91
92		/*
93		 * If we have the capability, extract link information
94		 * and record it in a linked list.
95		 */
96		if (ifa->ifa_addr->sa_family == AF_LINK) {
97			struct sockaddr_dl *foo;
98
99			/*
100			 * The implementation of getifaddrs should guarantee
101			 * this alignment
102			 */
103			assert_aligned(ifa->ifa_addr,
104				       _Alignof(struct sockaddr_dl));
105#ifdef __clang__
106#pragma clang diagnostic push
107#pragma clang diagnostic ignored "-Wcast-align"
108#endif
109			foo = (struct sockaddr_dl *)ifa->ifa_addr;
110#ifdef __clang__
111#pragma clang diagnostic pop
112#endif
113
114			iface->index = foo->sdl_index;
115			iface->hw_address.hlen = foo->sdl_alen;
116			iface->hw_address.htype = HTYPE_ETHER; /* XXX */
117			memcpy(iface->hw_address.haddr,
118			    LLADDR(foo), foo->sdl_alen);
119		} else if (ifa->ifa_addr->sa_family == AF_INET) {
120			struct sockaddr_in foo;
121			struct iaddr addr;
122
123			memcpy(&foo, ifa->ifa_addr, sizeof(foo));
124			if (foo.sin_addr.s_addr == htonl(INADDR_LOOPBACK))
125				continue;
126			if (!iface->ifp) {
127				if ((tif = calloc(1, sizeof(struct ifreq)))
128				    == NULL)
129					error("no space to remember ifp");
130				strlcpy(tif->ifr_name, ifa->ifa_name, IFNAMSIZ);
131				memcpy(&tif->ifr_addr, ifa->ifa_addr,
132				    ifa->ifa_addr->sa_len);
133				iface->ifp = tif;
134				iface->primary_address = foo.sin_addr;
135			}
136			addr.len = 4;
137			memcpy(addr.iabuf, &foo.sin_addr.s_addr, addr.len);
138		}
139	}
140
141	if (!iface->ifp)
142		error("%s: not found", iface->name);
143
144	/* Register the interface... */
145	if_register_receive(iface);
146	if_register_send(iface);
147	add_protocol(iface->name, iface->rfdesc, got_one, iface);
148	freeifaddrs(ifap);
149}
150
151void
152reinitialize_interfaces(void)
153{
154	interfaces_invalidated = 1;
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 */
163void
164dispatch(void)
165{
166	int count, live_interfaces, i, to_msec, nfds = 0;
167	struct protocol *l;
168	struct pollfd *fds;
169	time_t howlong;
170
171	for (l = protocols; l; l = l->next)
172		nfds++;
173
174	fds = malloc(nfds * sizeof(struct pollfd));
175	if (fds == NULL)
176		error("Can't allocate poll structures.");
177
178	do {
179		/*
180		 * Call any expired timeouts, and then if there's still
181		 * a timeout registered, time out the select call then.
182		 */
183another:
184		if (timeouts) {
185			struct timeout *t;
186
187			if (timeouts->when <= cur_time) {
188				t = timeouts;
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		live_interfaces = 0;
211		for (i = 0, l = protocols; l; l = l->next) {
212			struct interface_info *ip = l->local;
213
214			if (ip == NULL || ip->dead)
215				continue;
216			fds[i].fd = l->fd;
217			fds[i].events = POLLIN;
218			fds[i].revents = 0;
219			i++;
220			if (l->handler == got_one)
221				live_interfaces++;
222		}
223		if (live_interfaces == 0)
224			error("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			} else
235				error("poll: %m");
236		}
237
238		/* Get the current time... */
239		time(&cur_time);
240
241		i = 0;
242		for (l = protocols; l; l = l->next) {
243			struct interface_info *ip;
244			ip = l->local;
245			if ((fds[i].revents & (POLLIN | POLLHUP))) {
246				fds[i].revents = 0;
247				if (ip && (l->handler != got_one ||
248				    !ip->dead))
249					(*(l->handler))(l);
250				if (interfaces_invalidated)
251					break;
252			}
253			i++;
254		}
255		interfaces_invalidated = 0;
256	} while (1);
257}
258
259
260void
261got_one(struct protocol *l)
262{
263	struct sockaddr_in from;
264	struct hardware hfrom;
265	struct iaddr ifrom;
266	ssize_t result;
267	union {
268		/*
269		 * Packet input buffer.  Must be as large as largest
270		 * possible MTU.
271		 */
272		unsigned char packbuf[4095];
273		struct dhcp_packet packet;
274	} u;
275	struct interface_info *ip = l->local;
276
277	if ((result = receive_packet(ip, u.packbuf, sizeof(u), &from,
278	    &hfrom)) == -1) {
279		warning("receive_packet failed on %s: %s", ip->name,
280		    strerror(errno));
281		ip->errors++;
282		if ((!interface_status(ip)) ||
283		    (ip->noifmedia && ip->errors > 20)) {
284			/* our interface has gone away. */
285			warning("Interface %s no longer appears valid.",
286			    ip->name);
287			ip->dead = 1;
288			interfaces_invalidated = 1;
289			close(l->fd);
290			remove_protocol(l);
291			free(ip);
292		}
293		return;
294	}
295	if (result == 0)
296		return;
297
298	if (bootp_packet_handler) {
299		ifrom.len = 4;
300		memcpy(ifrom.iabuf, &from.sin_addr, ifrom.len);
301
302		(*bootp_packet_handler)(ip, &u.packet, result,
303		    from.sin_port, ifrom, &hfrom);
304	}
305}
306
307int
308interface_status(struct interface_info *ifinfo)
309{
310	char *ifname = ifinfo->name;
311	int ifsock = ifinfo->rfdesc;
312	struct ifreq ifr;
313	struct ifmediareq ifmr;
314
315	/* get interface flags */
316	memset(&ifr, 0, sizeof(ifr));
317	strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
318	if (ioctl(ifsock, SIOCGIFFLAGS, &ifr) < 0) {
319		syslog(LOG_ERR, "ioctl(SIOCGIFFLAGS) on %s: %m", ifname);
320		goto inactive;
321	}
322
323	/*
324	 * if one of UP and RUNNING flags is dropped,
325	 * the interface is not active.
326	 */
327	if ((ifr.ifr_flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
328		goto inactive;
329
330	/* Next, check carrier on the interface, if possible */
331	if (ifinfo->noifmedia)
332		goto active;
333	memset(&ifmr, 0, sizeof(ifmr));
334	strlcpy(ifmr.ifm_name, ifname, sizeof(ifmr.ifm_name));
335	if (ioctl(ifsock, SIOCGIFMEDIA, (caddr_t)&ifmr) < 0) {
336		if (errno != EINVAL) {
337			syslog(LOG_DEBUG, "ioctl(SIOCGIFMEDIA) on %s: %m",
338			    ifname);
339
340			ifinfo->noifmedia = 1;
341			goto active;
342		}
343		/*
344		 * EINVAL (or ENOTTY) simply means that the interface
345		 * does not support the SIOCGIFMEDIA ioctl. We regard it alive.
346		 */
347		ifinfo->noifmedia = 1;
348		goto active;
349	}
350	if (ifmr.ifm_status & IFM_AVALID) {
351		switch (ifmr.ifm_active & IFM_NMASK) {
352		case IFM_ETHER:
353		case IFM_IEEE80211:
354			if (ifmr.ifm_status & IFM_ACTIVE)
355				goto active;
356			else
357				goto inactive;
358			break;
359		default:
360			goto inactive;
361		}
362	}
363inactive:
364	return (0);
365active:
366	return (1);
367}
368
369void
370add_timeout(time_t when, void (*where)(void *), void *what)
371{
372	struct timeout *t, *q;
373
374	/* See if this timeout supersedes an existing timeout. */
375	t = NULL;
376	for (q = timeouts; q; q = q->next) {
377		if (q->func == where && q->what == what) {
378			if (t)
379				t->next = q->next;
380			else
381				timeouts = q->next;
382			break;
383		}
384		t = q;
385	}
386
387	/* If we didn't supersede a timeout, allocate a timeout
388	   structure now. */
389	if (!q) {
390		if (free_timeouts) {
391			q = free_timeouts;
392			free_timeouts = q->next;
393			q->func = where;
394			q->what = what;
395		} else {
396			q = malloc(sizeof(struct timeout));
397			if (!q)
398				error("Can't allocate timeout structure!");
399			q->func = where;
400			q->what = what;
401		}
402	}
403
404	q->when = when;
405
406	/* Now sort this timeout into the timeout list. */
407
408	/* Beginning of list? */
409	if (!timeouts || timeouts->when > q->when) {
410		q->next = timeouts;
411		timeouts = q;
412		return;
413	}
414
415	/* Middle of list? */
416	for (t = timeouts; t->next; t = t->next) {
417		if (t->next->when > q->when) {
418			q->next = t->next;
419			t->next = q;
420			return;
421		}
422	}
423
424	/* End of list. */
425	t->next = q;
426	q->next = NULL;
427}
428
429void
430cancel_timeout(void (*where)(void *), void *what)
431{
432	struct timeout *t, *q;
433
434	/* Look for this timeout on the list, and unlink it if we find it. */
435	t = NULL;
436	for (q = timeouts; q; q = q->next) {
437		if (q->func == where && q->what == what) {
438			if (t)
439				t->next = q->next;
440			else
441				timeouts = q->next;
442			break;
443		}
444		t = q;
445	}
446
447	/* If we found the timeout, put it on the free list. */
448	if (q) {
449		q->next = free_timeouts;
450		free_timeouts = q;
451	}
452}
453
454/* Add a protocol to the list of protocols... */
455void
456add_protocol(const char *name, int fd, void (*handler)(struct protocol *),
457    void *local)
458{
459	struct protocol *p;
460
461	p = malloc(sizeof(*p));
462	if (!p)
463		error("can't allocate protocol struct for %s", name);
464
465	p->fd = fd;
466	p->handler = handler;
467	p->local = local;
468	p->next = protocols;
469	protocols = p;
470}
471
472void
473remove_protocol(struct protocol *proto)
474{
475	struct protocol *p, *next;
476
477	for (p = protocols; p; p = next) {
478		next = p->next;
479		if (p == proto) {
480			protocols = p->next;
481			free(p);
482		}
483	}
484}
485
486int
487interface_link_status(char *ifname)
488{
489	struct ifmediareq ifmr;
490	int sock;
491
492	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
493		error("Can't create socket");
494
495	memset(&ifmr, 0, sizeof(ifmr));
496	strlcpy(ifmr.ifm_name, ifname, sizeof(ifmr.ifm_name));
497	if (ioctl(sock, SIOCGIFMEDIA, (caddr_t)&ifmr) == -1) {
498		/* EINVAL -> link state unknown. treat as active */
499		if (errno != EINVAL)
500			syslog(LOG_DEBUG, "ioctl(SIOCGIFMEDIA) on %s: %m",
501			    ifname);
502		close(sock);
503		return (1);
504	}
505	close(sock);
506
507	if (ifmr.ifm_status & IFM_AVALID) {
508		switch (ifmr.ifm_active & IFM_NMASK) {
509		case IFM_ETHER:
510		case IFM_IEEE80211:
511			if (ifmr.ifm_status & IFM_ACTIVE)
512				return (1);
513			else
514				return (0);
515		}
516	}
517	return (1);
518}
519
520void
521interface_set_mtu_unpriv(int privfd, u_int16_t mtu)
522{
523	struct imsg_hdr hdr;
524	struct buf *buf;
525	int errs = 0;
526
527	hdr.code = IMSG_SET_INTERFACE_MTU;
528	hdr.len = sizeof(hdr) +
529		sizeof(u_int16_t);
530
531	if ((buf = buf_open(hdr.len)) == NULL)
532		error("buf_open: %m");
533
534	errs += buf_add(buf, &hdr, sizeof(hdr));
535	errs += buf_add(buf, &mtu, sizeof(mtu));
536	if (errs)
537		error("buf_add: %m");
538
539	if (buf_close(privfd, buf) == -1)
540		error("buf_close: %m");
541}
542
543void
544interface_set_mtu_priv(char *ifname, u_int16_t mtu)
545{
546	struct ifreq ifr;
547	int sock;
548	u_int16_t old_mtu;
549
550	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
551		error("Can't create socket");
552
553	memset(&ifr, 0, sizeof(ifr));
554	old_mtu = 0;
555
556	strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
557
558	if (ioctl(sock, SIOCGIFMTU, (caddr_t)&ifr) == -1)
559		warning("SIOCGIFMTU failed (%s): %s", ifname,
560			strerror(errno));
561	else
562		old_mtu = ifr.ifr_mtu;
563
564	if (mtu != old_mtu) {
565		ifr.ifr_mtu = mtu;
566
567		if (ioctl(sock, SIOCSIFMTU, &ifr) == -1)
568			warning("SIOCSIFMTU failed (%d): %s", mtu,
569				strerror(errno));
570	}
571
572	close(sock);
573}
574