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