rarpd.c revision 96254
1/*
2 * Copyright (c) 1990, 1991, 1992, 1993, 1996
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that: (1) source code distributions
7 * retain the above copyright notice and this paragraph in its entirety, (2)
8 * distributions including binary code include the above copyright notice and
9 * this paragraph in its entirety in the documentation or other materials
10 * provided with the distribution, and (3) all advertising materials mentioning
11 * features or use of this software display the following acknowledgement:
12 * ``This product includes software developed by the University of California,
13 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14 * the University nor the names of its contributors may be used to endorse
15 * or promote products derived from this software without specific prior
16 * written permission.
17 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20 */
21
22#ifndef lint
23static const char copyright[] =
24"@(#) Copyright (c) 1990, 1991, 1992, 1993, 1996\n\
25The Regents of the University of California.  All rights reserved.\n";
26#endif /* not lint */
27
28#ifndef lint
29static const char rcsid[] =
30  "$FreeBSD: head/usr.sbin/rarpd/rarpd.c 96254 2002-05-09 14:15:57Z roberto $";
31#endif /* not lint */
32
33/*
34 * rarpd - Reverse ARP Daemon
35 *
36 * Usage:	rarpd -a [ -dfsv ] [ hostname ]
37 *		rarpd [ -dfsv ] interface [ hostname ]
38 *
39 * 'hostname' is optional solely for backwards compatibility with Sun's rarpd.
40 * Currently, the argument is ignored.
41 */
42#include <sys/param.h>
43#include <sys/file.h>
44#include <sys/ioctl.h>
45#include <sys/socket.h>
46#include <sys/time.h>
47
48#include <net/bpf.h>
49#include <net/ethernet.h>
50#include <net/if.h>
51#include <net/if_types.h>
52#include <net/if_dl.h>
53#include <net/route.h>
54
55#include <netinet/in.h>
56#include <netinet/if_ether.h>
57
58#include <arpa/inet.h>
59
60#include <errno.h>
61#include <netdb.h>
62#include <stdarg.h>
63#include <stdio.h>
64#include <string.h>
65#include <syslog.h>
66#include <stdlib.h>
67#include <unistd.h>
68
69#if defined(SUNOS4) || defined(__FreeBSD__) /* XXX */
70#define HAVE_DIRENT_H
71#endif
72
73#ifdef HAVE_DIRENT_H
74#include <dirent.h>
75#else
76#include <sys/dir.h>
77#endif
78
79/* Cast a struct sockaddr to a structaddr_in */
80#define SATOSIN(sa) ((struct sockaddr_in *)(sa))
81
82#ifndef TFTP_DIR
83#define TFTP_DIR "/tftpboot"
84#endif
85
86#if BSD >= 199200
87#define ARPSECS (20 * 60)		/* as per code in netinet/if_ether.c */
88#define REVARP_REQUEST ARPOP_REVREQUEST
89#define REVARP_REPLY ARPOP_REVREPLY
90#endif
91
92#ifndef ETHERTYPE_REVARP
93#define ETHERTYPE_REVARP 0x8035
94#define REVARP_REQUEST 3
95#define REVARP_REPLY 4
96#endif
97
98/*
99 * Map field names in ether_arp struct.  What a pain in the neck.
100 */
101#ifdef SUNOS3
102#undef arp_sha
103#undef arp_spa
104#undef arp_tha
105#undef arp_tpa
106#define arp_sha arp_xsha
107#define arp_spa arp_xspa
108#define arp_tha arp_xtha
109#define arp_tpa arp_xtpa
110#endif
111
112/*
113 * The structure for each interface.
114 */
115struct if_info {
116	struct	if_info *ii_next;
117	int	ii_fd;		/* BPF file descriptor */
118	u_long	ii_ipaddr;	/* IP address of this interface */
119	u_long	ii_netmask;	/* subnet or net mask */
120	u_char	ii_eaddr[6];	/* Ethernet address of this interface */
121	char ii_ifname[sizeof(((struct ifreq *)0)->ifr_name) + 1];
122};
123
124/*
125 * The list of all interfaces that are being listened to.  rarp_loop()
126 * "selects" on the descriptors in this list.
127 */
128struct if_info *iflist;
129
130int verbose;			/* verbose messages */
131int s;				/* inet datagram socket */
132const char *tftp_dir = TFTP_DIR;	/* tftp directory */
133
134int dflag;			/* messages to stdout/stderr, not syslog(3) */
135int sflag;			/* ignore /tftpboot */
136
137static	u_char zero[6];
138
139static int	bpf_open(void);
140static u_long	choose_ipaddr(u_long **, u_long, u_long);
141static char	*eatoa(u_char *);
142static int	expand_syslog_m(const char *fmt, char **newfmt);
143static void	init(char *);
144static void	init_one(struct ifreq *, char *);
145static char	*intoa(u_long);
146static u_long	ipaddrtonetmask(u_long);
147static void	logmsg(int, const char *, ...) __printflike(2, 3);
148static int	rarp_bootable(u_long);
149static int	rarp_check(u_char *, u_int);
150static void	rarp_loop(void);
151static int	rarp_open(char *);
152static void	rarp_process(struct if_info *, u_char *, u_int);
153static void	rarp_reply(struct if_info *, struct ether_header *,
154		u_long, u_int);
155static void	update_arptab(u_char *, u_long);
156static void	usage(void);
157
158int
159main(int argc, char *argv[])
160{
161	int op;
162	char *ifname, *hostname, *name;
163
164	int aflag = 0;		/* listen on "all" interfaces  */
165	int fflag = 0;		/* don't fork */
166
167	if ((name = strrchr(argv[0], '/')) != NULL)
168		++name;
169	else
170		name = argv[0];
171	if (*name == '-')
172		++name;
173
174	/*
175	 * All error reporting is done through syslog, unless -d is specified
176	 */
177	openlog(name, LOG_PID | LOG_CONS, LOG_DAEMON);
178
179	opterr = 0;
180	while ((op = getopt(argc, argv, "adfst:v")) != -1) {
181		switch (op) {
182		case 'a':
183			++aflag;
184			break;
185
186		case 'd':
187			++dflag;
188			break;
189
190		case 'f':
191			++fflag;
192			break;
193
194		case 's':
195			++sflag;
196			break;
197
198		case 't':
199			tftp_dir = optarg;
200			break;
201
202		case 'v':
203			++verbose;
204			break;
205
206		default:
207			usage();
208			/* NOTREACHED */
209		}
210	}
211	ifname = argv[optind++];
212	hostname =  ifname ? argv[optind] : NULL;
213	if ((aflag && ifname) || (!aflag && ifname == NULL))
214		usage();
215
216	if (aflag)
217		init(NULL);
218	else
219		init(ifname);
220
221	if (!fflag) {
222		if (daemon(0,0)) {
223			logmsg(LOG_ERR, "cannot fork");
224			exit(1);
225		}
226	}
227	rarp_loop();
228	return(0);
229}
230
231/*
232 * Add to the interface list.
233 */
234void
235init_one(struct ifreq *ifrp, char *target)
236{
237	struct if_info *ii;
238	struct sockaddr_dl *ll;
239	int family;
240	struct ifreq ifr;
241
242	family = ifrp->ifr_addr.sa_family;
243	switch (family) {
244
245	case AF_INET:
246#if BSD >= 199100
247	case AF_LINK:
248#endif
249		(void)strncpy(ifr.ifr_name, ifrp->ifr_name,
250		    sizeof(ifrp->ifr_name));
251		if (ioctl(s, SIOCGIFFLAGS, (char *)&ifr) == -1) {
252			logmsg(LOG_ERR,
253			    "SIOCGIFFLAGS: %.*s: %m",
254				(int)sizeof(ifrp->ifr_name), ifrp->ifr_name);
255			exit(1);
256		}
257		if ((ifr.ifr_flags & IFF_UP) == 0 ||
258		    (ifr.ifr_flags & (IFF_LOOPBACK | IFF_POINTOPOINT)) != 0)
259			return;
260		break;
261
262
263	default:
264		return;
265	}
266
267	/* Don't bother going any further if not the target interface */
268	if (target != NULL &&
269	    strncmp(ifrp->ifr_name, target, sizeof(ifrp->ifr_name)) != 0)
270		return;
271
272	/* Look for interface in list */
273	for (ii = iflist; ii != NULL; ii = ii->ii_next)
274		if (strncmp(ifrp->ifr_name, ii->ii_ifname,
275		    sizeof(ifrp->ifr_name)) == 0)
276			break;
277
278	/* Allocate a new one if not found */
279	if (ii == NULL) {
280		ii = (struct if_info *)malloc(sizeof(*ii));
281		if (ii == NULL) {
282			logmsg(LOG_ERR, "malloc: %m");
283			exit(1);
284		}
285		bzero(ii, sizeof(*ii));
286		ii->ii_fd = -1;
287		(void)strncpy(ii->ii_ifname, ifrp->ifr_name,
288		    sizeof(ifrp->ifr_name));
289		ii->ii_ifname[sizeof(ii->ii_ifname) - 1] = '\0';
290		ii->ii_next = iflist;
291		iflist = ii;
292	}
293
294	switch (family) {
295
296	case AF_INET:
297		if (ioctl(s, SIOCGIFADDR, (char *)&ifr) == -1) {
298			logmsg(LOG_ERR, "ipaddr SIOCGIFADDR: %s: %m",
299			    ii->ii_ifname);
300			exit(1);
301		}
302		ii->ii_ipaddr = SATOSIN(&ifr.ifr_addr)->sin_addr.s_addr;
303		if (ioctl(s, SIOCGIFNETMASK, (char *)&ifr) == -1) {
304			logmsg(LOG_ERR, "SIOCGIFNETMASK: %m");
305			exit(1);
306		}
307		ii->ii_netmask = SATOSIN(&ifr.ifr_addr)->sin_addr.s_addr;
308		if (ii->ii_netmask == 0)
309			ii->ii_netmask = ipaddrtonetmask(ii->ii_ipaddr);
310		if (ii->ii_fd < 0) {
311			ii->ii_fd = rarp_open(ii->ii_ifname);
312#if BSD < 199100
313			/* Use BPF descriptor to get ethernet address. */
314			if (ioctl(ii->ii_fd, SIOCGIFADDR, (char *)&ifr) == -1) {
315				logmsg(LOG_ERR, "eaddr SIOCGIFADDR: %s: %m",
316				    ii->ii_ifname);
317				exit(1);
318			}
319			bcopy(&ifr.ifr_addr.sa_data[0], ii->ii_eaddr, 6);
320#endif
321		}
322		break;
323
324#if BSD >= 199100
325		case AF_LINK:
326			ll = (struct sockaddr_dl *)&ifrp->ifr_addr;
327			if (ll->sdl_type == IFT_ETHER)
328				bcopy(LLADDR(ll), ii->ii_eaddr, 6);
329			break;
330#endif
331		}
332}
333/*
334 * Initialize all "candidate" interfaces that are in the system
335 * configuration list.  A "candidate" is up, not loopback and not
336 * point to point.
337 */
338void
339init(char *target)
340{
341	u_int n;
342	struct ifreq *ifrp, *ifend;
343	struct if_info *ii, *nii, *lii;
344	struct ifconf ifc;
345	struct ifreq ibuf[16];
346
347	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
348		logmsg(LOG_ERR, "socket: %m");
349		exit(1);
350	}
351	ifc.ifc_len = sizeof ibuf;
352	ifc.ifc_buf = (caddr_t)ibuf;
353	if ((ioctl(s, SIOCGIFCONF, (char *)&ifc) == -1) ||
354	    ((u_int)ifc.ifc_len < sizeof(struct ifreq))) {
355		logmsg(LOG_ERR, "SIOCGIFCONF: %m");
356		exit(1);
357	}
358	ifrp = ibuf;
359	ifend = (struct ifreq *)((char *)ibuf + ifc.ifc_len);
360	while (ifrp < ifend) {
361		init_one(ifrp, target);
362
363#if BSD >= 199100
364		n = ifrp->ifr_addr.sa_len + sizeof(ifrp->ifr_name);
365		if (n < sizeof(*ifrp))
366			n = sizeof(*ifrp);
367		ifrp = (struct ifreq *)((char *)ifrp + n);
368#else
369		++ifrp;
370#endif
371	}
372
373	/* Throw away incomplete interfaces */
374	lii = NULL;
375	for (ii = iflist; ii != NULL; ii = nii) {
376		nii = ii->ii_next;
377		if (ii->ii_ipaddr == 0 ||
378		    bcmp(ii->ii_eaddr, zero, 6) == 0) {
379			if (lii == NULL)
380				iflist = nii;
381			else
382				lii->ii_next = nii;
383			if (ii->ii_fd >= 0)
384				close(ii->ii_fd);
385			free(ii);
386			continue;
387		}
388		lii = ii;
389	}
390
391	/* Verbose stuff */
392	if (verbose)
393		for (ii = iflist; ii != NULL; ii = ii->ii_next)
394			logmsg(LOG_DEBUG, "%s %s 0x%08lx %s",
395			    ii->ii_ifname, intoa(ntohl(ii->ii_ipaddr)),
396			    (u_long)ntohl(ii->ii_netmask), eatoa(ii->ii_eaddr));
397}
398
399void
400usage(void)
401{
402	(void)fprintf(stderr, "usage: rarpd [-adfsv] [interface]\n");
403	exit(1);
404}
405
406int
407bpf_open(void)
408{
409	int fd;
410	int n = 0;
411	char device[sizeof "/dev/bpf000"];
412
413	/*
414	 * Go through all the minors and find one that isn't in use.
415	 */
416	do {
417		(void)sprintf(device, "/dev/bpf%d", n++);
418		fd = open(device, O_RDWR);
419	} while ((fd == -1) && (errno == EBUSY));
420
421	if (fd == -1) {
422		logmsg(LOG_ERR, "%s: %m", device);
423		exit(1);
424	}
425	return fd;
426}
427
428/*
429 * Open a BPF file and attach it to the interface named 'device'.
430 * Set immediate mode, and set a filter that accepts only RARP requests.
431 */
432int
433rarp_open(char *device)
434{
435	int fd;
436	struct ifreq ifr;
437	u_int dlt;
438	int immediate;
439
440	static struct bpf_insn insns[] = {
441		BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 12),
442		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, ETHERTYPE_REVARP, 0, 3),
443		BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 20),
444		BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, REVARP_REQUEST, 0, 1),
445		BPF_STMT(BPF_RET|BPF_K, sizeof(struct ether_arp) +
446			 sizeof(struct ether_header)),
447		BPF_STMT(BPF_RET|BPF_K, 0),
448	};
449	static struct bpf_program filter = {
450		sizeof insns / sizeof(insns[0]),
451		insns
452	};
453
454	fd = bpf_open();
455	/*
456	 * Set immediate mode so packets are processed as they arrive.
457	 */
458	immediate = 1;
459	if (ioctl(fd, BIOCIMMEDIATE, &immediate) == -1) {
460		logmsg(LOG_ERR, "BIOCIMMEDIATE: %m");
461		exit(1);
462	}
463	(void)strncpy(ifr.ifr_name, device, sizeof ifr.ifr_name);
464	if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) == -1) {
465		logmsg(LOG_ERR, "BIOCSETIF: %m");
466		exit(1);
467	}
468	/*
469	 * Check that the data link layer is an Ethernet; this code won't
470	 * work with anything else.
471	 */
472	if (ioctl(fd, BIOCGDLT, (caddr_t)&dlt) == -1) {
473		logmsg(LOG_ERR, "BIOCGDLT: %m");
474		exit(1);
475	}
476	if (dlt != DLT_EN10MB) {
477		logmsg(LOG_ERR, "%s is not an ethernet", device);
478		exit(1);
479	}
480	/*
481	 * Set filter program.
482	 */
483	if (ioctl(fd, BIOCSETF, (caddr_t)&filter) == -1) {
484		logmsg(LOG_ERR, "BIOCSETF: %m");
485		exit(1);
486	}
487	return fd;
488}
489
490/*
491 * Perform various sanity checks on the RARP request packet.  Return
492 * false on failure and log the reason.
493 */
494int
495rarp_check(u_char *p, u_int len)
496{
497	struct ether_header *ep = (struct ether_header *)p;
498	struct ether_arp *ap = (struct ether_arp *)(p + sizeof(*ep));
499
500	if (len < sizeof(*ep) + sizeof(*ap)) {
501		logmsg(LOG_ERR, "truncated request, got %u, expected %lu",
502				len, (u_long)(sizeof(*ep) + sizeof(*ap)));
503		return 0;
504	}
505	/*
506	 * XXX This test might be better off broken out...
507	 */
508	if (ntohs(ep->ether_type) != ETHERTYPE_REVARP ||
509	    ntohs(ap->arp_hrd) != ARPHRD_ETHER ||
510	    ntohs(ap->arp_op) != REVARP_REQUEST ||
511	    ntohs(ap->arp_pro) != ETHERTYPE_IP ||
512	    ap->arp_hln != 6 || ap->arp_pln != 4) {
513		logmsg(LOG_DEBUG, "request fails sanity check");
514		return 0;
515	}
516	if (bcmp((char *)&ep->ether_shost, (char *)&ap->arp_sha, 6) != 0) {
517		logmsg(LOG_DEBUG, "ether/arp sender address mismatch");
518		return 0;
519	}
520	if (bcmp((char *)&ap->arp_sha, (char *)&ap->arp_tha, 6) != 0) {
521		logmsg(LOG_DEBUG, "ether/arp target address mismatch");
522		return 0;
523	}
524	return 1;
525}
526
527#ifndef FD_SETSIZE
528#define FD_SET(n, fdp) ((fdp)->fds_bits[0] |= (1 << (n)))
529#define FD_ISSET(n, fdp) ((fdp)->fds_bits[0] & (1 << (n)))
530#define FD_ZERO(fdp) ((fdp)->fds_bits[0] = 0)
531#endif
532
533/*
534 * Loop indefinitely listening for RARP requests on the
535 * interfaces in 'iflist'.
536 */
537void
538rarp_loop(void)
539{
540	u_char *buf, *bp, *ep;
541	int cc, fd;
542	fd_set fds, listeners;
543	int bufsize, maxfd = 0;
544	struct if_info *ii;
545
546	if (iflist == NULL) {
547		logmsg(LOG_ERR, "no interfaces");
548		exit(1);
549	}
550	if (ioctl(iflist->ii_fd, BIOCGBLEN, (caddr_t)&bufsize) == -1) {
551		logmsg(LOG_ERR, "BIOCGBLEN: %m");
552		exit(1);
553	}
554	buf = malloc(bufsize);
555	if (buf == NULL) {
556		logmsg(LOG_ERR, "malloc: %m");
557		exit(1);
558	}
559
560	while (1) {
561		/*
562		 * Find the highest numbered file descriptor for select().
563		 * Initialize the set of descriptors to listen to.
564		 */
565		FD_ZERO(&fds);
566		for (ii = iflist; ii != NULL; ii = ii->ii_next) {
567			FD_SET(ii->ii_fd, &fds);
568			if (ii->ii_fd > maxfd)
569				maxfd = ii->ii_fd;
570		}
571		listeners = fds;
572		if (select(maxfd + 1, &listeners, NULL, NULL, NULL) == -1) {
573			/* Don't choke when we get ptraced */
574			if (errno == EINTR)
575				continue;
576			logmsg(LOG_ERR, "select: %m");
577			exit(1);
578		}
579		for (ii = iflist; ii != NULL; ii = ii->ii_next) {
580			fd = ii->ii_fd;
581			if (!FD_ISSET(fd, &listeners))
582				continue;
583		again:
584			cc = read(fd, (char *)buf, bufsize);
585			/* Don't choke when we get ptraced */
586			if ((cc == -1) && (errno == EINTR))
587				goto again;
588#if defined(SUNOS3) || defined(SUNOS4)
589			/*
590			 * Due to a SunOS bug, after 2^31 bytes, the
591			 * file offset overflows and read fails with
592			 * EINVAL.  The lseek() to 0 will fix things.
593			 */
594			if (cc == -1) {
595				if (errno == EINVAL &&
596				    (long)(tell(fd) + bufsize) < 0) {
597					(void)lseek(fd, 0, 0);
598					goto again;
599				}
600				logmsg(LOG_ERR, "read: %m");
601				exit(1);
602			}
603#endif
604
605			/* Loop through the packet(s) */
606#define bhp ((struct bpf_hdr *)bp)
607			bp = buf;
608			ep = bp + cc;
609			while (bp < ep) {
610				u_int caplen, hdrlen;
611
612				caplen = bhp->bh_caplen;
613				hdrlen = bhp->bh_hdrlen;
614				if (rarp_check(bp + hdrlen, caplen))
615					rarp_process(ii, bp + hdrlen, caplen);
616				bp += BPF_WORDALIGN(hdrlen + caplen);
617			}
618		}
619	}
620#undef bhp
621}
622
623/*
624 * True if this server can boot the host whose IP address is 'addr'.
625 * This check is made by looking in the tftp directory for the
626 * configuration file.
627 */
628int
629rarp_bootable(u_long addr)
630{
631#ifdef HAVE_DIRENT_H
632	struct dirent *dent;
633#else
634	struct direct *dent;
635#endif
636	DIR *d;
637	char ipname[9];
638	static DIR *dd = NULL;
639
640	(void)sprintf(ipname, "%08lX", (u_long)ntohl(addr));
641
642	/*
643	 * If directory is already open, rewind it.  Otherwise, open it.
644	 */
645	if ((d = dd) != NULL)
646		rewinddir(d);
647	else {
648		if (chdir(tftp_dir) == -1) {
649			logmsg(LOG_ERR, "chdir: %s: %m", tftp_dir);
650			exit(1);
651		}
652		d = opendir(".");
653		if (d == NULL) {
654			logmsg(LOG_ERR, "opendir: %m");
655			exit(1);
656		}
657		dd = d;
658	}
659	while ((dent = readdir(d)) != NULL)
660		if (strncmp(dent->d_name, ipname, 8) == 0)
661			return 1;
662	return 0;
663}
664
665/*
666 * Given a list of IP addresses, 'alist', return the first address that
667 * is on network 'net'; 'netmask' is a mask indicating the network portion
668 * of the address.
669 */
670u_long
671choose_ipaddr(u_long **alist, u_long net, u_long netmask)
672{
673	for (; *alist; ++alist)
674		if ((**alist & netmask) == net)
675			return **alist;
676	return 0;
677}
678
679/*
680 * Answer the RARP request in 'pkt', on the interface 'ii'.  'pkt' has
681 * already been checked for validity.  The reply is overlaid on the request.
682 */
683void
684rarp_process(struct if_info *ii, u_char *pkt, u_int len)
685{
686	struct ether_header *ep;
687	struct hostent *hp;
688	u_long target_ipaddr;
689	char ename[256];
690
691	ep = (struct ether_header *)pkt;
692	/* should this be arp_tha? */
693	if (ether_ntohost(ename, (struct ether_addr *)&ep->ether_shost) != 0) {
694		logmsg(LOG_ERR, "cannot map %s to name",
695			eatoa(ep->ether_shost));
696		return;
697	}
698
699	if ((hp = gethostbyname(ename)) == NULL) {
700		logmsg(LOG_ERR, "cannot map %s to IP address", ename);
701		return;
702	}
703
704	/*
705	 * Choose correct address from list.
706	 */
707	if (hp->h_addrtype != AF_INET) {
708		logmsg(LOG_ERR, "cannot handle non IP addresses for %s",
709								ename);
710		return;
711	}
712	target_ipaddr = choose_ipaddr((u_long **)hp->h_addr_list,
713				      ii->ii_ipaddr & ii->ii_netmask,
714				      ii->ii_netmask);
715	if (target_ipaddr == 0) {
716		logmsg(LOG_ERR, "cannot find %s on net %s",
717		       ename, intoa(ntohl(ii->ii_ipaddr & ii->ii_netmask)));
718		return;
719	}
720	if (sflag || rarp_bootable(target_ipaddr))
721		rarp_reply(ii, ep, target_ipaddr, len);
722	else if (verbose > 1)
723		logmsg(LOG_INFO, "%s %s at %s DENIED (not bootable)",
724		    ii->ii_ifname,
725		    eatoa(ep->ether_shost),
726		    intoa(ntohl(target_ipaddr)));
727}
728
729/*
730 * Poke the kernel arp tables with the ethernet/ip address combinataion
731 * given.  When processing a reply, we must do this so that the booting
732 * host (i.e. the guy running rarpd), won't try to ARP for the hardware
733 * address of the guy being booted (he cannot answer the ARP).
734 */
735#if BSD >= 199200
736struct sockaddr_inarp sin_inarp = {
737	sizeof(struct sockaddr_inarp), AF_INET, 0,
738	{0},
739	{0},
740	0, 0
741};
742struct sockaddr_dl sin_dl = {
743	sizeof(struct sockaddr_dl), AF_LINK, 0, IFT_ETHER, 0, 6,
744	0, ""
745};
746struct {
747	struct rt_msghdr rthdr;
748	char rtspace[512];
749} rtmsg;
750
751void
752update_arptab(u_char *ep, u_long ipaddr)
753{
754	int cc;
755	struct sockaddr_inarp *ar, *ar2;
756	struct sockaddr_dl *ll, *ll2;
757	struct rt_msghdr *rt;
758	int xtype, xindex;
759	static pid_t pid;
760	int r;
761	static int seq;
762
763	r = socket(PF_ROUTE, SOCK_RAW, 0);
764	if (r == -1) {
765		logmsg(LOG_ERR, "raw route socket: %m");
766		exit(1);
767	}
768	pid = getpid();
769
770	ar = &sin_inarp;
771	ar->sin_addr.s_addr = ipaddr;
772	ll = &sin_dl;
773	bcopy(ep, LLADDR(ll), 6);
774
775	/* Get the type and interface index */
776	rt = &rtmsg.rthdr;
777	bzero(rt, sizeof(rtmsg));
778	rt->rtm_version = RTM_VERSION;
779	rt->rtm_addrs = RTA_DST;
780	rt->rtm_type = RTM_GET;
781	rt->rtm_seq = ++seq;
782	ar2 = (struct sockaddr_inarp *)rtmsg.rtspace;
783	bcopy(ar, ar2, sizeof(*ar));
784	rt->rtm_msglen = sizeof(*rt) + sizeof(*ar);
785	errno = 0;
786	if ((write(r, rt, rt->rtm_msglen) == -1) && (errno != ESRCH)) {
787		logmsg(LOG_ERR, "rtmsg get write: %m");
788		close(r);
789		return;
790	}
791	do {
792		cc = read(r, rt, sizeof(rtmsg));
793	} while (cc > 0 && (rt->rtm_seq != seq || rt->rtm_pid != pid));
794	if (cc == -1) {
795		logmsg(LOG_ERR, "rtmsg get read: %m");
796		close(r);
797		return;
798	}
799	ll2 = (struct sockaddr_dl *)((u_char *)ar2 + ar2->sin_len);
800	if (ll2->sdl_family != AF_LINK) {
801		/*
802		 * XXX I think this means the ip address is not on a
803		 * directly connected network (the family is AF_INET in
804		 * this case).
805		 */
806		logmsg(LOG_ERR, "bogus link family (%d) wrong net for %08lX?\n",
807		    ll2->sdl_family, ipaddr);
808		close(r);
809		return;
810	}
811	xtype = ll2->sdl_type;
812	xindex = ll2->sdl_index;
813
814	/* Set the new arp entry */
815	bzero(rt, sizeof(rtmsg));
816	rt->rtm_version = RTM_VERSION;
817	rt->rtm_addrs = RTA_DST | RTA_GATEWAY;
818	rt->rtm_inits = RTV_EXPIRE;
819	rt->rtm_rmx.rmx_expire = time(0) + ARPSECS;
820	rt->rtm_flags = RTF_HOST | RTF_STATIC;
821	rt->rtm_type = RTM_ADD;
822	rt->rtm_seq = ++seq;
823
824	bcopy(ar, ar2, sizeof(*ar));
825
826	ll2 = (struct sockaddr_dl *)((u_char *)ar2 + sizeof(*ar2));
827	bcopy(ll, ll2, sizeof(*ll));
828	ll2->sdl_type = xtype;
829	ll2->sdl_index = xindex;
830
831	rt->rtm_msglen = sizeof(*rt) + sizeof(*ar2) + sizeof(*ll2);
832	errno = 0;
833	if ((write(r, rt, rt->rtm_msglen) == -1) && (errno != EEXIST)) {
834		logmsg(LOG_ERR, "rtmsg add write: %m");
835		close(r);
836		return;
837	}
838	do {
839		cc = read(r, rt, sizeof(rtmsg));
840	} while (cc > 0 && (rt->rtm_seq != seq || rt->rtm_pid != pid));
841	close(r);
842	if (cc == -1) {
843		logmsg(LOG_ERR, "rtmsg add read: %m");
844		return;
845	}
846}
847#else
848void
849update_arptab(u_char *ep, u_long ipaddr)
850{
851	struct arpreq request;
852	struct sockaddr_in *sin;
853
854	request.arp_flags = 0;
855	sin = (struct sockaddr_in *)&request.arp_pa;
856	sin->sin_family = AF_INET;
857	sin->sin_addr.s_addr = ipaddr;
858	request.arp_ha.sa_family = AF_UNSPEC;
859	bcopy((char *)ep, (char *)request.arp_ha.sa_data, 6);
860
861	if (ioctl(s, SIOCSARP, (caddr_t)&request) == -1)
862		logmsg(LOG_ERR, "SIOCSARP: %m");
863}
864#endif
865
866/*
867 * Build a reverse ARP packet and sent it out on the interface.
868 * 'ep' points to a valid REVARP_REQUEST.  The REVARP_REPLY is built
869 * on top of the request, then written to the network.
870 *
871 * RFC 903 defines the ether_arp fields as follows.  The following comments
872 * are taken (more or less) straight from this document.
873 *
874 * REVARP_REQUEST
875 *
876 * arp_sha is the hardware address of the sender of the packet.
877 * arp_spa is undefined.
878 * arp_tha is the 'target' hardware address.
879 *   In the case where the sender wishes to determine his own
880 *   protocol address, this, like arp_sha, will be the hardware
881 *   address of the sender.
882 * arp_tpa is undefined.
883 *
884 * REVARP_REPLY
885 *
886 * arp_sha is the hardware address of the responder (the sender of the
887 *   reply packet).
888 * arp_spa is the protocol address of the responder (see the note below).
889 * arp_tha is the hardware address of the target, and should be the same as
890 *   that which was given in the request.
891 * arp_tpa is the protocol address of the target, that is, the desired address.
892 *
893 * Note that the requirement that arp_spa be filled in with the responder's
894 * protocol is purely for convenience.  For instance, if a system were to use
895 * both ARP and RARP, then the inclusion of the valid protocol-hardware
896 * address pair (arp_spa, arp_sha) may eliminate the need for a subsequent
897 * ARP request.
898 */
899void
900rarp_reply(struct if_info *ii, struct ether_header *ep, u_long ipaddr,
901		u_int len)
902{
903	u_int n;
904	struct ether_arp *ap = (struct ether_arp *)(ep + 1);
905
906	update_arptab((u_char *)&ap->arp_sha, ipaddr);
907
908	/*
909	 * Build the rarp reply by modifying the rarp request in place.
910	 */
911	ap->arp_op = htons(REVARP_REPLY);
912
913#ifdef BROKEN_BPF
914	ep->ether_type = ETHERTYPE_REVARP;
915#endif
916	bcopy((char *)&ap->arp_sha, (char *)&ep->ether_dhost, 6);
917	bcopy((char *)ii->ii_eaddr, (char *)&ep->ether_shost, 6);
918	bcopy((char *)ii->ii_eaddr, (char *)&ap->arp_sha, 6);
919
920	bcopy((char *)&ipaddr, (char *)ap->arp_tpa, 4);
921	/* Target hardware is unchanged. */
922	bcopy((char *)&ii->ii_ipaddr, (char *)ap->arp_spa, 4);
923
924	/* Zero possible garbage after packet. */
925	bzero((char *)ep + (sizeof(*ep) + sizeof(*ap)),
926			len - (sizeof(*ep) + sizeof(*ap)));
927	n = write(ii->ii_fd, (char *)ep, len);
928	if (n != len)
929		logmsg(LOG_ERR, "write: only %d of %d bytes written", n, len);
930	if (verbose)
931		logmsg(LOG_INFO, "%s %s at %s REPLIED", ii->ii_ifname,
932		    eatoa(ap->arp_tha),
933		    intoa(ntohl(ipaddr)));
934}
935
936/*
937 * Get the netmask of an IP address.  This routine is used if
938 * SIOCGIFNETMASK doesn't work.
939 */
940u_long
941ipaddrtonetmask(u_long addr)
942{
943	addr = ntohl(addr);
944	if (IN_CLASSA(addr))
945		return htonl(IN_CLASSA_NET);
946	if (IN_CLASSB(addr))
947		return htonl(IN_CLASSB_NET);
948	if (IN_CLASSC(addr))
949		return htonl(IN_CLASSC_NET);
950	logmsg(LOG_DEBUG, "unknown IP address class: %08lX", addr);
951	return htonl(0xffffffff);
952}
953
954/*
955 * A faster replacement for inet_ntoa().
956 */
957char *
958intoa(u_long addr)
959{
960	char *cp;
961	u_int byte;
962	int n;
963	static char buf[sizeof(".xxx.xxx.xxx.xxx")];
964
965	cp = &buf[sizeof buf];
966	*--cp = '\0';
967
968	n = 4;
969	do {
970		byte = addr & 0xff;
971		*--cp = byte % 10 + '0';
972		byte /= 10;
973		if (byte > 0) {
974			*--cp = byte % 10 + '0';
975			byte /= 10;
976			if (byte > 0)
977				*--cp = byte + '0';
978		}
979		*--cp = '.';
980		addr >>= 8;
981	} while (--n > 0);
982
983	return cp + 1;
984}
985
986char *
987eatoa(u_char *ea)
988{
989	static char buf[sizeof("xx:xx:xx:xx:xx:xx")];
990
991	(void)sprintf(buf, "%x:%x:%x:%x:%x:%x",
992	    ea[0], ea[1], ea[2], ea[3], ea[4], ea[5]);
993	return (buf);
994}
995
996void
997logmsg(int pri, const char *fmt, ...)
998{
999	va_list v;
1000	FILE *fp;
1001	char *newfmt;
1002
1003	va_start(v, fmt);
1004	if (dflag) {
1005		if (pri == LOG_ERR)
1006			fp = stderr;
1007		else
1008			fp = stdout;
1009		if (expand_syslog_m(fmt, &newfmt) == -1) {
1010			vfprintf(fp, fmt, v);
1011		} else {
1012			vfprintf(fp, newfmt, v);
1013			free(newfmt);
1014		}
1015		fputs("\n", fp);
1016		fflush(fp);
1017	} else {
1018		vsyslog(pri, fmt, v);
1019	}
1020	va_end(v);
1021}
1022
1023int
1024expand_syslog_m(const char *fmt, char **newfmt) {
1025	const char *str, *m;
1026	char *p, *np;
1027
1028	p = strdup("");
1029	str = fmt;
1030	while ((m = strstr(str, "%m")) != NULL) {
1031		asprintf(&np, "%s%.*s%s", p, (int)(m - str),
1032		    str, strerror(errno));
1033		free(p);
1034		if (np == NULL) {
1035			errno = ENOMEM;
1036			return (-1);
1037		}
1038		p = np;
1039		str = m + 2;
1040	}
1041
1042	if (*str != '\0') {
1043		asprintf(&np, "%s%s", p, str);
1044		free(p);
1045		if (np == NULL) {
1046			errno = ENOMEM;
1047			return (-1);
1048		}
1049		p = np;
1050	}
1051
1052	*newfmt = p;
1053	return (0);
1054}
1055