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