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