1/*	$NetBSD: arp.c,v 1.48 2009/04/02 21:02:06 christos Exp $ */
2
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#include <sys/cdefs.h>
36#ifndef lint
37__COPYRIGHT("@(#) Copyright (c) 1984, 1993\
38 The Regents of the University of California.  All rights reserved.");
39#endif /* not lint */
40
41#ifndef lint
42#if 0
43static char sccsid[] = "@(#)arp.c	8.3 (Berkeley) 4/28/95";
44#else
45__RCSID("$NetBSD: arp.c,v 1.48 2009/04/02 21:02:06 christos Exp $");
46#endif
47#endif /* not lint */
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/sysctl.h>
57#include <sys/ioctl.h>
58
59#include <net/if.h>
60#include <net/if_dl.h>
61#include <net/if_ether.h>
62#include <net/if_types.h>
63#include <net/route.h>
64#include <netinet/in.h>
65#include <netinet/if_inarp.h>
66#include <arpa/inet.h>
67
68#include <err.h>
69#include <errno.h>
70#include <netdb.h>
71#include <nlist.h>
72#include <paths.h>
73#include <stdio.h>
74#include <stdlib.h>
75#include <string.h>
76#include <unistd.h>
77#include <ifaddrs.h>
78
79static int is_llinfo(const struct sockaddr_dl *, int);
80static int delete(const char *, const char *);
81static void dump(uint32_t);
82static void delete_all(void);
83static void sdl_print(const struct sockaddr_dl *);
84static int getifname(u_int16_t, char *, size_t);
85static int atosdl(const char *s, struct sockaddr_dl *sdl);
86static int file(const char *);
87static void get(const char *);
88static int getinetaddr(const char *, struct in_addr *);
89static void getsocket(void);
90static int rtmsg(int);
91static int set(int, char **);
92static void usage(void) __dead;
93
94static pid_t pid;
95static int aflag, nflag, vflag;
96static int s = -1;
97static struct ifaddrs* ifaddrs = NULL;
98static struct sockaddr_in so_mask = {
99	.sin_len = 8,
100	.sin_addr = {
101		.s_addr = 0xffffffff
102	}
103};
104static struct sockaddr_inarp blank_sin = {
105	.sin_len = sizeof(blank_sin),
106	.sin_family = AF_INET
107};
108static struct sockaddr_inarp sin_m;
109static struct sockaddr_dl blank_sdl = {
110	.sdl_len = sizeof(blank_sdl),
111	.sdl_family = AF_LINK
112};
113static struct sockaddr_dl sdl_m;
114
115static int expire_time, flags, export_only, doing_proxy, found_entry;
116static struct {
117	struct	rt_msghdr m_rtm;
118	char	m_space[512];
119} m_rtmsg;
120
121int
122main(int argc, char **argv)
123{
124	int ch;
125	int op = 0;
126
127	setprogname(argv[0]);
128
129	pid = getpid();
130
131	while ((ch = getopt(argc, argv, "andsfv")) != -1)
132		switch((char)ch) {
133		case 'a':
134			aflag = 1;
135			break;
136		case 'd':
137		case 's':
138		case 'f':
139			if (op)
140				usage();
141			op = ch;
142			break;
143		case 'n':
144			nflag = 1;
145			break;
146		case 'v':
147			vflag = 1;
148			break;
149		default:
150			usage();
151		}
152	argc -= optind;
153	argv += optind;
154
155	if (!op && aflag)
156		op = 'a';
157
158	switch((char)op) {
159	case 'a':
160		dump(0);
161		break;
162	case 'd':
163		if (aflag && argc == 0)
164			delete_all();
165		else {
166			if (aflag || argc < 1 || argc > 2)
167				usage();
168			(void)delete(argv[0], argv[1]);
169		}
170		break;
171	case 's':
172		if (argc < 2 || argc > 5)
173			usage();
174		return (set(argc, argv) ? 1 : 0);
175	case 'f':
176		if (argc != 1)
177			usage();
178		return (file(argv[0]));
179	default:
180		if (argc != 1)
181			usage();
182		get(argv[0]);
183		break;
184	}
185	return (0);
186}
187
188/*
189 * Process a file to set standard arp entries
190 */
191static int
192file(const char *name)
193{
194	char *line, *argv[5];
195	int i, retval;
196	FILE *fp;
197
198	if (!strcmp(name, "-")) {
199		fp = stdin;
200	} else {
201		fp = fopen(name, "r");
202		if (fp == NULL) {
203			err(1, "Cannot open %s", name);
204		}
205	}
206	retval = 0;
207	for (; (line = fparseln(fp, NULL, NULL, NULL, 0)) != NULL; free(line)) {
208		char **ap, *inputstring;
209
210		inputstring = line;
211		for (ap = argv; ap < &argv[sizeof(argv) / sizeof(argv[0])] &&
212		    (*ap = stresep(&inputstring, " \t", '\\')) != NULL;) {
213		       if (**ap != '\0')
214				ap++;
215		}
216		i = ap - argv;
217		if (i < 2) {
218			warnx("bad line: %s", line);
219			retval = 1;
220			continue;
221		}
222		if (set(i, argv))
223			retval = 1;
224	}
225	if (fp != stdin)
226		(void)fclose(fp);
227	return retval;
228}
229
230static void
231getsocket(void)
232{
233	if (s >= 0)
234		return;
235	s = socket(PF_ROUTE, SOCK_RAW, 0);
236	if (s < 0)
237		err(1, "socket");
238}
239
240/*
241 * Set an individual arp entry
242 */
243static int
244set(int argc, char **argv)
245{
246	struct sockaddr_inarp *sina;
247	struct sockaddr_dl *sdl;
248	struct rt_msghdr *rtm;
249	char *host = argv[0], *eaddr;
250	int rval;
251
252	sina = &sin_m;
253	rtm = &(m_rtmsg.m_rtm);
254	eaddr = argv[1];
255
256	getsocket();
257	argc -= 2;
258	argv += 2;
259	sdl_m = blank_sdl;		/* struct copy */
260	sin_m = blank_sin;		/* struct copy */
261	if (getinetaddr(host, &sina->sin_addr) == -1)
262		return (1);
263	if (atosdl(eaddr, &sdl_m))
264		warnx("invalid link-level address '%s'", eaddr);
265	doing_proxy = flags = export_only = expire_time = 0;
266	while (argc-- > 0) {
267		if (strncmp(argv[0], "temp", 4) == 0) {
268			struct timeval timev;
269			(void)gettimeofday(&timev, 0);
270			expire_time = timev.tv_sec + 20 * 60;
271		}
272		else if (strncmp(argv[0], "pub", 3) == 0) {
273			flags |= RTF_ANNOUNCE;
274			doing_proxy = SIN_PROXY;
275			if (argc && strncmp(argv[1], "pro", 3) == 0) {
276			        export_only = 1;
277			        argc--; argv++;
278			}
279		} else if (strncmp(argv[0], "trail", 5) == 0) {
280			warnx("%s: Sending trailers is no longer supported",
281			    host);
282		}
283		argv++;
284	}
285tryagain:
286	if (rtmsg(RTM_GET) < 0) {
287		warn("%s", host);
288		return (1);
289	}
290	sina = (struct sockaddr_inarp *)(void *)(rtm + 1);
291	sdl = (struct sockaddr_dl *)(void *)(RT_ROUNDUP(sina->sin_len) +
292	    (char *)(void *)sina);
293	if (sina->sin_addr.s_addr == sin_m.sin_addr.s_addr) {
294		if (is_llinfo(sdl, rtm->rtm_flags))
295			goto overwrite;
296		if (doing_proxy == 0) {
297			warnx("set: can only proxy for %s", host);
298			return (1);
299		}
300		if (sin_m.sin_other & SIN_PROXY) {
301			warnx("set: proxy entry exists for non 802 device");
302			return (1);
303		}
304		sin_m.sin_other = SIN_PROXY;
305		export_only = 1;
306		goto tryagain;
307	}
308overwrite:
309	if (sdl->sdl_family != AF_LINK) {
310		warnx("cannot intuit interface index and type for %s",
311		    host);
312		return (1);
313	}
314	sdl_m.sdl_type = sdl->sdl_type;
315	sdl_m.sdl_index = sdl->sdl_index;
316	rval = rtmsg(RTM_ADD);
317	if (vflag)
318		(void)printf("%s (%s) added\n", host, eaddr);
319	return (rval);
320}
321
322/*
323 * Display an individual arp entry
324 */
325static void
326get(const char *host)
327{
328	struct sockaddr_inarp *sina;
329
330	sina = &sin_m;
331	sin_m = blank_sin;		/* struct copy */
332	if (getinetaddr(host, &sina->sin_addr) == -1)
333		exit(1);
334	dump(sina->sin_addr.s_addr);
335	if (found_entry == 0)
336		errx(1, "%s (%s) -- no entry", host, inet_ntoa(sina->sin_addr));
337}
338
339
340static int
341is_llinfo(const struct sockaddr_dl *sdl, int rtflags)
342{
343	if (sdl->sdl_family != AF_LINK ||
344	    (rtflags & (RTF_LLINFO|RTF_GATEWAY)) != RTF_LLINFO)
345		return 0;
346
347	switch (sdl->sdl_type) {
348	case IFT_ETHER:
349	case IFT_FDDI:
350	case IFT_ISO88023:
351	case IFT_ISO88024:
352	case IFT_ISO88025:
353	case IFT_ARCNET:
354		return 1;
355	default:
356		return 0;
357	}
358}
359
360/*
361 * Delete an arp entry
362 */
363int
364delete(const char *host, const char *info)
365{
366	struct sockaddr_inarp *sina;
367	struct rt_msghdr *rtm;
368	struct sockaddr_dl *sdl;
369
370	sina = &sin_m;
371	rtm = &m_rtmsg.m_rtm;
372
373	getsocket();
374	sin_m = blank_sin;		/* struct copy */
375	if (info && strncmp(info, "pro", 3) == 0)
376		 sina->sin_other = SIN_PROXY;
377	if (getinetaddr(host, &sina->sin_addr) == -1)
378		return (1);
379tryagain:
380	if (rtmsg(RTM_GET) < 0) {
381		warn("%s", host);
382		return (1);
383	}
384	sina = (struct sockaddr_inarp *)(void *)(rtm + 1);
385	sdl = (struct sockaddr_dl *)(void *)(RT_ROUNDUP(sina->sin_len) +
386	    (char *)(void *)sina);
387	if (sina->sin_addr.s_addr == sin_m.sin_addr.s_addr &&
388	    is_llinfo(sdl, rtm->rtm_flags))
389		goto delete;
390	if (sin_m.sin_other & SIN_PROXY) {
391		warnx("delete: can't locate %s", host);
392		return (1);
393	} else {
394		sin_m.sin_other = SIN_PROXY;
395		goto tryagain;
396	}
397delete:
398	if (sdl->sdl_family != AF_LINK) {
399		(void)warnx("cannot locate %s", host);
400		return (1);
401	}
402	if (rtmsg(RTM_DELETE))
403		return (1);
404	if (vflag)
405		(void)printf("%s (%s) deleted\n", host,
406		    inet_ntoa(sina->sin_addr));
407	return (0);
408}
409
410/*
411 * Dump the entire arp table
412 */
413void
414dump(uint32_t addr)
415{
416	int mib[6];
417	size_t needed;
418	char ifname[IFNAMSIZ];
419	char *lim, *buf, *next;
420        const char *host;
421	struct rt_msghdr *rtm;
422	struct sockaddr_inarp *sina;
423	struct sockaddr_dl *sdl;
424	struct hostent *hp;
425
426	mib[0] = CTL_NET;
427	mib[1] = PF_ROUTE;
428	mib[2] = 0;
429	mib[3] = AF_INET;
430	mib[4] = NET_RT_FLAGS;
431	mib[5] = RTF_LLINFO;
432	if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
433		err(1, "route-sysctl-estimate");
434	if (needed == 0)
435		return;
436	if ((buf = malloc(needed)) == NULL)
437		err(1, "malloc");
438	if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
439		err(1, "actual retrieval of routing table");
440	lim = buf + needed;
441	for (next = buf; next < lim; next += rtm->rtm_msglen) {
442		rtm = (struct rt_msghdr *)(void *)next;
443		sina = (struct sockaddr_inarp *)(void *)(rtm + 1);
444		sdl = (struct sockaddr_dl *)(void *)
445		    (RT_ROUNDUP(sina->sin_len) + (char *)(void *)sina);
446		if (addr) {
447			if (addr != sina->sin_addr.s_addr)
448				continue;
449			found_entry = 1;
450		}
451		if (nflag == 0)
452			hp = gethostbyaddr((const char *)(void *)
453			    &(sina->sin_addr),
454			    sizeof sina->sin_addr, AF_INET);
455		else
456			hp = NULL;
457
458		host = hp ? hp->h_name : "?";
459
460		(void)printf("%s (%s) at ", host, inet_ntoa(sina->sin_addr));
461		if (sdl->sdl_alen)
462			sdl_print(sdl);
463		else
464			(void)printf("(incomplete)");
465
466		if (sdl->sdl_index) {
467			if (getifname(sdl->sdl_index, ifname, sizeof(ifname)) == 0)
468				(void)printf(" on %s", ifname);
469		}
470
471		if (rtm->rtm_rmx.rmx_expire == 0)
472			(void)printf(" permanent");
473		if (sina->sin_other & SIN_PROXY)
474			(void)printf(" published (proxy only)");
475		if (rtm->rtm_addrs & RTA_NETMASK) {
476			sina = (struct sockaddr_inarp *)(void *)
477			    (RT_ROUNDUP(sdl->sdl_len) + (char *)(void *)sdl);
478			if (sina->sin_addr.s_addr == 0xffffffff)
479				(void)printf(" published");
480			if (sina->sin_len != 8)
481				(void)printf("(weird)");
482		}
483		(void)printf("\n");
484	}
485	free(buf);
486}
487
488/*
489 * Delete the entire arp table
490 */
491void
492delete_all(void)
493{
494	int mib[6];
495	size_t needed;
496	char addr[sizeof("000.000.000.000\0")];
497	char *lim, *buf, *next;
498	struct rt_msghdr *rtm;
499	struct sockaddr_inarp *sina;
500
501	mib[0] = CTL_NET;
502	mib[1] = PF_ROUTE;
503	mib[2] = 0;
504	mib[3] = AF_INET;
505	mib[4] = NET_RT_FLAGS;
506	mib[5] = RTF_LLINFO;
507	if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
508		err(1, "route-sysctl-estimate");
509	if (needed == 0)
510		return;
511	if ((buf = malloc(needed)) == NULL)
512		err(1, "malloc");
513	if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
514		err(1, "actual retrieval of routing table");
515	lim = buf + needed;
516	for (next = buf; next < lim; next += rtm->rtm_msglen) {
517		rtm = (struct rt_msghdr *)(void *)next;
518		sina = (struct sockaddr_inarp *)(void *)(rtm + 1);
519		(void)snprintf(addr, sizeof(addr), "%s",
520		    inet_ntoa(sina->sin_addr));
521		(void)delete(addr, NULL);
522	}
523	free(buf);
524}
525
526void
527sdl_print(const struct sockaddr_dl *sdl)
528{
529	char hbuf[NI_MAXHOST];
530
531	if (getnameinfo((const struct sockaddr *)(const void *)sdl,
532	    (socklen_t)sdl->sdl_len,
533	    hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0)
534		(void)printf("<invalid>");
535	else
536		(void)printf("%s", hbuf);
537}
538
539static int
540atosdl(const char *ss, struct sockaddr_dl *sdl)
541{
542	int i;
543	unsigned long b;
544	char *endp;
545	char *p;
546	char *t, *r;
547
548	p = LLADDR(sdl);
549	endp = ((char *)(void *)sdl) + sdl->sdl_len;
550	i = 0;
551
552	b = strtoul(ss, &t, 16);
553	if (b > 255 || t == ss)
554		return 1;
555
556	*p++ = (char)b;
557	++i;
558	while ((p < endp) && (*t++ == ':')) {
559		b = strtoul(t, &r, 16);
560		if (b > 255 || r == t)
561			break;
562		*p++ = (char)b;
563		++i;
564		t = r;
565	}
566	sdl->sdl_alen = i;
567
568	return 0;
569}
570
571static void
572usage(void)
573{
574	const char *progname;
575
576	progname = getprogname();
577	(void)fprintf(stderr, "Usage: %s [-n] hostname\n", progname);
578	(void)fprintf(stderr, "	      %s [-nv] -a\n", progname);
579	(void)fprintf(stderr, "	      %s [-v] -d [-a|hostname [pub [proxy]]]\n",
580	    progname);
581	(void)fprintf(stderr, "       %s -s hostname ether_addr [temp] [pub [proxy]]\n",
582	    progname);
583	(void)fprintf(stderr, "       %s -f filename\n", progname);
584	exit(1);
585}
586
587static int
588rtmsg(int cmd)
589{
590	static int seq;
591	struct rt_msghdr *rtm;
592	char *cp;
593	int l;
594
595	rtm = &m_rtmsg.m_rtm;
596	cp = m_rtmsg.m_space;
597	errno = 0;
598
599	if (cmd == RTM_DELETE)
600		goto doit;
601	(void)memset(&m_rtmsg, 0, sizeof(m_rtmsg));
602	rtm->rtm_flags = flags;
603	rtm->rtm_version = RTM_VERSION;
604
605	switch (cmd) {
606	default:
607		errx(1, "internal wrong cmd");
608		/*NOTREACHED*/
609	case RTM_ADD:
610		rtm->rtm_addrs |= RTA_GATEWAY;
611		rtm->rtm_rmx.rmx_expire = expire_time;
612		rtm->rtm_inits = RTV_EXPIRE;
613		rtm->rtm_flags |= (RTF_HOST | RTF_STATIC);
614		sin_m.sin_other = 0;
615		if (doing_proxy) {
616			if (export_only)
617				sin_m.sin_other = SIN_PROXY;
618			else {
619				rtm->rtm_addrs |= RTA_NETMASK;
620				rtm->rtm_flags &= ~RTF_HOST;
621			}
622		}
623		/* FALLTHROUGH */
624	case RTM_GET:
625		rtm->rtm_addrs |= RTA_DST;
626	}
627
628#define NEXTADDR(w, s) \
629	if (rtm->rtm_addrs & (w)) { \
630		(void)memcpy(cp, &s, \
631		(size_t)((struct sockaddr *)(void *)&s)->sa_len); \
632		RT_ADVANCE(cp, ((struct sockaddr *)(void *)&s)); \
633	}
634
635	NEXTADDR(RTA_DST, sin_m);
636	NEXTADDR(RTA_GATEWAY, sdl_m);
637	NEXTADDR(RTA_NETMASK, so_mask);
638
639	rtm->rtm_msglen = cp - (char *)(void *)&m_rtmsg;
640doit:
641	l = rtm->rtm_msglen;
642	rtm->rtm_seq = ++seq;
643	rtm->rtm_type = cmd;
644	if (write(s, &m_rtmsg, (size_t)l) < 0) {
645		if (errno != ESRCH || cmd != RTM_DELETE) {
646			warn("writing to routing socket");
647			return (-1);
648		}
649	}
650	do {
651		l = read(s, &m_rtmsg, sizeof(m_rtmsg));
652	} while (l > 0 && (rtm->rtm_seq != seq || rtm->rtm_pid != pid));
653	if (l < 0)
654		warn("read from routing socket");
655	return (0);
656}
657
658static int
659getinetaddr(const char *host, struct in_addr *inap)
660{
661	struct hostent *hp;
662
663	if (inet_aton(host, inap) == 1)
664		return (0);
665	if ((hp = gethostbyname(host)) == NULL) {
666		warnx("%s: %s", host, hstrerror(h_errno));
667		return (-1);
668	}
669	(void)memcpy(inap, hp->h_addr, sizeof(*inap));
670	return (0);
671}
672
673static int
674getifname(u_int16_t ifindex, char *ifname, size_t l)
675{
676	int i;
677	struct ifaddrs *addr;
678	const struct sockaddr_dl *sdl = NULL;
679
680	if (ifaddrs == NULL) {
681		i = getifaddrs(&ifaddrs);
682		if (i != 0)
683			err(1, "getifaddrs");
684	}
685
686	for (addr = ifaddrs; addr; addr = addr->ifa_next) {
687		if (addr->ifa_addr == NULL ||
688		    addr->ifa_addr->sa_family != AF_LINK)
689			continue;
690
691		sdl = (const struct sockaddr_dl *)(void *)addr->ifa_addr;
692		if (sdl && sdl->sdl_index == ifindex) {
693			(void) strlcpy(ifname, addr->ifa_name, l);
694			return 0;
695		}
696	}
697
698	return -1;
699}
700