xref: /openbsd-src/usr.sbin/arp/arp.c (revision ae3cb403620ab940fbaabb3055fac045a63d56b7)
1 /*	$OpenBSD: arp.c,v 1.80 2017/12/23 20:53:07 cheloha Exp $ */
2 /*	$NetBSD: arp.c,v 1.12 1995/04/24 13:25:18 cgd Exp $ */
3 
4 /*
5  * Copyright (c) 1984, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Sun Microsystems, Inc.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 /*
37  * arp - display, set, delete arp table entries and wake up hosts.
38  */
39 
40 #include <sys/file.h>
41 #include <sys/socket.h>
42 #include <sys/sysctl.h>
43 #include <sys/ioctl.h>
44 #include <net/bpf.h>
45 #include <net/if.h>
46 #include <net/if_dl.h>
47 #include <net/if_types.h>
48 #include <net/route.h>
49 #include <netinet/in.h>
50 #include <netinet/if_ether.h>
51 #include <arpa/inet.h>
52 
53 #include <netdb.h>
54 #include <errno.h>
55 #include <err.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <time.h>
60 #include <paths.h>
61 #include <unistd.h>
62 #include <limits.h>
63 #include <ifaddrs.h>
64 
65 void dump(void);
66 int delete(const char *);
67 void search(in_addr_t addr, void (*action)(struct sockaddr_dl *sdl,
68 	struct sockaddr_inarp *sin, struct rt_msghdr *rtm));
69 void print_entry(struct sockaddr_dl *sdl,
70 	struct sockaddr_inarp *sin, struct rt_msghdr *rtm);
71 void nuke_entry(struct sockaddr_dl *sdl,
72 	struct sockaddr_inarp *sin, struct rt_msghdr *rtm);
73 static char *ether_str(struct sockaddr_dl *);
74 int wake(const char *ether_addr, const char *iface);
75 int file(char *);
76 int get(const char *);
77 int getinetaddr(const char *, struct in_addr *);
78 void getsocket(void);
79 int rtget(struct sockaddr_inarp **, struct sockaddr_dl **);
80 int rtmsg(int);
81 int set(int, char **);
82 void usage(void);
83 static char *sec2str(time_t);
84 
85 static pid_t pid;
86 static int replace;	/* replace entries when adding */
87 static int nflag;	/* no reverse dns lookups */
88 static int aflag;	/* do it for all entries */
89 static int rtsock = -1;
90 static int rdomain;
91 
92 extern int h_errno;
93 
94 /* ROUNDUP() is nasty, but it is identical to what's in the kernel. */
95 #define ROUNDUP(a)					\
96 	((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
97 
98 /* which function we're supposed to do */
99 #define F_GET		1
100 #define F_SET		2
101 #define F_FILESET	3
102 #define F_DELETE	4
103 #define F_WAKE		5
104 
105 int
106 main(int argc, char *argv[])
107 {
108 	int		 ch, func = 0, error = 0;
109 	const char	*errstr;
110 
111 	pid = getpid();
112 	opterr = 0;
113 	rdomain = getrtable();
114 	while ((ch = getopt(argc, argv, "andsFfV:W")) != -1) {
115 		switch (ch) {
116 		case 'a':
117 			aflag = 1;
118 			break;
119 		case 'n':
120 			nflag = 1;
121 			break;
122 		case 'd':
123 			if (func)
124 				usage();
125 			func = F_DELETE;
126 			break;
127 		case 's':
128 			if (func)
129 				usage();
130 			func = F_SET;
131 			break;
132 		case 'F':
133 			replace = 1;
134 			break;
135 		case 'f':
136 			if (func)
137 				usage();
138 			func = F_FILESET;
139 			break;
140 		case 'V':
141 			rdomain = strtonum(optarg, 0, RT_TABLEID_MAX, &errstr);
142 			if (errstr != NULL) {
143 				warn("bad rdomain: %s", errstr);
144 				usage();
145 			}
146 			break;
147 		case 'W':
148 			if (func)
149 				usage();
150 			func = F_WAKE;
151 			break;
152 		default:
153 			usage();
154 			break;
155 		}
156 	}
157 	argc -= optind;
158 	argv += optind;
159 
160 	if (!func)
161 		func = F_GET;
162 
163 	switch (func) {
164 	case F_GET:
165 		if (aflag && argc == 0)
166 			dump();
167 		else if (!aflag && argc == 1)
168 			error = get(argv[0]);
169 		else
170 			usage();
171 		break;
172 	case F_SET:
173 		if (argc < 2 || argc > 5)
174 			usage();
175 		if (replace)
176 			delete(argv[0]);
177 		error = set(argc, argv) ? 1 : 0;
178 		break;
179 	case F_DELETE:
180 		if (aflag && argc == 0)
181 			search(0, nuke_entry);
182 		else if (!aflag && argc == 1)
183 			error = delete(argv[0]);
184 		else
185 			usage();
186 		break;
187 	case F_FILESET:
188 		if (argc != 1)
189 			usage();
190 		error = file(argv[0]);
191 		break;
192 	case F_WAKE:
193 		if (aflag || nflag || replace || rdomain > 0)
194 			usage();
195 		if (argc == 1)
196 			error = wake(argv[0], NULL);
197 		else if (argc == 2)
198 			error = wake(argv[0], argv[1]);
199 		else
200 			usage();
201 		break;
202 	}
203 	return (error);
204 }
205 
206 /*
207  * Process a file to set standard arp entries
208  */
209 int
210 file(char *name)
211 {
212 	char	 line[100], arg[5][50], *args[5];
213 	int	 i, retval;
214 	FILE	*fp;
215 
216 	if ((fp = fopen(name, "r")) == NULL)
217 		err(1, "cannot open %s", name);
218 	args[0] = &arg[0][0];
219 	args[1] = &arg[1][0];
220 	args[2] = &arg[2][0];
221 	args[3] = &arg[3][0];
222 	args[4] = &arg[4][0];
223 	retval = 0;
224 	while (fgets(line, sizeof(line), fp) != NULL) {
225 		i = sscanf(line, "%49s %49s %49s %49s %49s", arg[0], arg[1],
226 		    arg[2], arg[3], arg[4]);
227 		if (i < 2) {
228 			warnx("bad line: %s", line);
229 			retval = 1;
230 			continue;
231 		}
232 		if (replace)
233 			delete(arg[0]);
234 		if (set(i, args))
235 			retval = 1;
236 	}
237 	fclose(fp);
238 	return (retval);
239 }
240 
241 void
242 getsocket(void)
243 {
244 	socklen_t len = sizeof(rdomain);
245 
246 	if (rtsock >= 0)
247 		return;
248 	rtsock = socket(PF_ROUTE, SOCK_RAW, 0);
249 	if (rtsock < 0)
250 		err(1, "routing socket");
251 	if (setsockopt(rtsock, PF_ROUTE, ROUTE_TABLEFILTER, &rdomain, len) < 0)
252 		err(1, "ROUTE_TABLEFILTER");
253 
254 	if (pledge("stdio dns", NULL) == -1)
255 		err(1, "pledge");
256 }
257 
258 struct sockaddr_in	so_mask = { 8, 0, 0, { 0xffffffff } };
259 struct sockaddr_inarp	blank_sin = { sizeof(blank_sin), AF_INET }, sin_m;
260 struct sockaddr_dl	blank_sdl = { sizeof(blank_sdl), AF_LINK }, sdl_m;
261 struct sockaddr_dl	ifp_m = { sizeof(&ifp_m), AF_LINK };
262 time_t			expire_time;
263 int			flags, export_only, doing_proxy, found_entry;
264 struct	{
265 	struct rt_msghdr	m_rtm;
266 	char			m_space[512];
267 }	m_rtmsg;
268 
269 /*
270  * Set an individual arp entry
271  */
272 int
273 set(int argc, char *argv[])
274 {
275 	struct sockaddr_inarp *sin;
276 	struct sockaddr_dl *sdl;
277 	struct rt_msghdr *rtm;
278 	char *eaddr = argv[1], *host = argv[0];
279 	struct ether_addr *ea;
280 
281 	sin = &sin_m;
282 	rtm = &(m_rtmsg.m_rtm);
283 
284 	getsocket();
285 	argc -= 2;
286 	argv += 2;
287 	sdl_m = blank_sdl;		/* struct copy */
288 	sin_m = blank_sin;		/* struct copy */
289 	if (getinetaddr(host, &sin->sin_addr) == -1)
290 		return (1);
291 	ea = ether_aton(eaddr);
292 	if (ea == NULL)
293 		errx(1, "invalid ethernet address: %s", eaddr);
294 	memcpy(LLADDR(&sdl_m), ea, sizeof(*ea));
295 	sdl_m.sdl_alen = 6;
296 	expire_time = 0;
297 	doing_proxy = flags = export_only = 0;
298 	while (argc-- > 0) {
299 		if (strncmp(argv[0], "temp", 4) == 0) {
300 			expire_time = time(NULL) + 20 * 60;
301 			if (flags & RTF_PERMANENT_ARP) {
302 				/* temp or permanent, not both */
303 				usage();
304 				return (0);
305 			}
306 		} else if (strncmp(argv[0], "pub", 3) == 0) {
307 			flags |= RTF_ANNOUNCE;
308 			doing_proxy = SIN_PROXY;
309 		} else if (strncmp(argv[0], "permanent", 9) == 0) {
310 			flags |= RTF_PERMANENT_ARP;
311 			if (expire_time != 0) {
312 				/* temp or permanent, not both */
313 				usage();
314 				return (0);
315 			}
316 		}
317 
318 		argv++;
319 	}
320 
321 tryagain:
322 	if (rtget(&sin, &sdl)) {
323 		warn("%s", host);
324 		return (1);
325 	}
326 
327 	if (sin->sin_addr.s_addr == sin_m.sin_addr.s_addr) {
328 		if (sdl->sdl_family == AF_LINK &&
329 		    (rtm->rtm_flags & RTF_LLINFO) &&
330 		    !(rtm->rtm_flags & RTF_GATEWAY))
331 			switch (sdl->sdl_type) {
332 			case IFT_ETHER:
333 			case IFT_FDDI:
334 			case IFT_ISO88023:
335 			case IFT_ISO88024:
336 			case IFT_ISO88025:
337 			case IFT_CARP:
338 				goto overwrite;
339 			}
340 
341 		if (doing_proxy == 0) {
342 			printf("set: can only proxy for %s\n", host);
343 			return (1);
344 		}
345 		if (sin_m.sin_other & SIN_PROXY) {
346 			printf("set: proxy entry exists for non 802 device\n");
347 			return (1);
348 		}
349 		sin_m.sin_other = SIN_PROXY;
350 		export_only = 1;
351 		goto tryagain;
352 	}
353 
354 overwrite:
355 	if (sdl->sdl_family != AF_LINK) {
356 		printf("cannot intuit interface index and type for %s\n", host);
357 		return (1);
358 	}
359 	sdl_m.sdl_type = sdl->sdl_type;
360 	sdl_m.sdl_index = sdl->sdl_index;
361 	return (rtmsg(RTM_ADD));
362 }
363 
364 #define W_ADDR	36
365 #define W_LL	17
366 #define W_IF	7
367 
368 /*
369  * Display an individual arp entry
370  */
371 int
372 get(const char *host)
373 {
374 	struct sockaddr_inarp *sin;
375 
376 	sin = &sin_m;
377 	sin_m = blank_sin;		/* struct copy */
378 	if (getinetaddr(host, &sin->sin_addr) == -1)
379 		exit(1);
380 
381 	printf("%-*.*s %-*.*s %*.*s %-9.9s %5s\n",
382 	    W_ADDR, W_ADDR, "Host", W_LL, W_LL, "Ethernet Address",
383 	    W_IF, W_IF, "Netif", "Expire", "Flags");
384 
385 	search(sin->sin_addr.s_addr, print_entry);
386 	if (found_entry == 0) {
387 		printf("%-*.*s no entry\n", W_ADDR, W_ADDR,
388 		    inet_ntoa(sin->sin_addr));
389 		return (1);
390 	}
391 	return (0);
392 }
393 
394 /*
395  * Delete an arp entry
396  */
397 int
398 delete(const char *host)
399 {
400 	struct sockaddr_inarp *sin;
401 	struct rt_msghdr *rtm;
402 	struct sockaddr_dl *sdl;
403 
404 	sin = &sin_m;
405 	rtm = &m_rtmsg.m_rtm;
406 
407 	getsocket();
408 	sin_m = blank_sin;		/* struct copy */
409 	if (getinetaddr(host, &sin->sin_addr) == -1)
410 		return (1);
411 tryagain:
412 	if (rtget(&sin, &sdl)) {
413 		warn("%s", host);
414 		return (1);
415 	}
416 	if (sin->sin_addr.s_addr == sin_m.sin_addr.s_addr) {
417 		if (sdl->sdl_family == AF_LINK && rtm->rtm_flags & RTF_LLINFO) {
418 			if (rtm->rtm_flags & RTF_LOCAL)
419 				return (0);
420 		    	if (!(rtm->rtm_flags & RTF_GATEWAY))
421 				switch (sdl->sdl_type) {
422 				case IFT_ETHER:
423 				case IFT_FDDI:
424 				case IFT_ISO88023:
425 				case IFT_ISO88024:
426 				case IFT_ISO88025:
427 				case IFT_CARP:
428 					goto delete;
429 				}
430 		}
431 	}
432 
433 	if (sin_m.sin_other & SIN_PROXY) {
434 		warnx("delete: can't locate %s", host);
435 		return (1);
436 	} else {
437 		sin_m.sin_other = SIN_PROXY;
438 		goto tryagain;
439 	}
440 delete:
441 	if (sdl->sdl_family != AF_LINK) {
442 		printf("cannot locate %s\n", host);
443 		return (1);
444 	}
445 	if (rtmsg(RTM_DELETE))
446 		return (1);
447 	printf("%s (%s) deleted\n", host, inet_ntoa(sin->sin_addr));
448 	return (0);
449 }
450 
451 /*
452  * Search the entire arp table, and do some action on matching entries.
453  */
454 void
455 search(in_addr_t addr, void (*action)(struct sockaddr_dl *sdl,
456     struct sockaddr_inarp *sin, struct rt_msghdr *rtm))
457 {
458 	int mib[7];
459 	size_t needed;
460 	char *lim, *buf = NULL, *next;
461 	struct rt_msghdr *rtm;
462 	struct sockaddr_inarp *sin;
463 	struct sockaddr_dl *sdl;
464 
465 	mib[0] = CTL_NET;
466 	mib[1] = PF_ROUTE;
467 	mib[2] = 0;
468 	mib[3] = AF_INET;
469 	mib[4] = NET_RT_FLAGS;
470 	mib[5] = RTF_LLINFO;
471 	mib[6] = rdomain;
472 	while (1) {
473 		if (sysctl(mib, 7, NULL, &needed, NULL, 0) == -1)
474 			err(1, "route-sysctl-estimate");
475 		if (needed == 0)
476 			return;
477 		if ((buf = realloc(buf, needed)) == NULL)
478 			err(1, "malloc");
479 		if (sysctl(mib, 7, buf, &needed, NULL, 0) == -1) {
480 			if (errno == ENOMEM)
481 				continue;
482 			err(1, "actual retrieval of routing table");
483 		}
484 		lim = buf + needed;
485 		break;
486 	}
487 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
488 		rtm = (struct rt_msghdr *)next;
489 		if (rtm->rtm_version != RTM_VERSION)
490 			continue;
491 		sin = (struct sockaddr_inarp *)(next + rtm->rtm_hdrlen);
492 		sdl = (struct sockaddr_dl *)(sin + 1);
493 		if (addr) {
494 			if (addr != sin->sin_addr.s_addr)
495 				continue;
496 			found_entry = 1;
497 		}
498 		(*action)(sdl, sin, rtm);
499 	}
500 	free(buf);
501 }
502 
503 /*
504  * Dump the entire ARP table
505  */
506 void
507 dump(void)
508 {
509 	printf("%-*.*s %-*.*s %*.*s %-9.9s %5s\n",
510 	    W_ADDR, W_ADDR, "Host", W_LL, W_LL, "Ethernet Address",
511 	    W_IF, W_IF, "Netif", "Expire", "Flags");
512 
513 	search(0, print_entry);
514 }
515 
516 /*
517  * Display an arp entry
518  */
519 void
520 print_entry(struct sockaddr_dl *sdl, struct sockaddr_inarp *sin,
521     struct rt_msghdr *rtm)
522 {
523 	char ifix_buf[IFNAMSIZ], *ifname, *host;
524 	struct hostent *hp = NULL;
525 	int addrwidth, llwidth, ifwidth ;
526 	time_t now;
527 
528 	now = time(NULL);
529 
530 	if (nflag == 0)
531 		hp = gethostbyaddr((caddr_t)&(sin->sin_addr),
532 		    sizeof(sin->sin_addr), AF_INET);
533 	if (hp)
534 		host = hp->h_name;
535 	else
536 		host = inet_ntoa(sin->sin_addr);
537 
538 	addrwidth = strlen(host);
539 	if (addrwidth < W_ADDR)
540 		addrwidth = W_ADDR;
541 	llwidth = strlen(ether_str(sdl));
542 	if (W_ADDR + W_LL - addrwidth > llwidth)
543 		llwidth = W_ADDR + W_LL - addrwidth;
544 	ifname = if_indextoname(sdl->sdl_index, ifix_buf);
545 	if (!ifname)
546 		ifname = "?";
547 	ifwidth = strlen(ifname);
548 	if (W_ADDR + W_LL + W_IF - addrwidth - llwidth > ifwidth)
549 		ifwidth = W_ADDR + W_LL + W_IF - addrwidth - llwidth;
550 
551 	printf("%-*.*s %-*.*s %*.*s", addrwidth, addrwidth, host,
552 	    llwidth, llwidth, ether_str(sdl), ifwidth, ifwidth, ifname);
553 
554 	if (rtm->rtm_flags & (RTF_PERMANENT_ARP|RTF_LOCAL))
555 		printf(" %-9.9s", "permanent");
556 	else if (rtm->rtm_rmx.rmx_expire == 0)
557 		printf(" %-9.9s", "static");
558 	else if (rtm->rtm_rmx.rmx_expire > now)
559 		printf(" %-9.9s",
560 		    sec2str(rtm->rtm_rmx.rmx_expire - now));
561 	else
562 		printf(" %-9.9s", "expired");
563 
564 	printf(" %s%s\n",
565 	    (rtm->rtm_flags & RTF_LOCAL) ? "l" : "",
566 	    (rtm->rtm_flags & RTF_ANNOUNCE) ? "p" : "");
567 }
568 
569 /*
570  * Nuke an arp entry
571  */
572 void
573 nuke_entry(struct sockaddr_dl *sdl, struct sockaddr_inarp *sin,
574     struct rt_msghdr *rtm)
575 {
576 	char ip[20];
577 
578 	strlcpy(ip, inet_ntoa(sin->sin_addr), sizeof(ip));
579 	delete(ip);
580 }
581 
582 static char *
583 ether_str(struct sockaddr_dl *sdl)
584 {
585 	static char hbuf[NI_MAXHOST];
586 	u_char *cp;
587 
588 	if (sdl->sdl_alen) {
589 		cp = (u_char *)LLADDR(sdl);
590 		snprintf(hbuf, sizeof(hbuf), "%02x:%02x:%02x:%02x:%02x:%02x",
591 		    cp[0], cp[1], cp[2], cp[3], cp[4], cp[5]);
592 	} else
593 		snprintf(hbuf, sizeof(hbuf), "(incomplete)");
594 
595 	return(hbuf);
596 }
597 
598 void
599 usage(void)
600 {
601 	fprintf(stderr, "usage: arp [-adn] [-V rdomain] hostname\n");
602 	fprintf(stderr, "       arp [-F] [-f file] [-V rdomain] "
603 	    "-s hostname ether_addr\n"
604 	    "           [temp | permanent] [pub]\n");
605 	fprintf(stderr, "       arp -W ether_addr [iface]\n");
606 	exit(1);
607 }
608 
609 int
610 rtmsg(int cmd)
611 {
612 	static int seq;
613 	struct rt_msghdr *rtm;
614 	char *cp;
615 	int l;
616 
617 	rtm = &m_rtmsg.m_rtm;
618 	cp = m_rtmsg.m_space;
619 	errno = 0;
620 
621 	if (cmd == RTM_DELETE)
622 		goto doit;
623 	memset(&m_rtmsg, 0, sizeof(m_rtmsg));
624 	rtm->rtm_flags = flags;
625 	rtm->rtm_version = RTM_VERSION;
626 	rtm->rtm_hdrlen = sizeof(*rtm);
627 	rtm->rtm_tableid = rdomain;
628 
629 	switch (cmd) {
630 	default:
631 		errx(1, "internal wrong cmd");
632 		/*NOTREACHED*/
633 	case RTM_ADD:
634 		rtm->rtm_addrs |= RTA_GATEWAY;
635 		rtm->rtm_rmx.rmx_expire = expire_time;
636 		rtm->rtm_inits = RTV_EXPIRE;
637 		rtm->rtm_flags |= (RTF_HOST | RTF_STATIC);
638 		sin_m.sin_other = 0;
639 		if (doing_proxy) {
640 			if (export_only)
641 				sin_m.sin_other = SIN_PROXY;
642 			else {
643 				rtm->rtm_addrs |= RTA_NETMASK;
644 				rtm->rtm_flags &= ~RTF_HOST;
645 			}
646 		}
647 		/* FALLTHROUGH */
648 	case RTM_GET:
649 		rtm->rtm_addrs |= (RTA_DST | RTA_IFP);
650 	}
651 
652 #define NEXTADDR(w, s)					\
653 	if (rtm->rtm_addrs & (w)) {			\
654 		memcpy(cp, &s, sizeof(s));		\
655 		cp += ROUNDUP(sizeof(s));		\
656 	}
657 
658 	NEXTADDR(RTA_DST, sin_m);
659 	NEXTADDR(RTA_GATEWAY, sdl_m);
660 	NEXTADDR(RTA_NETMASK, so_mask);
661 	NEXTADDR(RTA_IFP, ifp_m);
662 
663 	rtm->rtm_msglen = cp - (char *)&m_rtmsg;
664 doit:
665 	l = rtm->rtm_msglen;
666 	rtm->rtm_seq = ++seq;
667 	rtm->rtm_type = cmd;
668 	if (write(rtsock, (char *)&m_rtmsg, l) < 0)
669 		if (errno != ESRCH || cmd != RTM_DELETE) {
670 			warn("writing to routing socket");
671 			return (-1);
672 		}
673 
674 	do {
675 		l = read(rtsock, (char *)&m_rtmsg, sizeof(m_rtmsg));
676 	} while (l > 0 && (rtm->rtm_version != RTM_VERSION ||
677 	    rtm->rtm_seq != seq || rtm->rtm_pid != pid));
678 
679 	if (l < 0)
680 		warn("read from routing socket");
681 	return (0);
682 }
683 
684 int
685 rtget(struct sockaddr_inarp **sinp, struct sockaddr_dl **sdlp)
686 {
687 	struct rt_msghdr *rtm = &(m_rtmsg.m_rtm);
688 	struct sockaddr_inarp *sin = NULL;
689 	struct sockaddr_dl *sdl = NULL;
690 	struct sockaddr *sa;
691 	char *cp;
692 	unsigned int i;
693 
694 	if (rtmsg(RTM_GET) < 0)
695 		return (1);
696 
697 	if (rtm->rtm_addrs) {
698 		cp = ((char *)rtm + rtm->rtm_hdrlen);
699 		for (i = 1; i; i <<= 1) {
700 			if (i & rtm->rtm_addrs) {
701 				sa = (struct sockaddr *)cp;
702 				switch (i) {
703 				case RTA_DST:
704 					sin = (struct sockaddr_inarp *)sa;
705 					break;
706 				case RTA_IFP:
707 					sdl = (struct sockaddr_dl *)sa;
708 					break;
709 				default:
710 					break;
711 				}
712 				cp += ROUNDUP(sa->sa_len);
713 			}
714 		}
715 	}
716 
717 	if (sin == NULL || sdl == NULL)
718 		return (1);
719 
720 	*sinp = sin;
721 	*sdlp = sdl;
722 
723 	return (0);
724 }
725 
726 int
727 getinetaddr(const char *host, struct in_addr *inap)
728 {
729 	struct hostent *hp;
730 
731 	if (inet_aton(host, inap) == 1)
732 		return (0);
733 	if ((hp = gethostbyname(host)) == NULL) {
734 		warnx("%s: %s", host, hstrerror(h_errno));
735 		return (-1);
736 	}
737 	memcpy(inap, hp->h_addr, sizeof(*inap));
738 	return (0);
739 }
740 
741 static char *
742 sec2str(time_t total)
743 {
744 	static char result[256];
745 	int days, hours, mins, secs;
746 	int first = 1;
747 	char *p = result;
748 	char *ep = &result[sizeof(result)];
749 	int n;
750 
751 	days = total / 3600 / 24;
752 	hours = (total / 3600) % 24;
753 	mins = (total / 60) % 60;
754 	secs = total % 60;
755 
756 	if (days) {
757 		first = 0;
758 		n = snprintf(p, ep - p, "%dd", days);
759 		if (n < 0 || n >= ep - p)
760 			return "?";
761 		p += n;
762 	}
763 	if (!first || hours) {
764 		first = 0;
765 		n = snprintf(p, ep - p, "%dh", hours);
766 		if (n < 0 || n >= ep - p)
767 			return "?";
768 		p += n;
769 	}
770 	if (!first || mins) {
771 		first = 0;
772 		n = snprintf(p, ep - p, "%dm", mins);
773 		if (n < 0 || n >= ep - p)
774 			return "?";
775 		p += n;
776 	}
777 	snprintf(p, ep - p, "%ds", secs);
778 
779 	return(result);
780 }
781 
782 /*
783  * Copyright (c) 2011 Jasper Lievisse Adriaanse <jasper@openbsd.org>
784  * Copyright (C) 2006,2007,2008,2009 Marc Balmer <mbalmer@openbsd.org>
785  * Copyright (C) 2000 Eugene M. Kim.  All rights reserved.
786  *
787  * Redistribution and use in source and binary forms, with or without
788  * modification, are permitted provided that the following conditions
789  * are met:
790  *
791  * 1. Redistributions of source code must retain the above copyright
792  *    notice, this list of conditions and the following disclaimer.
793  * 2. Author's name may not be used endorse or promote products derived
794  *    from this software without specific prior written permission.
795  *
796  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
797  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
798  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
799  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
800  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
801  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
802  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
803  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
804  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
805  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
806  * POSSIBILITY OF SUCH DAMAGE.
807  */
808 
809 int	do_wakeup(const char *, const char *, int);
810 int	bind_if_to_bpf(const char *, int);
811 int	get_ether(const char *, struct ether_addr *);
812 int	send_frame(int, const struct ether_addr *);
813 
814 int
815 wake(const char *ether_addr, const char *iface)
816 {
817 	struct ifaddrs		*ifa, *ifap;
818 	char			*pname = NULL;
819 	int			 bpf;
820 
821 	if ((bpf = open("/dev/bpf", O_RDWR)) == -1)
822 		err(1, "Failed to bind to bpf");
823 
824 	if (iface == NULL) {
825 		if (getifaddrs(&ifa) == -1)
826 			errx(1, "Could not get interface addresses.");
827 
828 		for (ifap = ifa; ifap != NULL; ifap = ifap->ifa_next){
829 			if (pname && !strcmp(pname, ifap->ifa_name))
830 				continue;
831 			pname = ifap->ifa_name;
832 
833 			/*
834 			 * We're only interested in sending the WoL frame on
835 			 * certain interfaces. So skip the loopback interface,
836 			 * as well as point-to-point and down interfaces.
837 			 */
838 			if ((ifap->ifa_flags & IFF_LOOPBACK) ||
839 			    (ifap->ifa_flags & IFF_POINTOPOINT) ||
840 			    (!(ifap->ifa_flags & IFF_UP)) ||
841 			    (!(ifap->ifa_flags & IFF_BROADCAST)))
842 				continue;
843 
844 			do_wakeup(ether_addr, ifap->ifa_name, bpf);
845 		}
846 		freeifaddrs(ifa);
847 	} else {
848 		do_wakeup(ether_addr, iface, bpf);
849 	}
850 
851 	(void)close(bpf);
852 
853 	return 0;
854 }
855 
856 int
857 do_wakeup(const char *eaddr, const char *iface, int bpf)
858 {
859 	struct ether_addr	 macaddr;
860 
861 	if (get_ether(eaddr, &macaddr) != 0)
862 		errx(1, "Invalid Ethernet address: %s", eaddr);
863 	if (bind_if_to_bpf(iface, bpf) != 0)
864 		errx(1, "Failed to bind %s to bpf.", iface);
865 	if (send_frame(bpf, &macaddr) != 0)
866 		errx(1, "Failed to send WoL frame on %s", iface);
867 	return 0;
868 }
869 
870 int
871 bind_if_to_bpf(const char *ifname, int bpf)
872 {
873 	struct ifreq ifr;
874 	u_int dlt;
875 
876 	if (strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)) >=
877 	    sizeof(ifr.ifr_name))
878 		return -1;
879 	if (ioctl(bpf, BIOCSETIF, &ifr) == -1)
880 		return -1;
881 	if (ioctl(bpf, BIOCGDLT, &dlt) == -1)
882 		return -1;
883 	if (dlt != DLT_EN10MB)
884 		return -1;
885 	return 0;
886 }
887 
888 int
889 get_ether(const char *text, struct ether_addr *addr)
890 {
891 	struct ether_addr *eaddr;
892 
893 	eaddr = ether_aton(text);
894 
895 	if (eaddr == NULL) {
896 		if (ether_hostton(text, addr))
897 			return -1;
898 	} else {
899 		*addr = *eaddr;
900 		return 0;
901 	}
902 
903 	return 0;
904 }
905 
906 #define SYNC_LEN 6
907 #define DESTADDR_COUNT 16
908 
909 int
910 send_frame(int bpf, const struct ether_addr *addr)
911 {
912 	struct {
913 		struct ether_header hdr;
914 		u_char sync[SYNC_LEN];
915 		u_char dest[ETHER_ADDR_LEN * DESTADDR_COUNT];
916 	} __packed pkt;
917 	u_char *p;
918 	int i;
919 
920 	(void)memset(&pkt, 0, sizeof(pkt));
921 	(void)memset(&pkt.hdr.ether_dhost, 0xff, sizeof(pkt.hdr.ether_dhost));
922 	pkt.hdr.ether_type = htons(0);
923 	(void)memset(pkt.sync, 0xff, SYNC_LEN);
924 	for (p = pkt.dest, i = 0; i < DESTADDR_COUNT; p += ETHER_ADDR_LEN, i++)
925 		bcopy(addr->ether_addr_octet, p, ETHER_ADDR_LEN);
926 	if (write(bpf, &pkt, sizeof(pkt)) != sizeof(pkt))
927 		return (errno);
928 	return (0);
929 }
930