2 * Copyright (c) 1990, 1991, 1992, 1993, 1996
3 * The Regents of the University of California. All rights reserved.
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
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.
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";
24 #include <sys/cdefs.h>
25 __FBSDID("$FreeBSD$");
28 * rarpd - Reverse ARP Daemon
30 * Usage: rarpd -a [-dfsv] [-t directory] [hostname]
31 * rarpd [-dfsv] [-t directory] interface [hostname]
33 * 'hostname' is optional solely for backwards compatibility with Sun's rarpd.
34 * Currently, the argument is ignored.
36 #include <sys/param.h>
38 #include <sys/ioctl.h>
39 #include <sys/socket.h>
43 #include <net/ethernet.h>
45 #include <net/if_types.h>
46 #include <net/if_dl.h>
47 #include <net/route.h>
49 #include <netinet/in.h>
50 #include <netinet/if_ether.h>
52 #include <arpa/inet.h>
65 /* Cast a struct sockaddr to a struct sockaddr_in */
66 #define SATOSIN(sa) ((struct sockaddr_in *)(sa))
69 #define TFTP_DIR "/tftpboot"
72 #define ARPSECS (20 * 60) /* as per code in netinet/if_ether.c */
73 #define REVARP_REQUEST ARPOP_REVREQUEST
74 #define REVARP_REPLY ARPOP_REVREPLY
77 * The structure for each interface.
80 struct if_info *ii_next;
81 int ii_fd; /* BPF file descriptor */
82 in_addr_t ii_ipaddr; /* IP address */
83 in_addr_t ii_netmask; /* subnet or net mask */
84 u_char ii_eaddr[ETHER_ADDR_LEN]; /* ethernet address */
85 char ii_ifname[IF_NAMESIZE];
89 * The list of all interfaces that are being listened to. rarp_loop()
90 * "selects" on the descriptors in this list.
92 struct if_info *iflist;
94 int verbose; /* verbose messages */
95 const char *tftp_dir = TFTP_DIR; /* tftp directory */
97 int dflag; /* messages to stdout/stderr, not syslog(3) */
98 int sflag; /* ignore /tftpboot */
100 static u_char zero[6];
102 static int bpf_open(void);
103 static in_addr_t choose_ipaddr(in_addr_t **, in_addr_t, in_addr_t);
104 static char *eatoa(u_char *);
105 static int expand_syslog_m(const char *fmt, char **newfmt);
106 static void init(char *);
107 static void init_one(struct ifaddrs *, char *, int);
108 static char *intoa(in_addr_t);
109 static in_addr_t ipaddrtonetmask(in_addr_t);
110 static void logmsg(int, const char *, ...) __printflike(2, 3);
111 static int rarp_bootable(in_addr_t);
112 static int rarp_check(u_char *, u_int);
113 static void rarp_loop(void);
114 static int rarp_open(char *);
115 static void rarp_process(struct if_info *, u_char *, u_int);
116 static void rarp_reply(struct if_info *, struct ether_header *,
118 static void update_arptab(u_char *, in_addr_t);
119 static void usage(void);
122 main(int argc, char *argv[])
125 char *ifname, *hostname, *name;
127 int aflag = 0; /* listen on "all" interfaces */
128 int fflag = 0; /* don't fork */
130 if ((name = strrchr(argv[0], '/')) != NULL)
138 * All error reporting is done through syslog, unless -d is specified
140 openlog(name, LOG_PID | LOG_CONS, LOG_DAEMON);
143 while ((op = getopt(argc, argv, "adfst:v")) != -1)
176 ifname = (aflag == 0) ? argv[0] : NULL;
177 hostname = ifname ? argv[1] : argv[0];
179 if ((aflag && ifname) || (!aflag && ifname == NULL))
186 logmsg(LOG_ERR, "cannot fork");
195 * Add to the interface list.
198 init_one(struct ifaddrs *ifa, char *target, int pass1)
200 struct if_info *ii, *ii2;
201 struct sockaddr_dl *ll;
204 family = ifa->ifa_addr->sa_family;
208 /* Consider only AF_LINK during pass1. */
212 if (!(ifa->ifa_flags & IFF_UP) ||
213 (ifa->ifa_flags & (IFF_LOOPBACK | IFF_POINTOPOINT)))
220 /* Don't bother going any further if not the target interface */
221 if (target != NULL && strcmp(ifa->ifa_name, target) != 0)
224 /* Look for interface in list */
225 for (ii = iflist; ii != NULL; ii = ii->ii_next)
226 if (strcmp(ifa->ifa_name, ii->ii_ifname) == 0)
229 if (pass1 && ii != NULL)
230 /* We've already seen that interface once. */
233 /* Allocate a new one if not found */
235 ii = (struct if_info *)malloc(sizeof(*ii));
237 logmsg(LOG_ERR, "malloc: %m");
240 bzero(ii, sizeof(*ii));
242 strlcpy(ii->ii_ifname, ifa->ifa_name, sizeof(ii->ii_ifname));
243 ii->ii_next = iflist;
245 } else if (!pass1 && ii->ii_ipaddr != 0) {
247 * Second AF_INET definition for that interface: clone
248 * the existing one, and work on that cloned one.
249 * This must be another IP address for this interface,
250 * so avoid killing the previous configuration.
252 ii2 = (struct if_info *)malloc(sizeof(*ii2));
254 logmsg(LOG_ERR, "malloc: %m");
257 memcpy(ii2, ii, sizeof(*ii2));
259 ii2->ii_next = iflist;
267 ii->ii_ipaddr = SATOSIN(ifa->ifa_addr)->sin_addr.s_addr;
268 ii->ii_netmask = SATOSIN(ifa->ifa_netmask)->sin_addr.s_addr;
269 if (ii->ii_netmask == 0)
270 ii->ii_netmask = ipaddrtonetmask(ii->ii_ipaddr);
272 ii->ii_fd = rarp_open(ii->ii_ifname);
276 ll = (struct sockaddr_dl *)ifa->ifa_addr;
277 if (ll->sdl_type == IFT_ETHER)
278 bcopy(LLADDR(ll), ii->ii_eaddr, 6);
283 * Initialize all "candidate" interfaces that are in the system
284 * configuration list. A "candidate" is up, not loopback and not
290 struct if_info *ii, *nii, *lii;
291 struct ifaddrs *ifhead, *ifa;
294 error = getifaddrs(&ifhead);
296 logmsg(LOG_ERR, "getifaddrs: %m");
300 * We make two passes over the list we have got. In the first
301 * one, we only collect AF_LINK interfaces, and initialize our
302 * list of interfaces from them. In the second pass, we
303 * collect the actual IP addresses from the AF_INET
304 * interfaces, and allow for the same interface name to appear
305 * multiple times (in case of more than one IP address).
307 for (ifa = ifhead; ifa != NULL; ifa = ifa->ifa_next)
308 init_one(ifa, target, 1);
309 for (ifa = ifhead; ifa != NULL; ifa = ifa->ifa_next)
310 init_one(ifa, target, 0);
313 /* Throw away incomplete interfaces */
315 for (ii = iflist; ii != NULL; ii = nii) {
317 if (ii->ii_ipaddr == 0 ||
318 bcmp(ii->ii_eaddr, zero, 6) == 0) {
333 for (ii = iflist; ii != NULL; ii = ii->ii_next)
334 logmsg(LOG_DEBUG, "%s %s 0x%08x %s",
335 ii->ii_ifname, intoa(ntohl(ii->ii_ipaddr)),
336 (in_addr_t)ntohl(ii->ii_netmask), eatoa(ii->ii_eaddr));
342 (void)fprintf(stderr, "%s\n%s\n",
343 "usage: rarpd -a [-dfsv] [-t directory]",
344 " rarpd [-dfsv] [-t directory] interface");
353 char device[sizeof "/dev/bpf000"];
356 * Go through all the minors and find one that isn't in use.
359 (void)sprintf(device, "/dev/bpf%d", n++);
360 fd = open(device, O_RDWR);
361 } while ((fd == -1) && (errno == EBUSY));
364 logmsg(LOG_ERR, "%s: %m", device);
371 * Open a BPF file and attach it to the interface named 'device'.
372 * Set immediate mode, and set a filter that accepts only RARP requests.
375 rarp_open(char *device)
382 static struct bpf_insn insns[] = {
383 BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 12),
384 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, ETHERTYPE_REVARP, 0, 3),
385 BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 20),
386 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, REVARP_REQUEST, 0, 1),
387 BPF_STMT(BPF_RET|BPF_K, sizeof(struct ether_arp) +
388 sizeof(struct ether_header)),
389 BPF_STMT(BPF_RET|BPF_K, 0),
391 static struct bpf_program filter = {
392 sizeof insns / sizeof(insns[0]),
398 * Set immediate mode so packets are processed as they arrive.
401 if (ioctl(fd, BIOCIMMEDIATE, &immediate) == -1) {
402 logmsg(LOG_ERR, "BIOCIMMEDIATE: %m");
405 strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
406 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) == -1) {
407 logmsg(LOG_ERR, "BIOCSETIF: %m");
411 * Check that the data link layer is an Ethernet; this code won't
412 * work with anything else.
414 if (ioctl(fd, BIOCGDLT, (caddr_t)&dlt) == -1) {
415 logmsg(LOG_ERR, "BIOCGDLT: %m");
418 if (dlt != DLT_EN10MB) {
419 logmsg(LOG_ERR, "%s is not an ethernet", device);
423 * Set filter program.
425 if (ioctl(fd, BIOCSETF, (caddr_t)&filter) == -1) {
426 logmsg(LOG_ERR, "BIOCSETF: %m");
433 * Perform various sanity checks on the RARP request packet. Return
434 * false on failure and log the reason.
437 rarp_check(u_char *p, u_int len)
439 struct ether_header *ep = (struct ether_header *)p;
440 struct ether_arp *ap = (struct ether_arp *)(p + sizeof(*ep));
442 if (len < sizeof(*ep) + sizeof(*ap)) {
443 logmsg(LOG_ERR, "truncated request, got %u, expected %lu",
444 len, (u_long)(sizeof(*ep) + sizeof(*ap)));
448 * XXX This test might be better off broken out...
450 if (ntohs(ep->ether_type) != ETHERTYPE_REVARP ||
451 ntohs(ap->arp_hrd) != ARPHRD_ETHER ||
452 ntohs(ap->arp_op) != REVARP_REQUEST ||
453 ntohs(ap->arp_pro) != ETHERTYPE_IP ||
454 ap->arp_hln != 6 || ap->arp_pln != 4) {
455 logmsg(LOG_DEBUG, "request fails sanity check");
458 if (bcmp((char *)&ep->ether_shost, (char *)&ap->arp_sha, 6) != 0) {
459 logmsg(LOG_DEBUG, "ether/arp sender address mismatch");
462 if (bcmp((char *)&ap->arp_sha, (char *)&ap->arp_tha, 6) != 0) {
463 logmsg(LOG_DEBUG, "ether/arp target address mismatch");
470 * Loop indefinitely listening for RARP requests on the
471 * interfaces in 'iflist'.
476 u_char *buf, *bp, *ep;
478 fd_set fds, listeners;
479 int bufsize, maxfd = 0;
482 if (iflist == NULL) {
483 logmsg(LOG_ERR, "no interfaces");
486 if (ioctl(iflist->ii_fd, BIOCGBLEN, (caddr_t)&bufsize) == -1) {
487 logmsg(LOG_ERR, "BIOCGBLEN: %m");
490 buf = malloc(bufsize);
492 logmsg(LOG_ERR, "malloc: %m");
498 * Find the highest numbered file descriptor for select().
499 * Initialize the set of descriptors to listen to.
502 for (ii = iflist; ii != NULL; ii = ii->ii_next) {
503 FD_SET(ii->ii_fd, &fds);
504 if (ii->ii_fd > maxfd)
508 if (select(maxfd + 1, &listeners, NULL, NULL, NULL) == -1) {
509 /* Don't choke when we get ptraced */
512 logmsg(LOG_ERR, "select: %m");
515 for (ii = iflist; ii != NULL; ii = ii->ii_next) {
517 if (!FD_ISSET(fd, &listeners))
520 cc = read(fd, (char *)buf, bufsize);
521 /* Don't choke when we get ptraced */
522 if ((cc == -1) && (errno == EINTR))
525 /* Loop through the packet(s) */
526 #define bhp ((struct bpf_hdr *)bp)
530 u_int caplen, hdrlen;
532 caplen = bhp->bh_caplen;
533 hdrlen = bhp->bh_hdrlen;
534 if (rarp_check(bp + hdrlen, caplen))
535 rarp_process(ii, bp + hdrlen, caplen);
536 bp += BPF_WORDALIGN(hdrlen + caplen);
544 * True if this server can boot the host whose IP address is 'addr'.
545 * This check is made by looking in the tftp directory for the
546 * configuration file.
549 rarp_bootable(in_addr_t addr)
554 static DIR *dd = NULL;
556 (void)sprintf(ipname, "%08X", (in_addr_t)ntohl(addr));
559 * If directory is already open, rewind it. Otherwise, open it.
561 if ((d = dd) != NULL)
564 if (chdir(tftp_dir) == -1) {
565 logmsg(LOG_ERR, "chdir: %s: %m", tftp_dir);
570 logmsg(LOG_ERR, "opendir: %m");
575 while ((dent = readdir(d)) != NULL)
576 if (strncmp(dent->d_name, ipname, 8) == 0)
582 * Given a list of IP addresses, 'alist', return the first address that
583 * is on network 'net'; 'netmask' is a mask indicating the network portion
587 choose_ipaddr(in_addr_t **alist, in_addr_t net, in_addr_t netmask)
589 for (; *alist; ++alist)
590 if ((**alist & netmask) == net)
596 * Answer the RARP request in 'pkt', on the interface 'ii'. 'pkt' has
597 * already been checked for validity. The reply is overlaid on the request.
600 rarp_process(struct if_info *ii, u_char *pkt, u_int len)
602 struct ether_header *ep;
604 in_addr_t target_ipaddr;
607 ep = (struct ether_header *)pkt;
608 /* should this be arp_tha? */
609 if (ether_ntohost(ename, (struct ether_addr *)&ep->ether_shost) != 0) {
610 logmsg(LOG_ERR, "cannot map %s to name",
611 eatoa(ep->ether_shost));
615 if ((hp = gethostbyname(ename)) == NULL) {
616 logmsg(LOG_ERR, "cannot map %s to IP address", ename);
621 * Choose correct address from list.
623 if (hp->h_addrtype != AF_INET) {
624 logmsg(LOG_ERR, "cannot handle non IP addresses for %s",
628 target_ipaddr = choose_ipaddr((in_addr_t **)hp->h_addr_list,
629 ii->ii_ipaddr & ii->ii_netmask,
631 if (target_ipaddr == 0) {
632 logmsg(LOG_ERR, "cannot find %s on net %s",
633 ename, intoa(ntohl(ii->ii_ipaddr & ii->ii_netmask)));
636 if (sflag || rarp_bootable(target_ipaddr))
637 rarp_reply(ii, ep, target_ipaddr, len);
638 else if (verbose > 1)
639 logmsg(LOG_INFO, "%s %s at %s DENIED (not bootable)",
641 eatoa(ep->ether_shost),
642 intoa(ntohl(target_ipaddr)));
646 * Poke the kernel arp tables with the ethernet/ip address combinataion
647 * given. When processing a reply, we must do this so that the booting
648 * host (i.e. the guy running rarpd), won't try to ARP for the hardware
649 * address of the guy being booted (he cannot answer the ARP).
651 struct sockaddr_inarp sin_inarp = {
652 sizeof(struct sockaddr_inarp), AF_INET, 0,
657 struct sockaddr_dl sin_dl = {
658 sizeof(struct sockaddr_dl), AF_LINK, 0, IFT_ETHER, 0, 6,
662 struct rt_msghdr rthdr;
667 update_arptab(u_char *ep, in_addr_t ipaddr)
671 struct sockaddr_inarp *ar, *ar2;
672 struct sockaddr_dl *ll, *ll2;
673 struct rt_msghdr *rt;
679 r = socket(PF_ROUTE, SOCK_RAW, 0);
681 logmsg(LOG_ERR, "raw route socket: %m");
687 ar->sin_addr.s_addr = ipaddr;
689 bcopy(ep, LLADDR(ll), 6);
691 /* Get the type and interface index */
693 bzero(rt, sizeof(rtmsg));
694 rt->rtm_version = RTM_VERSION;
695 rt->rtm_addrs = RTA_DST;
696 rt->rtm_type = RTM_GET;
698 ar2 = (struct sockaddr_inarp *)rtmsg.rtspace;
699 bcopy(ar, ar2, sizeof(*ar));
700 rt->rtm_msglen = sizeof(*rt) + sizeof(*ar);
702 if ((write(r, rt, rt->rtm_msglen) == -1) && (errno != ESRCH)) {
703 logmsg(LOG_ERR, "rtmsg get write: %m");
708 cc = read(r, rt, sizeof(rtmsg));
709 } while (cc > 0 && (rt->rtm_seq != seq || rt->rtm_pid != pid));
711 logmsg(LOG_ERR, "rtmsg get read: %m");
715 ll2 = (struct sockaddr_dl *)((u_char *)ar2 + ar2->sin_len);
716 if (ll2->sdl_family != AF_LINK) {
718 * XXX I think this means the ip address is not on a
719 * directly connected network (the family is AF_INET in
722 logmsg(LOG_ERR, "bogus link family (%d) wrong net for %08X?\n",
723 ll2->sdl_family, ipaddr);
727 xtype = ll2->sdl_type;
728 xindex = ll2->sdl_index;
730 /* Set the new arp entry */
731 bzero(rt, sizeof(rtmsg));
732 rt->rtm_version = RTM_VERSION;
733 rt->rtm_addrs = RTA_DST | RTA_GATEWAY;
734 rt->rtm_inits = RTV_EXPIRE;
735 clock_gettime(CLOCK_MONOTONIC, &tp);
736 rt->rtm_rmx.rmx_expire = tp.tv_sec + ARPSECS;
737 rt->rtm_flags = RTF_HOST | RTF_STATIC;
738 rt->rtm_type = RTM_ADD;
741 bcopy(ar, ar2, sizeof(*ar));
743 ll2 = (struct sockaddr_dl *)((u_char *)ar2 + sizeof(*ar2));
744 bcopy(ll, ll2, sizeof(*ll));
745 ll2->sdl_type = xtype;
746 ll2->sdl_index = xindex;
748 rt->rtm_msglen = sizeof(*rt) + sizeof(*ar2) + sizeof(*ll2);
750 if ((write(r, rt, rt->rtm_msglen) == -1) && (errno != EEXIST)) {
751 logmsg(LOG_ERR, "rtmsg add write: %m");
756 cc = read(r, rt, sizeof(rtmsg));
757 } while (cc > 0 && (rt->rtm_seq != seq || rt->rtm_pid != pid));
760 logmsg(LOG_ERR, "rtmsg add read: %m");
766 * Build a reverse ARP packet and sent it out on the interface.
767 * 'ep' points to a valid REVARP_REQUEST. The REVARP_REPLY is built
768 * on top of the request, then written to the network.
770 * RFC 903 defines the ether_arp fields as follows. The following comments
771 * are taken (more or less) straight from this document.
775 * arp_sha is the hardware address of the sender of the packet.
776 * arp_spa is undefined.
777 * arp_tha is the 'target' hardware address.
778 * In the case where the sender wishes to determine his own
779 * protocol address, this, like arp_sha, will be the hardware
780 * address of the sender.
781 * arp_tpa is undefined.
785 * arp_sha is the hardware address of the responder (the sender of the
787 * arp_spa is the protocol address of the responder (see the note below).
788 * arp_tha is the hardware address of the target, and should be the same as
789 * that which was given in the request.
790 * arp_tpa is the protocol address of the target, that is, the desired address.
792 * Note that the requirement that arp_spa be filled in with the responder's
793 * protocol is purely for convenience. For instance, if a system were to use
794 * both ARP and RARP, then the inclusion of the valid protocol-hardware
795 * address pair (arp_spa, arp_sha) may eliminate the need for a subsequent
799 rarp_reply(struct if_info *ii, struct ether_header *ep, in_addr_t ipaddr,
803 struct ether_arp *ap = (struct ether_arp *)(ep + 1);
805 update_arptab((u_char *)&ap->arp_sha, ipaddr);
808 * Build the rarp reply by modifying the rarp request in place.
810 ap->arp_op = htons(REVARP_REPLY);
813 ep->ether_type = ETHERTYPE_REVARP;
815 bcopy((char *)&ap->arp_sha, (char *)&ep->ether_dhost, 6);
816 bcopy((char *)ii->ii_eaddr, (char *)&ep->ether_shost, 6);
817 bcopy((char *)ii->ii_eaddr, (char *)&ap->arp_sha, 6);
819 bcopy((char *)&ipaddr, (char *)ap->arp_tpa, 4);
820 /* Target hardware is unchanged. */
821 bcopy((char *)&ii->ii_ipaddr, (char *)ap->arp_spa, 4);
823 /* Zero possible garbage after packet. */
824 bzero((char *)ep + (sizeof(*ep) + sizeof(*ap)),
825 len - (sizeof(*ep) + sizeof(*ap)));
826 n = write(ii->ii_fd, (char *)ep, len);
828 logmsg(LOG_ERR, "write: only %d of %d bytes written", n, len);
830 logmsg(LOG_INFO, "%s %s at %s REPLIED", ii->ii_ifname,
832 intoa(ntohl(ipaddr)));
836 * Get the netmask of an IP address. This routine is used if
837 * SIOCGIFNETMASK doesn't work.
840 ipaddrtonetmask(in_addr_t addr)
844 return htonl(IN_CLASSA_NET);
846 return htonl(IN_CLASSB_NET);
848 return htonl(IN_CLASSC_NET);
849 logmsg(LOG_DEBUG, "unknown IP address class: %08X", addr);
850 return htonl(0xffffffff);
854 * A faster replacement for inet_ntoa().
857 intoa(in_addr_t addr)
862 static char buf[sizeof(".xxx.xxx.xxx.xxx")];
864 cp = &buf[sizeof buf];
870 *--cp = byte % 10 + '0';
873 *--cp = byte % 10 + '0';
888 static char buf[sizeof("xx:xx:xx:xx:xx:xx")];
890 (void)sprintf(buf, "%x:%x:%x:%x:%x:%x",
891 ea[0], ea[1], ea[2], ea[3], ea[4], ea[5]);
896 logmsg(int pri, const char *fmt, ...)
908 if (expand_syslog_m(fmt, &newfmt) == -1) {
909 vfprintf(fp, fmt, v);
911 vfprintf(fp, newfmt, v);
917 vsyslog(pri, fmt, v);
923 expand_syslog_m(const char *fmt, char **newfmt) {
929 while ((m = strstr(str, "%m")) != NULL) {
930 asprintf(&np, "%s%.*s%s", p, (int)(m - str),
931 str, strerror(errno));
942 asprintf(&np, "%s%s", p, str);