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