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