rarpd.c revision 1.25
1/*	$NetBSD: rarpd.c,v 1.25 1998/04/23 02:48:33 mrg Exp $	*/
2
3/*
4 * Copyright (c) 1990 The Regents of the University of California.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that: (1) source code distributions
9 * retain the above copyright notice and this paragraph in its entirety, (2)
10 * distributions including binary code include the above copyright notice and
11 * this paragraph in its entirety in the documentation or other materials
12 * provided with the distribution, and (3) all advertising materials mentioning
13 * features or use of this software display the following acknowledgement:
14 * ``This product includes software developed by the University of California,
15 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
16 * the University nor the names of its contributors may be used to endorse
17 * or promote products derived from this software without specific prior
18 * written permission.
19 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
20 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
22 */
23#include <sys/cdefs.h>
24#ifndef lint
25__COPYRIGHT(
26    "@(#) Copyright (c) 1990 The Regents of the University of California.\n\
27 All rights reserved.\n");
28#endif /* not lint */
29
30#ifndef lint
31__RCSID("$NetBSD: rarpd.c,v 1.25 1998/04/23 02:48:33 mrg Exp $");
32#endif
33
34
35/*
36 * rarpd - Reverse ARP Daemon
37 *
38 * Usage:	rarpd -a [ -d -f ]
39 *		rarpd [ -d -f ] interface
40 */
41
42#include <sys/types.h>
43#include <sys/errno.h>
44#include <sys/file.h>
45#include <sys/time.h>
46#include <sys/socket.h>
47#include <sys/ioctl.h>
48
49#include <net/bpf.h>
50#include <net/if.h>
51#include <net/if_dl.h>
52#ifdef __NetBSD__
53#include <net/if_ether.h>
54#endif
55#include <net/if_types.h>
56#include <netinet/in.h>
57#ifdef __NetBSD__
58#include <netinet/if_inarp.h>
59#else
60#include <netinet/if_ether.h>
61#endif
62
63#include <arpa/inet.h>
64
65#include <dirent.h>
66#include <netdb.h>
67#include <stdio.h>
68#include <stdlib.h>
69#include <string.h>
70#include <syslog.h>
71#include <unistd.h>
72
73#include "pathnames.h"
74
75#define FATAL		1	/* fatal error occurred */
76#define NONFATAL	0	/* non fatal error occurred */
77
78/*
79 * The structure for each interface.
80 */
81struct if_info {
82	int     ii_fd;		/* BPF file descriptor */
83	u_char  ii_eaddr[6];	/* Ethernet address of this interface */
84	u_long  ii_ipaddr;	/* IP address of this interface */
85	u_long  ii_netmask;	/* subnet or net mask */
86	struct if_info *ii_next;
87};
88/*
89 * The list of all interfaces that are being listened to.  rarp_loop()
90 * "selects" on the descriptors in this list.
91 */
92struct if_info *iflist;
93
94u_int32_t choose_ipaddr __P((u_int32_t **, u_int32_t, u_int32_t));
95void	debug __P((const char *,...));
96void	init_all __P((void));
97void	init_one __P((char *));
98u_long	ipaddrtonetmask __P((u_long));
99void	lookup_eaddr __P((char *, u_char *));
100void	lookup_ipaddr __P((char *, u_long *, u_long *));
101int	main __P((int, char **));
102void	rarp_loop __P((void));
103int	rarp_open __P((char *));
104void	rarp_process __P((struct if_info *, u_char *));
105void	rarp_reply __P((struct if_info *, struct ether_header *, u_long,
106			struct hostent *));
107void	rarperr __P((int, const char *,...));
108
109#if defined(__NetBSD__)
110#include "mkarp.h"
111#else
112void  update_arptab __P((u_char *, u_long));
113#endif
114
115void	usage __P((void));
116
117static int	bpf_open __P((void));
118static int	rarp_check __P((u_char *, int));
119
120#ifdef REQUIRE_TFTPBOOT
121int	rarp_bootable __P((u_long));
122#endif
123
124int     aflag = 0;		/* listen on "all" interfaces  */
125int     dflag = 0;		/* print debugging messages */
126int     fflag = 0;		/* don't fork */
127int	lflag = 0;		/* log all replies */
128
129int
130main(argc, argv)
131	int     argc;
132	char  **argv;
133{
134	extern char *__progname;
135
136	int     op, pid, devnull, f;
137	char   *ifname, *hostname;
138
139	/* All error reporting is done through syslogs. */
140	openlog(__progname, LOG_PID, LOG_DAEMON);
141
142	opterr = 0;
143	while ((op = getopt(argc, argv, "adfl")) != -1) {
144		switch (op) {
145		case 'a':
146			++aflag;
147			break;
148
149		case 'd':
150			++dflag;
151			break;
152
153		case 'f':
154			++fflag;
155			break;
156
157		case 'l':
158			++lflag;
159			break;
160
161		default:
162			usage();
163			/* NOTREACHED */
164		}
165	}
166	ifname = argv[optind++];
167	hostname = ifname ? argv[optind] : 0;
168	if ((aflag && ifname) || (!aflag && ifname == 0))
169		usage();
170
171	if (aflag)
172		init_all();
173	else
174		init_one(ifname);
175
176	if ((!fflag) && (!dflag)) {
177		FILE *fp;
178
179		pid = fork();
180		if (pid > 0)
181			/* Parent exits, leaving child in background. */
182			exit(0);
183		else
184			if (pid == -1) {
185				rarperr(FATAL, "cannot fork");
186				/* NOTREACHED */
187			}
188
189		/* write pid file */
190		if ((fp = fopen(_PATH_RARPDPID, "w")) != NULL) {
191			fprintf(fp, "%u\n", getpid());
192			(void)fclose(fp);
193		}
194
195		/* Fade into the background */
196		f = open("/dev/tty", O_RDWR);
197		if (f >= 0) {
198			if (ioctl(f, TIOCNOTTY, 0) < 0) {
199				rarperr(FATAL,
200				    "TIOCNOTTY: %s", strerror(errno));
201				/* NOTREACHED */
202			}
203			(void) close(f);
204		}
205		(void) chdir("/");
206		(void) setpgrp(0, getpid());
207		devnull = open("/dev/null", O_RDWR);
208		if (devnull >= 0) {
209			(void) dup2(devnull, 0);
210			(void) dup2(devnull, 1);
211			(void) dup2(devnull, 2);
212			if (devnull > 2)
213				(void) close(devnull);
214		}
215	}
216	rarp_loop();
217	/* NOTREACHED */
218	return (0);
219}
220
221/*
222 * Add 'ifname' to the interface list.  Lookup its IP address and network
223 * mask and Ethernet address, and open a BPF file for it.
224 */
225void
226init_one(ifname)
227	char   *ifname;
228{
229	struct if_info *p;
230	int fd;
231
232	fd = rarp_open(ifname);
233	if (fd < 0)
234		return;
235
236	p = (struct if_info *)malloc(sizeof(*p));
237	if (p == 0) {
238		rarperr(FATAL, "malloc: %s", strerror(errno));
239		/* NOTREACHED */
240	}
241	p->ii_next = iflist;
242	iflist = p;
243
244	p->ii_fd = fd;
245	lookup_eaddr(ifname, p->ii_eaddr);
246	lookup_ipaddr(ifname, &p->ii_ipaddr, &p->ii_netmask);
247}
248
249/*
250 * Initialize all "candidate" interfaces that are in the system
251 * configuration list.  A "candidate" is up, not loopback and not
252 * point to point.
253 */
254void
255init_all()
256{
257	char inbuf[8192];
258	struct ifconf ifc;
259	struct ifreq ifreq, *ifr;
260	int fd;
261	int i, len;
262
263	if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
264		rarperr(FATAL, "socket: %s", strerror(errno));
265		/* NOTREACHED */
266	}
267
268	ifc.ifc_len = sizeof(inbuf);
269	ifc.ifc_buf = inbuf;
270	if (ioctl(fd, SIOCGIFCONF, (caddr_t)&ifc) < 0 ||
271	    ifc.ifc_len < sizeof(struct ifreq)) {
272		rarperr(FATAL, "init_all: SIOCGIFCONF: %s", strerror(errno));
273		/* NOTREACHED */
274	}
275	ifr = ifc.ifc_req;
276	ifreq.ifr_name[0] = '\0';
277	for (i = 0; i < ifc.ifc_len;
278	     i += len, ifr = (struct ifreq *)((caddr_t)ifr + len)) {
279		len = sizeof(ifr->ifr_name) + ifr->ifr_addr.sa_len;
280		if (!strncmp(ifreq.ifr_name, ifr->ifr_name, sizeof(ifr->ifr_name)))
281			continue;
282		ifreq = *ifr;
283		if (ioctl(fd, SIOCGIFFLAGS, (caddr_t)ifr) < 0) {
284			rarperr(FATAL, "init_all: SIOCGIFFLAGS: %s",
285			    strerror(errno));
286			/* NOTREACHED */
287		}
288		if ((ifr->ifr_flags &
289		    (IFF_UP | IFF_LOOPBACK | IFF_POINTOPOINT)) != IFF_UP)
290			continue;
291		init_one(ifr->ifr_name);
292	}
293	(void) close(fd);
294}
295
296void
297usage()
298{
299	(void) fprintf(stderr, "usage: rarpd -a [ -d -f ]\n");
300	(void) fprintf(stderr, "       rarpd [ -d -f ] interface\n");
301	exit(1);
302}
303
304static int
305bpf_open()
306{
307	int     fd;
308	int     n = 0;
309	char    device[sizeof "/dev/bpf000"];
310
311	/* Go through all the minors and find one that isn't in use. */
312	do {
313		(void) sprintf(device, "/dev/bpf%d", n++);
314		fd = open(device, O_RDWR);
315	} while (fd < 0 && errno == EBUSY);
316
317	if (fd < 0) {
318		rarperr(FATAL, "%s: %s", device, strerror(errno));
319		/* NOTREACHED */
320	}
321	return fd;
322}
323/*
324 * Open a BPF file and attach it to the interface named 'device'.
325 * Set immediate mode, and set a filter that accepts only RARP requests.
326 */
327int
328rarp_open(device)
329	char   *device;
330{
331	int     fd;
332	struct ifreq ifr;
333	u_int   dlt;
334	int     immediate;
335
336	static struct bpf_insn insns[] = {
337		BPF_STMT(BPF_LD | BPF_H | BPF_ABS, 12),
338		BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ETHERTYPE_REVARP, 0, 3),
339		BPF_STMT(BPF_LD | BPF_H | BPF_ABS, 20),
340		BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ARPOP_REVREQUEST, 0, 1),
341		BPF_STMT(BPF_RET | BPF_K,
342		    sizeof(struct arphdr) +
343		    2 * ETHER_ADDR_LEN + 2 * sizeof(struct in_addr) +
344		    sizeof(struct ether_header)),
345		BPF_STMT(BPF_RET | BPF_K, 0),
346	};
347	static struct bpf_program filter = {
348		sizeof insns / sizeof(insns[0]),
349		insns
350	};
351
352	fd = bpf_open();
353
354	/* Set immediate mode so packets are processed as they arrive. */
355	immediate = 1;
356	if (ioctl(fd, BIOCIMMEDIATE, &immediate) < 0) {
357		rarperr(FATAL, "BIOCIMMEDIATE: %s", strerror(errno));
358		/* NOTREACHED */
359	}
360	(void) strncpy(ifr.ifr_name, device, sizeof ifr.ifr_name);
361	if (ioctl(fd, BIOCSETIF, (caddr_t) & ifr) < 0) {
362		if (aflag) {	/* for -a skip non-ethernet interfaces */
363			close(fd);
364			return(-1);
365		}
366		rarperr(FATAL, "BIOCSETIF: %s", strerror(errno));
367		/* NOTREACHED */
368	}
369	/* Check that the data link layer is an Ethernet; this code won't work
370	 * with anything else. */
371	if (ioctl(fd, BIOCGDLT, (caddr_t) & dlt) < 0) {
372		rarperr(FATAL, "BIOCGDLT: %s", strerror(errno));
373		/* NOTREACHED */
374	}
375	if (dlt != DLT_EN10MB) {
376		if (aflag) {	/* for -a skip non-ethernet interfaces */
377			close(fd);
378			return(-1);
379		}
380		rarperr(FATAL, "%s is not an ethernet", device);
381		/* NOTREACHED */
382	}
383	/* Set filter program. */
384	if (ioctl(fd, BIOCSETF, (caddr_t) & filter) < 0) {
385		rarperr(FATAL, "BIOCSETF: %s", strerror(errno));
386		/* NOTREACHED */
387	}
388	return fd;
389}
390/*
391 * Perform various sanity checks on the RARP request packet.  Return
392 * false on failure and log the reason.
393 */
394static int
395rarp_check(p, len)
396	u_char *p;
397	int     len;
398{
399	struct ether_header *ep = (struct ether_header *) p;
400#ifdef __NetBSD__
401	struct arphdr *ap = (struct arphdr *) (p + sizeof(*ep));
402#else
403	struct ether_arp *ap = (struct ether_arp *) (p + sizeof(*ep));
404#endif
405
406	if (dflag)
407		fprintf(stderr, "got a packet\n");
408
409	if (len < sizeof(*ep) + sizeof(*ap)) {
410		rarperr(NONFATAL, "truncated request");
411		return 0;
412	}
413#ifdef __NetBSD__
414	/* now that we know the fixed part of the ARP hdr is there: */
415	if (len < sizeof(*ap) + 2 * ap->ar_hln + 2 * ap->ar_pln) {
416		rarperr(NONFATAL, "truncated request");
417		return 0;
418	}
419#endif
420	/* XXX This test might be better off broken out... */
421#ifdef __FreeBSD__
422	/* BPF (incorrectly) returns this in host order. */
423	if (ep->ether_type != ETHERTYPE_REVARP ||
424#else
425	if (ntohs (ep->ether_type) != ETHERTYPE_REVARP ||
426#endif
427#ifdef __NetBSD__
428	    ntohs (ap->ar_hrd) != ARPHRD_ETHER ||
429	    ntohs (ap->ar_op) != ARPOP_REVREQUEST ||
430	    ntohs (ap->ar_pro) != ETHERTYPE_IP ||
431	    ap->ar_hln != 6 || ap->ar_pln != 4) {
432#else
433	    ntohs (ap->arp_hrd) != ARPHRD_ETHER ||
434	    ntohs (ap->arp_op) != ARPOP_REVREQUEST ||
435	    ntohs (ap->arp_pro) != ETHERTYPE_IP ||
436	    ap->arp_hln != 6 || ap->arp_pln != 4) {
437#endif
438		rarperr(NONFATAL, "request fails sanity check");
439		return 0;
440	}
441#ifdef __NetBSD__
442	if (memcmp((char *) &ep->ether_shost, ar_sha(ap), 6) != 0) {
443#else
444	if (memcmp((char *) &ep->ether_shost, ap->arp_sha, 6) != 0) {
445#endif
446		rarperr(NONFATAL, "ether/arp sender address mismatch");
447		return 0;
448	}
449#ifdef __NetBSD__
450	if (memcmp(ar_sha(ap), ar_tha(ap), 6) != 0) {
451#else
452	if (memcmp((char *) &ap->arp_sha, (char *) &ap->arp_tha, 6) != 0) {
453#endif
454		rarperr(NONFATAL, "ether/arp target address mismatch");
455		return 0;
456	}
457	return 1;
458}
459
460/*
461 * Loop indefinitely listening for RARP requests on the
462 * interfaces in 'iflist'.
463 */
464void
465rarp_loop()
466{
467	u_char *buf, *bp, *ep;
468	int     cc, fd;
469	fd_set  fds, listeners;
470	int     bufsize, maxfd = 0;
471	struct if_info *ii;
472
473	if (iflist == 0) {
474		rarperr(FATAL, "no interfaces");
475		/* NOTREACHED */
476	}
477	if (ioctl(iflist->ii_fd, BIOCGBLEN, (caddr_t) & bufsize) < 0) {
478		rarperr(FATAL, "BIOCGBLEN: %s", strerror(errno));
479		/* NOTREACHED */
480	}
481	buf = (u_char *) malloc((unsigned) bufsize);
482	if (buf == 0) {
483		rarperr(FATAL, "malloc: %s", strerror(errno));
484		/* NOTREACHED */
485	}
486	/*
487         * Find the highest numbered file descriptor for select().
488         * Initialize the set of descriptors to listen to.
489         */
490	FD_ZERO(&fds);
491	for (ii = iflist; ii; ii = ii->ii_next) {
492		FD_SET(ii->ii_fd, &fds);
493		if (ii->ii_fd > maxfd)
494			maxfd = ii->ii_fd;
495	}
496	while (1) {
497		listeners = fds;
498		if (select(maxfd + 1, &listeners, (struct fd_set *) 0,
499			(struct fd_set *) 0, (struct timeval *) 0) < 0) {
500			rarperr(FATAL, "select: %s", strerror(errno));
501			/* NOTREACHED */
502		}
503		for (ii = iflist; ii; ii = ii->ii_next) {
504			fd = ii->ii_fd;
505			if (!FD_ISSET(fd, &listeners))
506				continue;
507		again:
508			cc = read(fd, (char *) buf, bufsize);
509			/* Don't choke when we get ptraced */
510			if (cc < 0 && errno == EINTR)
511				goto again;
512			/* Due to a SunOS bug, after 2^31 bytes, the file
513			 * offset overflows and read fails with EINVAL.  The
514			 * lseek() to 0 will fix things. */
515			if (cc < 0) {
516				if (errno == EINVAL &&
517				    (lseek(fd, 0, SEEK_CUR) + bufsize) < 0) {
518					(void) lseek(fd, 0, 0);
519					goto again;
520				}
521				rarperr(FATAL, "read: %s", strerror(errno));
522				/* NOTREACHED */
523			}
524			/* Loop through the packet(s) */
525#define bhp ((struct bpf_hdr *)bp)
526			bp = buf;
527			ep = bp + cc;
528			while (bp < ep) {
529				register int caplen, hdrlen;
530
531				caplen = bhp->bh_caplen;
532				hdrlen = bhp->bh_hdrlen;
533				if (rarp_check(bp + hdrlen, caplen))
534					rarp_process(ii, bp + hdrlen);
535				bp += BPF_WORDALIGN(hdrlen + caplen);
536			}
537		}
538	}
539}
540
541#ifdef REQUIRE_TFTPBOOT
542
543#ifndef TFTP_DIR
544#define TFTP_DIR "/tftpboot"
545#endif
546
547/*
548 * True if this server can boot the host whose IP address is 'addr'.
549 * This check is made by looking in the tftp directory for the
550 * configuration file.
551 */
552int
553rarp_bootable(addr)
554	u_long  addr;
555{
556	register struct dirent *dent;
557	register DIR *d;
558	char    ipname[9];
559	static DIR *dd = 0;
560
561	(void) sprintf(ipname, "%08X", addr);
562	/* If directory is already open, rewind it.  Otherwise, open it. */
563	if (d = dd)
564		rewinddir(d);
565	else {
566		if (chdir(TFTP_DIR) == -1) {
567			rarperr(FATAL, "chdir: %s", strerror(errno));
568			/* NOTREACHED */
569		}
570		d = opendir(".");
571		if (d == 0) {
572			rarperr(FATAL, "opendir: %s", strerror(errno));
573			/* NOTREACHED */
574		}
575		dd = d;
576	}
577	while (dent = readdir(d))
578		if (strncmp(dent->d_name, ipname, 8) == 0)
579			return 1;
580	return 0;
581}
582#endif /* REQUIRE_TFTPBOOT */
583
584/*
585 * Given a list of IP addresses, 'alist', return the first address that
586 * is on network 'net'; 'netmask' is a mask indicating the network portion
587 * of the address.
588 */
589u_int32_t
590choose_ipaddr(alist, net, netmask)
591	u_int32_t **alist;
592	u_int32_t net;
593	u_int32_t netmask;
594{
595	for (; *alist; ++alist) {
596		if ((**alist & netmask) == net)
597			return **alist;
598	}
599	return 0;
600}
601/*
602 * Answer the RARP request in 'pkt', on the interface 'ii'.  'pkt' has
603 * already been checked for validity.  The reply is overlaid on the request.
604 */
605void
606rarp_process(ii, pkt)
607	struct if_info *ii;
608	u_char *pkt;
609{
610	struct ether_header *ep;
611	struct hostent *hp;
612	u_long  target_ipaddr;
613	char    ename[MAXHOSTNAMELEN + 1];
614	struct	in_addr in;
615
616	ep = (struct ether_header *) pkt;
617
618	if (ether_ntohost(ename, (struct ether_addr *)&ep->ether_shost) != 0) {
619		debug("no IP address for %s",
620		    ether_ntoa((struct ether_addr *)&ep->ether_shost));
621		return;
622	}
623	ename[sizeof(ename)-1] = '\0';
624
625	if ((hp = gethostbyname(ename)) == 0) {
626		debug("gethostbyname(%s) failed: %s", ename,
627		    hstrerror(h_errno));
628		return;
629	}
630
631	/* Choose correct address from list. */
632	if (hp->h_addrtype != AF_INET) {
633		rarperr(FATAL, "cannot handle non IP addresses");
634		/* NOTREACHED */
635	}
636	target_ipaddr = choose_ipaddr((u_int32_t **) hp->h_addr_list,
637	    ii->ii_ipaddr & ii->ii_netmask, ii->ii_netmask);
638
639	if (target_ipaddr == 0) {
640		in.s_addr = ii->ii_ipaddr & ii->ii_netmask;
641		rarperr(NONFATAL, "cannot find %s on net %s\n",
642		    ename, inet_ntoa(in));
643		return;
644	}
645#ifdef REQUIRE_TFTPBOOT
646	if (rarp_bootable(htonl(target_ipaddr)))
647#endif
648		rarp_reply(ii, ep, target_ipaddr, hp);
649#ifdef REQUIRE_TFTPBOOT
650	else
651		debug("%08X not bootable", htonl(target_ipaddr));
652#endif
653}
654/*
655 * Lookup the ethernet address of the interface attached to the BPF
656 * file descriptor 'fd'; return it in 'eaddr'.
657 */
658void
659lookup_eaddr(ifname, eaddr)
660	char *ifname;
661	u_char *eaddr;
662{
663	char inbuf[8192];
664	struct ifconf ifc;
665	struct ifreq *ifr;
666	struct sockaddr_dl *sdl;
667	int fd;
668	int i, len;
669
670	/* We cannot use SIOCGIFADDR on the BPF descriptor.
671	   We must instead get all the interfaces with SIOCGIFCONF
672	   and find the right one.  */
673
674	/* Use datagram socket to get Ethernet address. */
675	if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
676		rarperr(FATAL, "socket: %s", strerror(errno));
677		/* NOTREACHED */
678	}
679
680	ifc.ifc_len = sizeof(inbuf);
681	ifc.ifc_buf = inbuf;
682	if (ioctl(fd, SIOCGIFCONF, (caddr_t)&ifc) < 0 ||
683	    ifc.ifc_len < sizeof(struct ifreq)) {
684		rarperr(FATAL, "lookup_eaddr: SIOGIFCONF: %s", strerror(errno));
685		/* NOTREACHED */
686	}
687	ifr = ifc.ifc_req;
688	for (i = 0; i < ifc.ifc_len;
689	     i += len, ifr = (struct ifreq *)((caddr_t)ifr + len)) {
690		len = sizeof(ifr->ifr_name) + ifr->ifr_addr.sa_len;
691		sdl = (struct sockaddr_dl *)&ifr->ifr_addr;
692		if (sdl->sdl_family != AF_LINK || sdl->sdl_type != IFT_ETHER ||
693		    sdl->sdl_alen != 6)
694			continue;
695		if (!strncmp(ifr->ifr_name, ifname, sizeof(ifr->ifr_name))) {
696			memmove((caddr_t)eaddr, (caddr_t)LLADDR(sdl), 6);
697			debug("%s: %x:%x:%x:%x:%x:%x",
698			    ifr->ifr_name, eaddr[0], eaddr[1],
699			    eaddr[2], eaddr[3], eaddr[4], eaddr[5]);
700			return;
701		}
702	}
703
704	rarperr(FATAL, "lookup_eaddr: Never saw interface `%s'!", ifname);
705}
706/*
707 * Lookup the IP address and network mask of the interface named 'ifname'.
708 */
709void
710lookup_ipaddr(ifname, addrp, netmaskp)
711	char   *ifname;
712	u_long *addrp;
713	u_long *netmaskp;
714{
715	int     fd;
716	struct ifreq ifr;
717
718	/* Use datagram socket to get IP address. */
719	if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
720		rarperr(FATAL, "socket: %s", strerror(errno));
721		/* NOTREACHED */
722	}
723	(void) strncpy(ifr.ifr_name, ifname, sizeof ifr.ifr_name);
724	if (ioctl(fd, SIOCGIFADDR, (char *) &ifr) < 0) {
725		rarperr(FATAL, "SIOCGIFADDR: %s", strerror(errno));
726		/* NOTREACHED */
727	}
728	*addrp = ((struct sockaddr_in *) & ifr.ifr_addr)->sin_addr.s_addr;
729	if (ioctl(fd, SIOCGIFNETMASK, (char *) &ifr) < 0) {
730		perror("SIOCGIFNETMASK");
731		unlink(_PATH_RARPDPID);
732		exit(1);
733	}
734	*netmaskp = ((struct sockaddr_in *) & ifr.ifr_addr)->sin_addr.s_addr;
735	/* If SIOCGIFNETMASK didn't work, figure out a mask from the IP
736	 * address class. */
737	if (*netmaskp == 0)
738		*netmaskp = ipaddrtonetmask(*addrp);
739
740	(void) close(fd);
741}
742/*
743 * Poke the kernel arp tables with the ethernet/ip address combinataion
744 * given.  When processing a reply, we must do this so that the booting
745 * host (i.e. the guy running rarpd), won't try to ARP for the hardware
746 * address of the guy being booted (he cannot answer the ARP).
747 */
748#ifndef __NetBSD__
749void
750update_arptab(ep, ipaddr)
751	u_char *ep;
752	u_long  ipaddr;
753{
754	struct arpreq request;
755	struct sockaddr_in *sin;
756
757	request.arp_flags = 0;
758	sin = (struct sockaddr_in *) & request.arp_pa;
759	sin->sin_family = AF_INET;
760	sin->sin_addr.s_addr = ipaddr;
761	request.arp_ha.sa_family = AF_UNSPEC;
762	/* This is needed #if defined(COMPAT_43) && BYTE_ORDER != BIG_ENDIAN,
763	   because AF_UNSPEC is zero and the kernel assumes that a zero
764	   sa_family means that the real sa_family value is in sa_len.  */
765	request.arp_ha.sa_len = 16; /* XXX */
766	memmove((char *) request.arp_ha.sa_data, (char *)ep, 6);
767
768#if 0
769	s = socket(AF_INET, SOCK_DGRAM, 0);
770	if (ioctl(s, SIOCSARP, (caddr_t) & request) < 0) {
771		rarperr(NONFATAL, "SIOCSARP: %s", strerror(errno));
772	}
773	(void) close(s);
774#endif
775}
776#endif
777
778/*
779 * Build a reverse ARP packet and sent it out on the interface.
780 * 'ep' points to a valid ARPOP_REVREQUEST.  The ARPOP_REVREPLY is built
781 * on top of the request, then written to the network.
782 *
783 * RFC 903 defines the ether_arp fields as follows.  The following comments
784 * are taken (more or less) straight from this document.
785 *
786 * ARPOP_REVREQUEST
787 *
788 * arp_sha is the hardware address of the sender of the packet.
789 * arp_spa is undefined.
790 * arp_tha is the 'target' hardware address.
791 *   In the case where the sender wishes to determine his own
792 *   protocol address, this, like arp_sha, will be the hardware
793 *   address of the sender.
794 * arp_tpa is undefined.
795 *
796 * ARPOP_REVREPLY
797 *
798 * arp_sha is the hardware address of the responder (the sender of the
799 *   reply packet).
800 * arp_spa is the protocol address of the responder (see the note below).
801 * arp_tha is the hardware address of the target, and should be the same as
802 *   that which was given in the request.
803 * arp_tpa is the protocol address of the target, that is, the desired address.
804 *
805 * Note that the requirement that arp_spa be filled in with the responder's
806 * protocol is purely for convenience.  For instance, if a system were to use
807 * both ARP and RARP, then the inclusion of the valid protocol-hardware
808 * address pair (arp_spa, arp_sha) may eliminate the need for a subsequent
809 * ARP request.
810 */
811void
812rarp_reply(ii, ep, ipaddr, hp)
813	struct if_info *ii;
814	struct ether_header *ep;
815	u_long  ipaddr;
816	struct hostent *hp;
817{
818	int     n;
819#ifdef __NetBSD__
820	struct arphdr *ap = (struct arphdr *) (ep + 1);
821#else
822	struct ether_arp *ap = (struct ether_arp *) (ep + 1);
823#endif
824
825	int     len;
826
827#ifdef __NetBSD__
828	(void)mkarp(ar_sha(ap), ipaddr);
829#else
830	update_arptab((u_char *) & ap->arp_sha, ipaddr);
831#endif
832
833	/* Build the rarp reply by modifying the rarp request in place. */
834#ifdef __FreeBSD__
835	/* BPF (incorrectly) wants this in host order. */
836	ep->ether_type = ETHERTYPE_REVARP;
837#else
838	ep->ether_type = htons(ETHERTYPE_REVARP);
839#endif
840#ifdef __NetBSD__
841	ap->ar_hrd = htons(ARPHRD_ETHER);
842	ap->ar_pro = htons(ETHERTYPE_IP);
843	ap->ar_op = htons(ARPOP_REVREPLY);
844
845	memmove((char *) &ep->ether_dhost, ar_sha(ap), 6);
846	memmove((char *) &ep->ether_shost, (char *) ii->ii_eaddr, 6);
847	memmove(ar_sha(ap), (char *) ii->ii_eaddr, 6);
848
849	memmove(ar_tpa(ap), (char *) &ipaddr, 4);
850	/* Target hardware is unchanged. */
851	memmove(ar_spa(ap), (char *) &ii->ii_ipaddr, 4);
852
853	len = sizeof(*ep) + sizeof(*ap) +
854	    2 * ap->ar_pln + 2 * ap->ar_hln;
855#else
856	ap->ea_hdr.ar_hrd = htons(ARPHRD_ETHER);
857	ap->ea_hdr.ar_pro = htons(ETHERTYPE_IP);
858	ap->arp_op = htons(ARPOP_REVREPLY);
859
860	memmove((char *) &ep->ether_dhost, (char *) &ap->arp_sha, 6);
861	memmove((char *) &ep->ether_shost, (char *) ii->ii_eaddr, 6);
862	memmove((char *) &ap->arp_sha, (char *) ii->ii_eaddr, 6);
863
864	memmove((char *) ap->arp_tpa, (char *) &ipaddr, 4);
865	/* Target hardware is unchanged. */
866	memmove((char *) ap->arp_spa, (char *) &ii->ii_ipaddr, 4);
867
868	len = sizeof(*ep) + sizeof(*ap);
869#endif
870
871	if (lflag)
872		syslog(LOG_INFO, "%s asked; %s replied", hp->h_name,
873		    ether_ntoa((struct ether_addr *)ar_tha(ap)));
874	n = write(ii->ii_fd, (char *) ep, len);
875	if (n != len) {
876		rarperr(NONFATAL, "write: only %d of %d bytes written", n, len);
877	}
878}
879/*
880 * Get the netmask of an IP address.  This routine is used if
881 * SIOCGIFNETMASK doesn't work.
882 */
883u_long
884ipaddrtonetmask(addr)
885	u_long  addr;
886{
887	if (IN_CLASSA(addr))
888		return IN_CLASSA_NET;
889	if (IN_CLASSB(addr))
890		return IN_CLASSB_NET;
891	if (IN_CLASSC(addr))
892		return IN_CLASSC_NET;
893	rarperr(FATAL, "unknown IP address class: %08X", addr);
894	/* NOTREACHED */
895	return(-1);
896}
897
898#if __STDC__
899#include <stdarg.h>
900#else
901#include <varargs.h>
902#endif
903
904void
905#if __STDC__
906rarperr(int fatal, const char *fmt,...)
907#else
908rarperr(fmt, va_alist)
909	int     fatal;
910	char   *fmt;
911va_dcl
912#endif
913{
914	va_list ap;
915#if __STDC__
916	va_start(ap, fmt);
917#else
918	va_start(ap);
919#endif
920	if (dflag) {
921		if (fatal)
922			(void) fprintf(stderr, "rarpd: error: ");
923		else
924			(void) fprintf(stderr, "rarpd: warning: ");
925		(void) vfprintf(stderr, fmt, ap);
926		(void) fprintf(stderr, "\n");
927	}
928	vsyslog(LOG_ERR, fmt, ap);
929	va_end(ap);
930	if (fatal) {
931		unlink(_PATH_RARPDPID);
932		exit(1);
933	}
934	/* NOTREACHED */
935}
936
937void
938#if __STDC__
939debug(const char *fmt,...)
940#else
941debug(fmt, va_alist)
942	char   *fmt;
943va_dcl
944#endif
945{
946	va_list ap;
947
948#if __STDC__
949	va_start(ap, fmt);
950#else
951	va_start(ap);
952#endif
953	if (dflag) {
954		(void) fprintf(stderr, "rarpd: ");
955		(void) vfprintf(stderr, fmt, ap);
956		(void) fprintf(stderr, "\n");
957	}
958	vsyslog(LOG_WARNING, fmt, ap);
959	va_end(ap);
960}
961