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