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