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