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