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