#include <sys/cdefs.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <netinet/in_systm.h>
#include <string.h>
#include "stand.h"
#include "net.h"
#include "netif.h"
static ssize_t rarpsend(struct iodesc *, void *, size_t);
static ssize_t rarprecv(struct iodesc *, void **, void **, time_t, void *);
int
rarp_getipaddress(int sock)
{
struct iodesc *d;
struct ether_arp *ap;
void *pkt;
struct {
u_char header[ETHER_SIZE];
struct {
struct ether_arp arp;
u_char pad[18];
} data;
} wbuf;
#ifdef RARP_DEBUG
if (debug)
printf("rarp: socket=%d\n", sock);
#endif
if (!(d = socktodesc(sock))) {
printf("rarp: bad socket. %d\n", sock);
return (-1);
}
#ifdef RARP_DEBUG
if (debug)
printf("rarp: d=%x\n", (u_int)d);
#endif
bzero((char*)&wbuf.data, sizeof(wbuf.data));
ap = &wbuf.data.arp;
ap->arp_hrd = htons(ARPHRD_ETHER);
ap->arp_pro = htons(ETHERTYPE_IP);
ap->arp_hln = sizeof(ap->arp_sha);
ap->arp_pln = sizeof(ap->arp_spa);
ap->arp_op = htons(ARPOP_REVREQUEST);
bcopy(d->myea, ap->arp_sha, 6);
bcopy(d->myea, ap->arp_tha, 6);
pkt = NULL;
if (sendrecv(d,
rarpsend, &wbuf.data, sizeof(wbuf.data),
rarprecv, &pkt, (void *)&ap, NULL) < 0) {
printf("No response for RARP request\n");
return (-1);
}
bcopy(ap->arp_tpa, (char *)&myip, sizeof(myip));
#if 0
bcopy(ap->arp_spa, (char *)&rootip, sizeof(rootip));
#endif
free(pkt);
if (IN_CLASSA(myip.s_addr))
netmask = IN_CLASSA_NET;
else if (IN_CLASSB(myip.s_addr))
netmask = IN_CLASSB_NET;
else
netmask = IN_CLASSC_NET;
d->myip = myip;
return (0);
}
static ssize_t
rarpsend(struct iodesc *d, void *pkt, size_t len)
{
#ifdef RARP_DEBUG
if (debug)
printf("rarpsend: called\n");
#endif
return (sendether(d, pkt, len, bcea, ETHERTYPE_REVARP));
}
static ssize_t
rarprecv(struct iodesc *d, void **pkt, void **payload, time_t tleft,
void *extra __unused)
{
ssize_t n;
struct ether_arp *ap;
void *ptr = NULL;
uint16_t etype;
#ifdef RARP_DEBUG
if (debug)
printf("rarprecv: ");
#endif
n = readether(d, &ptr, (void **)&ap, tleft, &etype);
errno = 0;
if (n == -1 || n < sizeof(struct ether_arp)) {
#ifdef RARP_DEBUG
if (debug)
printf("bad len=%d\n", n);
#endif
free(ptr);
return (-1);
}
if (etype != ETHERTYPE_REVARP) {
#ifdef RARP_DEBUG
if (debug)
printf("bad type=0x%x\n", etype);
#endif
free(ptr);
return (-1);
}
if (ap->arp_hrd != htons(ARPHRD_ETHER) ||
ap->arp_pro != htons(ETHERTYPE_IP) ||
ap->arp_hln != sizeof(ap->arp_sha) ||
ap->arp_pln != sizeof(ap->arp_spa) )
{
#ifdef RARP_DEBUG
if (debug)
printf("bad hrd/pro/hln/pln\n");
#endif
free(ptr);
return (-1);
}
if (ap->arp_op != htons(ARPOP_REVREPLY)) {
#ifdef RARP_DEBUG
if (debug)
printf("bad op=0x%x\n", ntohs(ap->arp_op));
#endif
free(ptr);
return (-1);
}
if (bcmp(ap->arp_tha, d->myea, 6)) {
#ifdef RARP_DEBUG
if (debug)
printf("unwanted address\n");
#endif
free(ptr);
return (-1);
}
#ifdef RARP_DEBUG
if (debug)
printf("got it\n");
#endif
*pkt = ptr;
*payload = ap;
return (n);
}