xref: /freebsd/usr.sbin/arp/arp.c (revision 734e82fe33aa764367791a7d603b383996c6b40b)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1984, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Sun Microsystems, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #if 0
36 #ifndef lint
37 static char const copyright[] =
38 "@(#) Copyright (c) 1984, 1993\n\
39 	The Regents of the University of California.  All rights reserved.\n";
40 #endif /* not lint */
41 
42 #ifndef lint
43 static char const sccsid[] = "@(#)from: arp.c	8.2 (Berkeley) 1/2/94";
44 #endif /* not lint */
45 #endif
46 #include <sys/cdefs.h>
47 /*
48  * arp - display, set, and delete arp table entries
49  */
50 
51 #include <sys/param.h>
52 #include <sys/file.h>
53 #include <sys/socket.h>
54 #include <sys/sockio.h>
55 #include <sys/sysctl.h>
56 #include <sys/ioctl.h>
57 #include <sys/time.h>
58 
59 #include <net/if.h>
60 #include <net/if_dl.h>
61 #include <net/if_types.h>
62 #include <net/route.h>
63 
64 #include <netinet/in.h>
65 #include <netinet/if_ether.h>
66 
67 #include <arpa/inet.h>
68 
69 #include <ctype.h>
70 #include <err.h>
71 #include <errno.h>
72 #include <netdb.h>
73 #include <nlist.h>
74 #include <paths.h>
75 #include <stdbool.h>
76 #include <stdio.h>
77 #include <stdlib.h>
78 #include <string.h>
79 #include <strings.h>
80 #include <unistd.h>
81 #include <ifaddrs.h>
82 #include <libxo/xo.h>
83 #include "arp.h"
84 
85 typedef void (action_fn)(struct sockaddr_dl *sdl, struct sockaddr_in *s_in,
86     struct rt_msghdr *rtm);
87 static void nuke_entries(uint32_t ifindex, struct in_addr addr);
88 static int print_entries(uint32_t ifindex, struct in_addr addr);
89 
90 static int delete(char *host);
91 static void usage(void) __dead2;
92 static int set(int argc, char **argv);
93 static int get(char *host);
94 static int file(char *name);
95 static struct rt_msghdr *rtmsg(int cmd,
96     struct sockaddr_in *dst, struct sockaddr_dl *sdl);
97 static int get_ether_addr(in_addr_t ipaddr, struct ether_addr *hwaddr);
98 static int set_rtsock(struct sockaddr_in *dst, struct sockaddr_dl *sdl_m,
99     char *host);
100 
101 static char *rifname;
102 
103 struct if_nameindex *ifnameindex;
104 
105 struct arp_opts opts = {};
106 
107 /* which function we're supposed to do */
108 #define F_GET		1
109 #define F_SET		2
110 #define F_FILESET	3
111 #define F_REPLACE	4
112 #define F_DELETE	5
113 
114 #define SETFUNC(f)	{ if (func) usage(); func = (f); }
115 
116 #define ARP_XO_VERSION	"1"
117 
118 int
119 main(int argc, char *argv[])
120 {
121 	int ch, func = 0;
122 	int rtn = 0;
123 
124 	argc = xo_parse_args(argc, argv);
125 	if (argc < 0)
126 		exit(1);
127 
128 	while ((ch = getopt(argc, argv, "andfsSi:")) != -1)
129 		switch(ch) {
130 		case 'a':
131 			opts.aflag = true;
132 			break;
133 		case 'd':
134 			SETFUNC(F_DELETE);
135 			break;
136 		case 'n':
137 			opts.nflag = true;
138 			break;
139 		case 'S':
140 			SETFUNC(F_REPLACE);
141 			break;
142 		case 's':
143 			SETFUNC(F_SET);
144 			break;
145 		case 'f' :
146 			SETFUNC(F_FILESET);
147 			break;
148 		case 'i':
149 			rifname = optarg;
150 			break;
151 		case '?':
152 		default:
153 			usage();
154 		}
155 	argc -= optind;
156 	argv += optind;
157 
158 	if (!func)
159 		func = F_GET;
160 	if (rifname) {
161 		if (func != F_GET && !(func == F_DELETE && opts.aflag))
162 			xo_errx(1, "-i not applicable to this operation");
163 		if (if_nametoindex(rifname) == 0) {
164 			if (errno == ENXIO)
165 				xo_errx(1, "interface %s does not exist",
166 				    rifname);
167 			else
168 				xo_err(1, "if_nametoindex(%s)", rifname);
169 		}
170 	}
171 	switch (func) {
172 	case F_GET:
173 		if (opts.aflag) {
174 			if (argc != 0)
175 				usage();
176 
177 			xo_set_version(ARP_XO_VERSION);
178 			xo_open_container("arp");
179 			xo_open_list("arp-cache");
180 
181 			struct in_addr all_addrs = {};
182 			print_entries(0, all_addrs);
183 
184 			xo_close_list("arp-cache");
185 			xo_close_container("arp");
186 			xo_finish();
187 		} else {
188 			if (argc != 1)
189 				usage();
190 			rtn = get(argv[0]);
191 		}
192 		break;
193 	case F_SET:
194 	case F_REPLACE:
195 		if (argc < 2 || argc > 6)
196 			usage();
197 		if (func == F_REPLACE)
198 			(void)delete(argv[0]);
199 		rtn = set(argc, argv) ? 1 : 0;
200 		break;
201 	case F_DELETE:
202 		if (opts.aflag) {
203 			if (argc != 0)
204 				usage();
205 			struct in_addr all_addrs = {};
206 			nuke_entries(0, all_addrs);
207 		} else {
208 			if (argc != 1)
209 				usage();
210 			rtn = delete(argv[0]);
211 		}
212 		break;
213 	case F_FILESET:
214 		if (argc != 1)
215 			usage();
216 		rtn = file(argv[0]);
217 		break;
218 	}
219 
220 	if (ifnameindex != NULL)
221 		if_freenameindex(ifnameindex);
222 
223 	return (rtn);
224 }
225 
226 /*
227  * Process a file to set standard arp entries
228  */
229 static int
230 file(char *name)
231 {
232 	FILE *fp;
233 	int i, retval;
234 	char line[100], arg[5][50], *args[5], *p;
235 
236 	if ((fp = fopen(name, "r")) == NULL)
237 		xo_err(1, "cannot open %s", name);
238 	args[0] = &arg[0][0];
239 	args[1] = &arg[1][0];
240 	args[2] = &arg[2][0];
241 	args[3] = &arg[3][0];
242 	args[4] = &arg[4][0];
243 	retval = 0;
244 	while(fgets(line, sizeof(line), fp) != NULL) {
245 		if ((p = strchr(line, '#')) != NULL)
246 			*p = '\0';
247 		for (p = line; isblank(*p); p++);
248 		if (*p == '\n' || *p == '\0')
249 			continue;
250 		i = sscanf(p, "%49s %49s %49s %49s %49s", arg[0], arg[1],
251 		    arg[2], arg[3], arg[4]);
252 		if (i < 2) {
253 			xo_warnx("bad line: %s", line);
254 			retval = 1;
255 			continue;
256 		}
257 		if (set(i, args))
258 			retval = 1;
259 	}
260 	fclose(fp);
261 	return (retval);
262 }
263 
264 /*
265  * Given a hostname, fills up a (static) struct sockaddr_in with
266  * the address of the host and returns a pointer to the
267  * structure.
268  */
269 struct sockaddr_in *
270 getaddr(char *host)
271 {
272 	struct hostent *hp;
273 	static struct sockaddr_in reply;
274 
275 	bzero(&reply, sizeof(reply));
276 	reply.sin_len = sizeof(reply);
277 	reply.sin_family = AF_INET;
278 	reply.sin_addr.s_addr = inet_addr(host);
279 	if (reply.sin_addr.s_addr == INADDR_NONE) {
280 		if (!(hp = gethostbyname(host))) {
281 			xo_warnx("%s: %s", host, hstrerror(h_errno));
282 			return (NULL);
283 		}
284 		bcopy((char *)hp->h_addr, (char *)&reply.sin_addr,
285 			sizeof reply.sin_addr);
286 	}
287 	return (&reply);
288 }
289 
290 int valid_type(int type);
291 /*
292  * Returns true if the type is a valid one for ARP.
293  */
294 int
295 valid_type(int type)
296 {
297 
298 	switch (type) {
299 	case IFT_ETHER:
300 	case IFT_FDDI:
301 	case IFT_IEEE1394:
302 	case IFT_INFINIBAND:
303 	case IFT_ISO88023:
304 	case IFT_ISO88024:
305 	case IFT_L2VLAN:
306 	case IFT_BRIDGE:
307 		return (1);
308 	default:
309 		return (0);
310 	}
311 }
312 
313 /*
314  * Set an individual arp entry
315  */
316 static int
317 set(int argc, char **argv)
318 {
319 	struct sockaddr_in *dst;	/* what are we looking for */
320 	struct ether_addr *ea;
321 	char *host = argv[0], *eaddr = argv[1];
322 	struct sockaddr_dl sdl_m;
323 
324 	argc -= 2;
325 	argv += 2;
326 
327 	bzero(&sdl_m, sizeof(sdl_m));
328 	sdl_m.sdl_len = sizeof(sdl_m);
329 	sdl_m.sdl_family = AF_LINK;
330 
331 	dst = getaddr(host);
332 	if (dst == NULL)
333 		return (1);
334 	while (argc-- > 0) {
335 		if (strcmp(argv[0], "temp") == 0) {
336 			int max_age;
337 			size_t len = sizeof(max_age);
338 
339 			if (sysctlbyname("net.link.ether.inet.max_age",
340 			    &max_age, &len, NULL, 0) != 0)
341 				xo_err(1, "sysctlbyname");
342 			opts.expire_time = max_age;
343 		} else if (strcmp(argv[0], "pub") == 0) {
344 			opts.flags |= RTF_ANNOUNCE;
345 			if (argc && strcmp(argv[1], "only") == 0) {
346 				/*
347 				 * Compatibility: in pre FreeBSD 8 times
348 				 * the "only" keyword used to mean that
349 				 * an ARP entry should be announced, but
350 				 * not installed into routing table.
351 				 */
352 				argc--; argv++;
353 			}
354 		} else if (strcmp(argv[0], "blackhole") == 0) {
355 			if (opts.flags & RTF_REJECT) {
356 				xo_errx(1, "Choose one of blackhole or reject, "
357 				    "not both.");
358 			}
359 			opts.flags |= RTF_BLACKHOLE;
360 		} else if (strcmp(argv[0], "reject") == 0) {
361 			if (opts.flags & RTF_BLACKHOLE) {
362 				xo_errx(1, "Choose one of blackhole or reject, "
363 				    "not both.");
364 			}
365 			opts.flags |= RTF_REJECT;
366 		} else {
367 			xo_warnx("Invalid parameter '%s'", argv[0]);
368 			usage();
369 		}
370 		argv++;
371 	}
372 	ea = (struct ether_addr *)LLADDR(&sdl_m);
373 	if ((opts.flags & RTF_ANNOUNCE) && !strcmp(eaddr, "auto")) {
374 		if (!get_ether_addr(dst->sin_addr.s_addr, ea)) {
375 			xo_warnx("no interface found for %s",
376 			       inet_ntoa(dst->sin_addr));
377 			return (1);
378 		}
379 		sdl_m.sdl_alen = ETHER_ADDR_LEN;
380 	} else {
381 		struct ether_addr *ea1 = ether_aton(eaddr);
382 
383 		if (ea1 == NULL) {
384 			xo_warnx("invalid Ethernet address '%s'", eaddr);
385 			return (1);
386 		} else {
387 			*ea = *ea1;
388 			sdl_m.sdl_alen = ETHER_ADDR_LEN;
389 		}
390 	}
391 #ifndef WITHOUT_NETLINK
392 	return (set_nl(0, dst, &sdl_m, host));
393 #else
394 	return (set_rtsock(dst, &sdl_m, host));
395 #endif
396 }
397 
398 #ifdef WITHOUT_NETLINK
399 static int
400 set_rtsock(struct sockaddr_in *dst, struct sockaddr_dl *sdl_m, char *host)
401 {
402 	struct sockaddr_in *addr;
403 	struct sockaddr_dl *sdl;
404 	struct rt_msghdr *rtm;
405 
406 	/*
407 	 * In the case a proxy-arp entry is being added for
408 	 * a remote end point, the RTF_ANNOUNCE flag in the
409 	 * RTM_GET command is an indication to the kernel
410 	 * routing code that the interface associated with
411 	 * the prefix route covering the local end of the
412 	 * PPP link should be returned, on which ARP applies.
413 	 */
414 	rtm = rtmsg(RTM_GET, dst, NULL);
415 	if (rtm == NULL) {
416 		xo_warn("%s", host);
417 		return (1);
418 	}
419 	addr = (struct sockaddr_in *)(rtm + 1);
420 	sdl = (struct sockaddr_dl *)(SA_SIZE(addr) + (char *)addr);
421 
422 	if ((sdl->sdl_family != AF_LINK) ||
423 	    (rtm->rtm_flags & RTF_GATEWAY) ||
424 	    !valid_type(sdl->sdl_type)) {
425 		xo_warnx("cannot intuit interface index and type for %s", host);
426 		return (1);
427 	}
428 	sdl_m->sdl_type = sdl->sdl_type;
429 	sdl_m->sdl_index = sdl->sdl_index;
430 	return (rtmsg(RTM_ADD, dst, sdl_m) == NULL);
431 }
432 #endif
433 
434 /*
435  * Display an individual arp entry
436  */
437 static int
438 get(char *host)
439 {
440 	struct sockaddr_in *addr;
441 	int found;
442 
443 	addr = getaddr(host);
444 	if (addr == NULL)
445 		return (1);
446 
447 	xo_set_version(ARP_XO_VERSION);
448 	xo_open_container("arp");
449 	xo_open_list("arp-cache");
450 
451 	found = print_entries(0, addr->sin_addr);
452 
453 	if (found == 0) {
454 		xo_emit("{d:hostname/%s} ({d:ip-address/%s}) -- no entry",
455 		    host, inet_ntoa(addr->sin_addr));
456 		if (rifname)
457 			xo_emit(" on {d:interface/%s}", rifname);
458 		xo_emit("\n");
459 	}
460 
461 	xo_close_list("arp-cache");
462 	xo_close_container("arp");
463 	xo_finish();
464 
465 	return (found == 0);
466 }
467 
468 /*
469  * Delete an arp entry
470  */
471 #ifdef WITHOUT_NETLINK
472 static int
473 delete_rtsock(char *host)
474 {
475 	struct sockaddr_in *addr, *dst;
476 	struct rt_msghdr *rtm;
477 	struct sockaddr_dl *sdl;
478 
479 	dst = getaddr(host);
480 	if (dst == NULL)
481 		return (1);
482 
483 	/*
484 	 * Perform a regular entry delete first.
485 	 */
486 	opts.flags &= ~RTF_ANNOUNCE;
487 
488 	for (;;) {	/* try twice */
489 		rtm = rtmsg(RTM_GET, dst, NULL);
490 		if (rtm == NULL) {
491 			xo_warn("%s", host);
492 			return (1);
493 		}
494 		addr = (struct sockaddr_in *)(rtm + 1);
495 		sdl = (struct sockaddr_dl *)(SA_SIZE(addr) + (char *)addr);
496 
497 		/*
498 		 * With the new L2/L3 restructure, the route
499 		 * returned is a prefix route. The important
500 		 * piece of information from the previous
501 		 * RTM_GET is the interface index. In the
502 		 * case of ECMP, the kernel will traverse
503 		 * the route group for the given entry.
504 		 */
505 		if (sdl->sdl_family == AF_LINK &&
506 		    !(rtm->rtm_flags & RTF_GATEWAY) &&
507 		    valid_type(sdl->sdl_type) ) {
508 			addr->sin_addr.s_addr = dst->sin_addr.s_addr;
509 			break;
510 		}
511 
512 		/*
513 		 * Regular entry delete failed, now check if there
514 		 * is a proxy-arp entry to remove.
515 		 */
516 		if (opts.flags & RTF_ANNOUNCE) {
517 			xo_warnx("delete: cannot locate %s", host);
518 			return (1);
519 		}
520 
521 		opts.flags |= RTF_ANNOUNCE;
522 	}
523 	rtm->rtm_flags |= RTF_LLDATA;
524 	if (rtmsg(RTM_DELETE, dst, NULL) != NULL) {
525 		printf("%s (%s) deleted\n", host, inet_ntoa(addr->sin_addr));
526 		return (0);
527 	}
528 	return (1);
529 }
530 #endif
531 
532 static int
533 delete(char *host)
534 {
535 #ifdef WITHOUT_NETLINK
536 	return (delete_rtsock(host));
537 #else
538 	return (delete_nl(0, host));
539 #endif
540 }
541 
542 
543 /*
544  * Search the arp table and do some action on matching entries
545  */
546 static int
547 search(u_long addr, action_fn *action)
548 {
549 	int mib[6];
550 	size_t needed;
551 	char *lim, *buf, *next;
552 	struct rt_msghdr *rtm;
553 	struct sockaddr_in *sin2;
554 	struct sockaddr_dl *sdl;
555 	char ifname[IF_NAMESIZE];
556 	int st, found_entry = 0;
557 
558 	mib[0] = CTL_NET;
559 	mib[1] = PF_ROUTE;
560 	mib[2] = 0;
561 	mib[3] = AF_INET;
562 	mib[4] = NET_RT_FLAGS;
563 #ifdef RTF_LLINFO
564 	mib[5] = RTF_LLINFO;
565 #else
566 	mib[5] = 0;
567 #endif
568 	if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
569 		xo_err(1, "route-sysctl-estimate");
570 	if (needed == 0)	/* empty table */
571 		return 0;
572 	buf = NULL;
573 	for (;;) {
574 		buf = reallocf(buf, needed);
575 		if (buf == NULL)
576 			xo_errx(1, "could not reallocate memory");
577 		st = sysctl(mib, 6, buf, &needed, NULL, 0);
578 		if (st == 0 || errno != ENOMEM)
579 			break;
580 		needed += needed / 8;
581 	}
582 	if (st == -1)
583 		xo_err(1, "actual retrieval of routing table");
584 	lim = buf + needed;
585 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
586 		rtm = (struct rt_msghdr *)next;
587 		sin2 = (struct sockaddr_in *)(rtm + 1);
588 		sdl = (struct sockaddr_dl *)((char *)sin2 + SA_SIZE(sin2));
589 		if (rifname && if_indextoname(sdl->sdl_index, ifname) &&
590 		    strcmp(ifname, rifname))
591 			continue;
592 		if (addr) {
593 			if (addr != sin2->sin_addr.s_addr)
594 				continue;
595 			found_entry = 1;
596 		}
597 		(*action)(sdl, sin2, rtm);
598 	}
599 	free(buf);
600 	return (found_entry);
601 }
602 
603 /*
604  * Display an arp entry
605  */
606 
607 static void
608 print_entry(struct sockaddr_dl *sdl,
609 	struct sockaddr_in *addr, struct rt_msghdr *rtm)
610 {
611 	const char *host;
612 	struct hostent *hp;
613 	struct if_nameindex *p;
614 
615 	if (ifnameindex == NULL)
616 		if ((ifnameindex = if_nameindex()) == NULL)
617 			xo_err(1, "cannot retrieve interface names");
618 
619 	xo_open_instance("arp-cache");
620 
621 	if (!opts.nflag)
622 		hp = gethostbyaddr((caddr_t)&(addr->sin_addr),
623 		    sizeof addr->sin_addr, AF_INET);
624 	else
625 		hp = 0;
626 	if (hp)
627 		host = hp->h_name;
628 	else {
629 		host = "?";
630 		if (h_errno == TRY_AGAIN)
631 			opts.nflag = true;
632 	}
633 	xo_emit("{:hostname/%s} ({:ip-address/%s}) at ", host,
634 	    inet_ntoa(addr->sin_addr));
635 	if (sdl->sdl_alen) {
636 		if ((sdl->sdl_type == IFT_ETHER ||
637 		    sdl->sdl_type == IFT_L2VLAN ||
638 		    sdl->sdl_type == IFT_BRIDGE) &&
639 		    sdl->sdl_alen == ETHER_ADDR_LEN)
640 			xo_emit("{:mac-address/%s}",
641 			    ether_ntoa((struct ether_addr *)LLADDR(sdl)));
642 		else {
643 			int n = sdl->sdl_nlen > 0 ? sdl->sdl_nlen + 1 : 0;
644 
645 			xo_emit("{:mac-address/%s}", link_ntoa(sdl) + n);
646 		}
647 	} else
648 		xo_emit("{d:/(incomplete)}{en:incomplete/true}");
649 
650 	for (p = ifnameindex; p && p->if_index && p->if_name; p++) {
651 		if (p->if_index == sdl->sdl_index) {
652 			xo_emit(" on {:interface/%s}", p->if_name);
653 			break;
654 		}
655 	}
656 
657 	if (rtm->rtm_rmx.rmx_expire == 0)
658 		xo_emit("{d:/ permanent}{en:permanent/true}");
659 	else {
660 		static struct timespec tp;
661 		time_t expire_time = 0;
662 
663 		if (tp.tv_sec == 0)
664 			clock_gettime(CLOCK_MONOTONIC, &tp);
665 		if ((expire_time = rtm->rtm_rmx.rmx_expire - tp.tv_sec) > 0)
666 			xo_emit(" expires in {:expires/%d} seconds",
667 			    (int)expire_time);
668 		else
669 			xo_emit("{d:/ expired}{en:expired/true}");
670 	}
671 
672 	if (rtm->rtm_flags & RTF_ANNOUNCE)
673 		xo_emit("{d:/ published}{en:published/true}");
674 
675 	switch(sdl->sdl_type) {
676 	case IFT_ETHER:
677 		xo_emit(" [{:type/ethernet}]");
678 		break;
679 	case IFT_FDDI:
680 		xo_emit(" [{:type/fddi}]");
681 		break;
682 	case IFT_ATM:
683 		xo_emit(" [{:type/atm}]");
684 		break;
685 	case IFT_L2VLAN:
686 		xo_emit(" [{:type/vlan}]");
687 		break;
688 	case IFT_IEEE1394:
689 		xo_emit(" [{:type/firewire}]");
690 		break;
691 	case IFT_BRIDGE:
692 		xo_emit(" [{:type/bridge}]");
693 		break;
694 	case IFT_INFINIBAND:
695 		xo_emit(" [{:type/infiniband}]");
696 		break;
697 	default:
698 		break;
699 	}
700 
701 	xo_emit("\n");
702 
703 	xo_close_instance("arp-cache");
704 }
705 
706 static int
707 print_entries(uint32_t ifindex, struct in_addr addr)
708 {
709 #ifndef WITHOUT_NETLINK
710 	return (print_entries_nl(ifindex, addr));
711 #else
712 	return (search(addr.s_addr, print_entry));
713 #endif
714 }
715 
716 
717 /*
718  * Nuke an arp entry
719  */
720 static void
721 nuke_entry(struct sockaddr_dl *sdl __unused,
722 	struct sockaddr_in *addr, struct rt_msghdr *rtm)
723 {
724 	char ip[20];
725 
726 	if (rtm->rtm_flags & RTF_PINNED)
727 		return;
728 
729 	snprintf(ip, sizeof(ip), "%s", inet_ntoa(addr->sin_addr));
730 	delete(ip);
731 }
732 
733 static void
734 nuke_entries(uint32_t ifindex, struct in_addr addr)
735 {
736 	search(addr.s_addr, nuke_entry);
737 }
738 
739 static void
740 usage(void)
741 {
742 	fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
743 	    "usage: arp [-n] [-i interface] hostname",
744 	    "       arp [-n] [-i interface] -a",
745 	    "       arp -d hostname [pub]",
746 	    "       arp -d [-i interface] -a",
747 	    "       arp -s hostname ether_addr [temp] [reject | blackhole] [pub [only]]",
748 	    "       arp -S hostname ether_addr [temp] [reject | blackhole] [pub [only]]",
749 	    "       arp -f filename");
750 	exit(1);
751 }
752 
753 static struct rt_msghdr *
754 rtmsg(int cmd, struct sockaddr_in *dst, struct sockaddr_dl *sdl)
755 {
756 	static int seq;
757 	int rlen;
758 	int l;
759 	static int s = -1;
760 	static pid_t pid;
761 
762 	static struct	{
763 		struct	rt_msghdr m_rtm;
764 		char	m_space[512];
765 	}	m_rtmsg;
766 
767 	struct rt_msghdr *rtm = &m_rtmsg.m_rtm;
768 	char *cp = m_rtmsg.m_space;
769 
770 	if (s < 0) {	/* first time: open socket, get pid */
771 		s = socket(PF_ROUTE, SOCK_RAW, 0);
772 		if (s < 0)
773 			xo_err(1, "socket");
774 		pid = getpid();
775 	}
776 
777 	errno = 0;
778 	/*
779 	 * XXX RTM_DELETE relies on a previous RTM_GET to fill the buffer
780 	 * appropriately.
781 	 */
782 	if (cmd == RTM_DELETE)
783 		goto doit;
784 	bzero((char *)&m_rtmsg, sizeof(m_rtmsg));
785 	rtm->rtm_flags = opts.flags;
786 	rtm->rtm_version = RTM_VERSION;
787 
788 	switch (cmd) {
789 	default:
790 		xo_errx(1, "internal wrong cmd");
791 	case RTM_ADD:
792 		rtm->rtm_addrs |= RTA_GATEWAY;
793 		if (opts.expire_time != 0) {
794 			struct timespec tp;
795 
796 			clock_gettime(CLOCK_MONOTONIC, &tp);
797 			rtm->rtm_rmx.rmx_expire = opts.expire_time + tp.tv_sec;
798 		}
799 		rtm->rtm_inits = RTV_EXPIRE;
800 		rtm->rtm_flags |= (RTF_HOST | RTF_STATIC | RTF_LLDATA);
801 		/* FALLTHROUGH */
802 	case RTM_GET:
803 		rtm->rtm_addrs |= RTA_DST;
804 	}
805 #define NEXTADDR(w, s)						\
806 	do {							\
807 		if ((s) != NULL && rtm->rtm_addrs & (w)) {	\
808 			bcopy((s), cp, sizeof(*(s)));		\
809 			cp += SA_SIZE(s);			\
810 		}						\
811 	} while (0)
812 
813 	NEXTADDR(RTA_DST, dst);
814 	NEXTADDR(RTA_GATEWAY, sdl);
815 
816 	rtm->rtm_msglen = cp - (char *)&m_rtmsg;
817 doit:
818 	l = rtm->rtm_msglen;
819 	rtm->rtm_seq = ++seq;
820 	rtm->rtm_type = cmd;
821 	if ((rlen = write(s, (char *)&m_rtmsg, l)) < 0) {
822 		if (errno != ESRCH || cmd != RTM_DELETE) {
823 			xo_warn("writing to routing socket");
824 			return (NULL);
825 		}
826 	}
827 	do {
828 		l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
829 	} while (l > 0 && (rtm->rtm_type != cmd || rtm->rtm_seq != seq ||
830 	    rtm->rtm_pid != pid));
831 	if (l < 0)
832 		xo_warn("read from routing socket");
833 	return (rtm);
834 }
835 
836 /*
837  * get_ether_addr - get the hardware address of an interface on the
838  * the same subnet as ipaddr.
839  */
840 static int
841 get_ether_addr(in_addr_t ipaddr, struct ether_addr *hwaddr)
842 {
843 	struct ifaddrs *ifa, *ifd, *ifas = NULL;
844 	in_addr_t ina, mask;
845 	struct sockaddr_dl *dla;
846 	int retval = 0;
847 
848 	/*
849 	 * Scan through looking for an interface with an Internet
850 	 * address on the same subnet as `ipaddr'.
851 	 */
852 	if (getifaddrs(&ifas) < 0) {
853 		xo_warnx("getifaddrs");
854 		goto done;
855 	}
856 
857 	for (ifa = ifas; ifa != NULL; ifa = ifa->ifa_next) {
858 		if (ifa->ifa_addr == NULL || ifa->ifa_netmask == NULL)
859 			continue;
860 		if (ifa->ifa_addr->sa_family != AF_INET)
861 			continue;
862 		/*
863 		 * Check that the interface is up,
864 		 * and not point-to-point or loopback.
865 		 */
866 		if ((ifa->ifa_flags &
867 		    (IFF_UP|IFF_BROADCAST|IFF_POINTOPOINT|
868 		    IFF_LOOPBACK|IFF_NOARP)) != (IFF_UP|IFF_BROADCAST))
869 			continue;
870 		/* Get its netmask and check that it's on the right subnet. */
871 		mask = ((struct sockaddr_in *)
872 			ifa->ifa_netmask)->sin_addr.s_addr;
873 		ina = ((struct sockaddr_in *)
874 			ifa->ifa_addr)->sin_addr.s_addr;
875 		if ((ipaddr & mask) == (ina & mask))
876 			break; /* ok, we got it! */
877 	}
878 	if (ifa == NULL)
879 		goto done;
880 
881 	/*
882 	 * Now scan through again looking for a link-level address
883 	 * for this interface.
884 	 */
885 	for (ifd = ifas; ifd != NULL; ifd = ifd->ifa_next) {
886 		if (ifd->ifa_addr == NULL)
887 			continue;
888 		if (strcmp(ifa->ifa_name, ifd->ifa_name) == 0 &&
889 		    ifd->ifa_addr->sa_family == AF_LINK)
890 			break;
891 	}
892 	if (ifd == NULL)
893 		goto done;
894 	/*
895 	 * Found the link-level address - copy it out
896 	 */
897 	dla = (struct sockaddr_dl *)ifd->ifa_addr;
898 	memcpy(hwaddr,  LLADDR(dla), dla->sdl_alen);
899 	printf("using interface %s for proxy with address %s\n", ifa->ifa_name,
900 	    ether_ntoa(hwaddr));
901 	retval = dla->sdl_alen;
902 done:
903 	if (ifas != NULL)
904 		freeifaddrs(ifas);
905 	return (retval);
906 }
907