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