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