Index: head/libexec/bootpd/getether.c =================================================================== --- head/libexec/bootpd/getether.c (revision 297864) +++ head/libexec/bootpd/getether.c (revision 297865) @@ -1,389 +1,389 @@ /* * getether.c : get the ethernet address of an interface * * All of this code is quite system-specific. As you may well * guess, it took a good bit of detective work to figure out! * * If you figure out how to do this on another system, * please let me know. * * $FreeBSD$ */ #include #include #ifndef NO_UNISTD #include #endif #include #include #include #include #include "getether.h" #include "report.h" #define EALEN 6 #if defined(ultrix) || (defined(__osf__) && defined(__alpha)) /* * This is really easy on Ultrix! Thanks to * Harald Lundberg for this code. * * The code here is not specific to the Alpha, but that was the * only symbol we could find to identify DEC's version of OSF. * (Perhaps we should just define DEC in the Makefile... -gwr) */ #include #include /* struct ifdevea */ getether(ifname, eap) char *ifname, *eap; { int rc = -1; int fd; struct ifdevea phys; bzero(&phys, sizeof(phys)); strcpy(phys.ifr_name, ifname); if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { report(LOG_ERR, "getether: socket(INET,DGRAM) failed"); return -1; } if (ioctl(fd, SIOCRPHYSADDR, &phys) < 0) { report(LOG_ERR, "getether: ioctl SIOCRPHYSADDR failed"); } else { bcopy(&phys.current_pa[0], eap, EALEN); rc = 0; } close(fd); return rc; } #define GETETHER #endif /* ultrix|osf1 */ #ifdef SUNOS #include #include /* needed by net_if.h */ #include /* for NIOCBIND */ #include /* for struct ifreq */ getether(ifname, eap) char *ifname; /* interface name from ifconfig structure */ char *eap; /* Ether address (output) */ { int rc = -1; struct ifreq ifrnit; int nit; bzero((char *) &ifrnit, sizeof(ifrnit)); strlcpy(&ifrnit.ifr_name[0], ifname, IFNAMSIZ); nit = open("/dev/nit", 0); if (nit < 0) { report(LOG_ERR, "getether: open /dev/nit: %s", get_errmsg()); return rc; } do { if (ioctl(nit, NIOCBIND, &ifrnit) < 0) { report(LOG_ERR, "getether: NIOCBIND on nit"); break; } if (ioctl(nit, SIOCGIFADDR, &ifrnit) < 0) { report(LOG_ERR, "getether: SIOCGIFADDR on nit"); break; } bcopy(&ifrnit.ifr_addr.sa_data[0], eap, EALEN); rc = 0; } while (0); close(nit); return rc; } #define GETETHER #endif /* SUNOS */ #if defined(__FreeBSD__) || defined(__NetBSD__) /* Thanks to John Brezak for this code. */ #include #include #include #include #include int getether(ifname, eap) char *ifname; /* interface name from ifconfig structure */ char *eap; /* Ether address (output) */ { int fd, rc = -1; - register int n; + int n; struct ifreq ibuf[16]; struct ifconf ifc; - register struct ifreq *ifrp, *ifend; + struct ifreq *ifrp, *ifend; /* Fetch the interface configuration */ fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { report(LOG_ERR, "getether: socket %s: %s", ifname, get_errmsg()); return (fd); } ifc.ifc_len = sizeof(ibuf); ifc.ifc_buf = (caddr_t) ibuf; if (ioctl(fd, SIOCGIFCONF, (char *) &ifc) < 0 || ifc.ifc_len < sizeof(struct ifreq)) { report(LOG_ERR, "getether: SIOCGIFCONF: %s", get_errmsg()); goto out; } /* Search interface configuration list for link layer address. */ ifrp = ibuf; ifend = (struct ifreq *) ((char *) ibuf + ifc.ifc_len); while (ifrp < ifend) { /* Look for interface */ if (strcmp(ifname, ifrp->ifr_name) == 0 && ifrp->ifr_addr.sa_family == AF_LINK && ((struct sockaddr_dl *) &ifrp->ifr_addr)->sdl_type == IFT_ETHER) { bcopy(LLADDR((struct sockaddr_dl *) &ifrp->ifr_addr), eap, EALEN); rc = 0; break; } /* Bump interface config pointer */ n = ifrp->ifr_addr.sa_len + sizeof(ifrp->ifr_name); if (n < sizeof(*ifrp)) n = sizeof(*ifrp); ifrp = (struct ifreq *) ((char *) ifrp + n); } out: close(fd); return (rc); } #define GETETHER #endif /* __NetBSD__ */ #ifdef SVR4 /* * This is for "Streams TCP/IP" by Lachman Associates. * They sure made this cumbersome! -gwr */ #include #include #include #include #ifndef NULL #define NULL 0 #endif int getether(ifname, eap) char *ifname; /* interface name from ifconfig structure */ char *eap; /* Ether address (output) */ { int rc = -1; char devname[32]; char tmpbuf[sizeof(union DL_primitives) + 16]; struct strbuf cbuf; int fd, flags; union DL_primitives *dlp; char *enaddr; int unit = -1; /* which unit to attach */ snprintf(devname, sizeof(devname), "%s%s", _PATH_DEV, ifname); fd = open(devname, 2); if (fd < 0) { /* Try without the trailing digit. */ char *p = devname + 5; while (isalpha(*p)) p++; if (isdigit(*p)) { unit = *p - '0'; *p = '\0'; } fd = open(devname, 2); if (fd < 0) { report(LOG_ERR, "getether: open %s: %s", devname, get_errmsg()); return rc; } } #ifdef DL_ATTACH_REQ /* * If this is a "Style 2" DLPI, then we must "attach" first * to tell the driver which unit (board, port) we want. * For now, decide this based on the device name. * (Should do "info_req" and check dl_provider_style ...) */ if (unit >= 0) { memset(tmpbuf, 0, sizeof(tmpbuf)); dlp = (union DL_primitives *) tmpbuf; dlp->dl_primitive = DL_ATTACH_REQ; dlp->attach_req.dl_ppa = unit; cbuf.buf = tmpbuf; cbuf.len = DL_ATTACH_REQ_SIZE; if (putmsg(fd, &cbuf, NULL, 0) < 0) { report(LOG_ERR, "getether: attach: putmsg: %s", get_errmsg()); goto out; } /* Recv the ack. */ cbuf.buf = tmpbuf; cbuf.maxlen = sizeof(tmpbuf); flags = 0; if (getmsg(fd, &cbuf, NULL, &flags) < 0) { report(LOG_ERR, "getether: attach: getmsg: %s", get_errmsg()); goto out; } /* * Check the type, etc. */ if (dlp->dl_primitive == DL_ERROR_ACK) { report(LOG_ERR, "getether: attach: dlpi_errno=%d, unix_errno=%d", dlp->error_ack.dl_errno, dlp->error_ack.dl_unix_errno); goto out; } if (dlp->dl_primitive != DL_OK_ACK) { report(LOG_ERR, "getether: attach: not OK or ERROR"); goto out; } } /* unit >= 0 */ #endif /* DL_ATTACH_REQ */ /* * Get the Ethernet address the same way the ARP module * does when it is pushed onto a new stream (bind). * One should instead be able just do a dl_info_req * but many drivers do not supply the hardware address * in the response to dl_info_req (they MUST supply it * for dl_bind_ack because the ARP module requires it). */ memset(tmpbuf, 0, sizeof(tmpbuf)); dlp = (union DL_primitives *) tmpbuf; dlp->dl_primitive = DL_BIND_REQ; dlp->bind_req.dl_sap = 0x8FF; /* XXX - Unused SAP */ cbuf.buf = tmpbuf; cbuf.len = DL_BIND_REQ_SIZE; if (putmsg(fd, &cbuf, NULL, 0) < 0) { report(LOG_ERR, "getether: bind: putmsg: %s", get_errmsg()); goto out; } /* Recv the ack. */ cbuf.buf = tmpbuf; cbuf.maxlen = sizeof(tmpbuf); flags = 0; if (getmsg(fd, &cbuf, NULL, &flags) < 0) { report(LOG_ERR, "getether: bind: getmsg: %s", get_errmsg()); goto out; } /* * Check the type, etc. */ if (dlp->dl_primitive == DL_ERROR_ACK) { report(LOG_ERR, "getether: bind: dlpi_errno=%d, unix_errno=%d", dlp->error_ack.dl_errno, dlp->error_ack.dl_unix_errno); goto out; } if (dlp->dl_primitive != DL_BIND_ACK) { report(LOG_ERR, "getether: bind: not OK or ERROR"); goto out; } if (dlp->bind_ack.dl_addr_offset == 0) { report(LOG_ERR, "getether: bind: ack has no address"); goto out; } if (dlp->bind_ack.dl_addr_length < EALEN) { report(LOG_ERR, "getether: bind: ack address truncated"); goto out; } /* * Copy the Ethernet address out of the message. */ enaddr = tmpbuf + dlp->bind_ack.dl_addr_offset; memcpy(eap, enaddr, EALEN); rc = 0; out: close(fd); return rc; } #define GETETHER #endif /* SVR4 */ #ifdef __linux__ /* * This is really easy on Linux! This version (for linux) * written by Nigel Metheringham and * updated by Pauline Middelink * * The code is almost identical to the Ultrix code - however * the names are different to confuse the innocent :-) * Most of this code was stolen from the Ultrix bit above. */ #include #include #include /* struct ifreq */ #include /* Needed for IOCTL defs */ int getether(ifname, eap) char *ifname, *eap; { int rc = -1; int fd; struct ifreq phys; memset(&phys, 0, sizeof(phys)); strcpy(phys.ifr_name, ifname); if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { report(LOG_ERR, "getether: socket(INET,DGRAM) failed"); return -1; } if (ioctl(fd, SIOCGIFHWADDR, &phys) < 0) { report(LOG_ERR, "getether: ioctl SIOCGIFHWADDR failed"); } else { memcpy(eap, &phys.ifr_hwaddr.sa_data, EALEN); rc = 0; } close(fd); return rc; } #define GETETHER #endif /* __linux__ */ /* If we don't know how on this system, just return an error. */ #ifndef GETETHER int getether(ifname, eap) char *ifname, *eap; { return -1; } #endif /* !GETETHER */ /* * Local Variables: * tab-width: 4 * c-indent-level: 4 * c-argdecl-indent: 4 * c-continued-statement-offset: 4 * c-continued-brace-offset: -4 * c-label-offset: -4 * c-brace-offset: 0 * End: */ Index: head/libexec/bootpd/hash.c =================================================================== --- head/libexec/bootpd/hash.c (revision 297864) +++ head/libexec/bootpd/hash.c (revision 297865) @@ -1,416 +1,416 @@ /************************************************************************ Copyright 1988, 1991 by Carnegie Mellon University All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Carnegie Mellon University not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. $FreeBSD$ ************************************************************************/ /* * Generalized hash table ADT * * Provides multiple, dynamically-allocated, variable-sized hash tables on * various data and keys. * * This package attempts to follow some of the coding conventions suggested * by Bob Sidebotham and the AFS Clean Code Committee of the * Information Technology Center at Carnegie Mellon. */ #include #include #ifndef USE_BFUNCS #include /* Yes, memcpy is OK here (no overlapped copies). */ #define bcopy(a,b,c) memcpy(b,a,c) #define bzero(p,l) memset(p,0,l) #define bcmp(a,b,c) memcmp(a,b,c) #endif #include "hash.h" #define TRUE 1 #define FALSE 0 #ifndef NULL #define NULL 0 #endif /* * This can be changed to make internal routines visible to debuggers, etc. */ #ifndef PRIVATE #define PRIVATE static #endif PRIVATE void hashi_FreeMembers(hash_member *, hash_freefp); /* * Hash table initialization routine. * * This routine creates and intializes a hash table of size "tablesize" * entries. Successful calls return a pointer to the hash table (which must * be passed to other hash routines to identify the hash table). Failed * calls return NULL. */ hash_tbl * hash_Init(tablesize) unsigned tablesize; { - register hash_tbl *hashtblptr; - register unsigned totalsize; + hash_tbl *hashtblptr; + unsigned totalsize; if (tablesize > 0) { totalsize = sizeof(hash_tbl) + sizeof(hash_member *) * (tablesize - 1); hashtblptr = (hash_tbl *) malloc(totalsize); if (hashtblptr) { bzero((char *) hashtblptr, totalsize); hashtblptr->size = tablesize; /* Success! */ hashtblptr->bucketnum = 0; hashtblptr->member = (hashtblptr->table)[0]; } } else { hashtblptr = NULL; /* Disallow zero-length tables */ } return hashtblptr; /* NULL if failure */ } /* * Frees an entire linked list of bucket members (used in the open * hashing scheme). Does nothing if the passed pointer is NULL. */ PRIVATE void hashi_FreeMembers(bucketptr, free_data) hash_member *bucketptr; hash_freefp free_data; { hash_member *nextbucket; while (bucketptr) { nextbucket = bucketptr->next; (*free_data) (bucketptr->data); free((char *) bucketptr); bucketptr = nextbucket; } } /* * This routine re-initializes the hash table. It frees all the allocated * memory and resets all bucket pointers to NULL. */ void hash_Reset(hashtable, free_data) hash_tbl *hashtable; hash_freefp free_data; { hash_member **bucketptr; unsigned i; bucketptr = hashtable->table; for (i = 0; i < hashtable->size; i++) { hashi_FreeMembers(*bucketptr, free_data); *bucketptr++ = NULL; } hashtable->bucketnum = 0; hashtable->member = (hashtable->table)[0]; } /* * Generic hash function to calculate a hash code from the given string. * * For each byte of the string, this function left-shifts the value in an * accumulator and then adds the byte into the accumulator. The contents of * the accumulator is returned after the entire string has been processed. * It is assumed that this result will be used as the "hashcode" parameter in * calls to other functions in this package. These functions automatically * adjust the hashcode for the size of each hashtable. * * This algorithm probably works best when the hash table size is a prime * number. * * Hopefully, this function is better than the previous one which returned * the sum of the squares of all the bytes. I'm still open to other * suggestions for a default hash function. The programmer is more than * welcome to supply his/her own hash function as that is one of the design * features of this package. */ unsigned hash_HashFunction(string, len) unsigned char *string; - register unsigned len; + unsigned len; { - register unsigned accum; + unsigned accum; accum = 0; for (; len > 0; len--) { accum <<= 1; accum += (unsigned) (*string++ & 0xFF); } return accum; } /* * Returns TRUE if at least one entry for the given key exists; FALSE * otherwise. */ int hash_Exists(hashtable, hashcode, compare, key) hash_tbl *hashtable; unsigned hashcode; hash_cmpfp compare; hash_datum *key; { - register hash_member *memberptr; + hash_member *memberptr; memberptr = (hashtable->table)[hashcode % (hashtable->size)]; while (memberptr) { if ((*compare) (key, memberptr->data)) { return TRUE; /* Entry does exist */ } memberptr = memberptr->next; } return FALSE; /* Entry does not exist */ } /* * Insert the data item "element" into the hash table using "hashcode" * to determine the bucket number, and "compare" and "key" to determine * its uniqueness. * * If the insertion is successful 0 is returned. If a matching entry * already exists in the given bucket of the hash table, or some other error * occurs, -1 is returned and the insertion is not done. */ int hash_Insert(hashtable, hashcode, compare, key, element) hash_tbl *hashtable; unsigned hashcode; hash_cmpfp compare; hash_datum *key, *element; { hash_member *temp; hashcode %= hashtable->size; if (hash_Exists(hashtable, hashcode, compare, key)) { return -1; /* At least one entry already exists */ } temp = (hash_member *) malloc(sizeof(hash_member)); if (!temp) return -1; /* malloc failed! */ temp->data = element; temp->next = (hashtable->table)[hashcode]; (hashtable->table)[hashcode] = temp; return 0; /* Success */ } /* * Delete all data elements which match the given key. If at least one * element is found and the deletion is successful, 0 is returned. * If no matching elements can be found in the hash table, -1 is returned. */ int hash_Delete(hashtable, hashcode, compare, key, free_data) hash_tbl *hashtable; unsigned hashcode; hash_cmpfp compare; hash_datum *key; hash_freefp free_data; { hash_member *memberptr, *tempptr; hash_member *previous = NULL; int retval; retval = -1; hashcode %= hashtable->size; /* * Delete the first member of the list if it matches. Since this moves * the second member into the first position we have to keep doing this * over and over until it no longer matches. */ memberptr = (hashtable->table)[hashcode]; while (memberptr && (*compare) (key, memberptr->data)) { (hashtable->table)[hashcode] = memberptr->next; /* * Stop hashi_FreeMembers() from deleting the whole list! */ memberptr->next = NULL; hashi_FreeMembers(memberptr, free_data); memberptr = (hashtable->table)[hashcode]; retval = 0; } /* * Now traverse the rest of the list */ if (memberptr) { previous = memberptr; memberptr = memberptr->next; } while (memberptr) { if ((*compare) (key, memberptr->data)) { tempptr = memberptr; previous->next = memberptr = memberptr->next; /* * Put the brakes on hashi_FreeMembers(). . . . */ tempptr->next = NULL; hashi_FreeMembers(tempptr, free_data); retval = 0; } else { previous = memberptr; memberptr = memberptr->next; } } return retval; } /* * Locate and return the data entry associated with the given key. * * If the data entry is found, a pointer to it is returned. Otherwise, * NULL is returned. */ hash_datum * hash_Lookup(hashtable, hashcode, compare, key) hash_tbl *hashtable; unsigned hashcode; hash_cmpfp compare; hash_datum *key; { hash_member *memberptr; memberptr = (hashtable->table)[hashcode % (hashtable->size)]; while (memberptr) { if ((*compare) (key, memberptr->data)) { return (memberptr->data); } memberptr = memberptr->next; } return NULL; } /* * Return the next available entry in the hashtable for a linear search */ hash_datum * hash_NextEntry(hashtable) hash_tbl *hashtable; { - register unsigned bucket; - register hash_member *memberptr; + unsigned bucket; + hash_member *memberptr; /* * First try to pick up where we left off. */ memberptr = hashtable->member; if (memberptr) { hashtable->member = memberptr->next; /* Set up for next call */ return memberptr->data; /* Return the data */ } /* * We hit the end of a chain, so look through the array of buckets * until we find a new chain (non-empty bucket) or run out of buckets. */ bucket = hashtable->bucketnum + 1; while ((bucket < hashtable->size) && !(memberptr = (hashtable->table)[bucket])) { bucket++; } /* * Check to see if we ran out of buckets. */ if (bucket >= hashtable->size) { /* * Reset to top of table for next call. */ hashtable->bucketnum = 0; hashtable->member = (hashtable->table)[0]; /* * But return end-of-table indication to the caller this time. */ return NULL; } /* * Must have found a non-empty bucket. */ hashtable->bucketnum = bucket; hashtable->member = memberptr->next; /* Set up for next call */ return memberptr->data; /* Return the data */ } /* * Return the first entry in a hash table for a linear search */ hash_datum * hash_FirstEntry(hashtable) hash_tbl *hashtable; { hashtable->bucketnum = 0; hashtable->member = (hashtable->table)[0]; return hash_NextEntry(hashtable); } /* * Local Variables: * tab-width: 4 * c-indent-level: 4 * c-argdecl-indent: 4 * c-continued-statement-offset: 4 * c-continued-brace-offset: -4 * c-label-offset: -4 * c-brace-offset: 0 * End: */ Index: head/libexec/bootpd/hwaddr.c =================================================================== --- head/libexec/bootpd/hwaddr.c (revision 297864) +++ head/libexec/bootpd/hwaddr.c (revision 297865) @@ -1,352 +1,352 @@ /* * hwaddr.c - routines that deal with hardware addresses. * (i.e. Ethernet) * * $FreeBSD$ */ #include #include #include #include #if defined(SUNOS) || defined(SVR4) #include #endif #ifdef SVR4 #include #include #include #endif #ifdef _AIX32 #include /* for struct timeval in net/if.h */ #include /* for struct ifnet in net/if_arp.h */ #endif #include #include #ifdef WIN_TCP #include #include #endif #include #ifndef NO_UNISTD #include #endif #include #ifndef USE_BFUNCS /* Yes, memcpy is OK here (no overlapped copies). */ #include #define bcopy(a,b,c) memcpy(b,a,c) #define bzero(p,l) memset(p,0,l) #define bcmp(a,b,c) memcmp(a,b,c) #endif #ifndef ATF_INUSE /* Not defined on some systems (i.e. Linux) */ #define ATF_INUSE 0 #endif /* For BSD 4.4, set arp entry by writing to routing socket */ #if defined(BSD) #if BSD >= 199306 extern int bsd_arp_set(struct in_addr *, char *, int); #endif #endif #include "bptypes.h" #include "hwaddr.h" #include "report.h" extern int debug; /* * Hardware address lengths (in bytes) and network name based on hardware * type code. List in order specified by Assigned Numbers RFC; Array index * is hardware type code. Entries marked as zero are unknown to the author * at this time. . . . */ struct hwinfo hwinfolist[] = { {0, "Reserved"}, /* Type 0: Reserved (don't use this) */ {6, "Ethernet"}, /* Type 1: 10Mb Ethernet (48 bits) */ {1, "3Mb Ethernet"}, /* Type 2: 3Mb Ethernet (8 bits) */ {0, "AX.25"}, /* Type 3: Amateur Radio AX.25 */ {1, "ProNET"}, /* Type 4: Proteon ProNET Token Ring */ {0, "Chaos"}, /* Type 5: Chaos */ {6, "IEEE 802"}, /* Type 6: IEEE 802 Networks */ {0, "ARCNET"} /* Type 7: ARCNET */ }; int hwinfocnt = sizeof(hwinfolist) / sizeof(hwinfolist[0]); /* * Setup the arp cache so that IP address 'ia' will be temporarily * bound to hardware address 'ha' of length 'len'. */ void setarp(s, ia, hafamily, haddr, halen) int s; /* socket fd */ struct in_addr *ia; /* protocol address */ int hafamily; /* HW address family */ u_char *haddr; /* HW address data */ int halen; { #ifdef SIOCSARP #ifdef WIN_TCP /* This is an SVR4 with different networking code from * Wollongong WIN-TCP. Not quite like the Lachman code. * Code from: drew@drewsun.FEITH.COM (Andrew B. Sudell) */ #undef SIOCSARP #define SIOCSARP ARP_ADD struct arptab arpreq; /* Arp table entry */ bzero((caddr_t) &arpreq, sizeof(arpreq)); arpreq.at_flags = ATF_COM; /* Set up IP address */ arpreq.at_in = ia->s_addr; /* Set up Hardware Address */ bcopy(haddr, arpreq.at_enaddr, halen); /* Set the Date Link type. */ /* XXX - Translate (hafamily) to dltype somehow? */ arpreq.at_dltype = DL_ETHER; #else /* WIN_TCP */ /* Good old Berkeley way. */ struct arpreq arpreq; /* Arp request ioctl block */ struct sockaddr_in *si; char *p; bzero((caddr_t) &arpreq, sizeof(arpreq)); arpreq.arp_flags = ATF_INUSE | ATF_COM; /* Set up the protocol address. */ arpreq.arp_pa.sa_family = AF_INET; si = (struct sockaddr_in *) &arpreq.arp_pa; si->sin_addr = *ia; /* Set up the hardware address. */ #ifdef __linux__ /* XXX - Do others need this? -gwr */ /* * Linux requires the sa_family field set. * longyear@netcom.com (Al Longyear) */ arpreq.arp_ha.sa_family = hafamily; #endif /* linux */ /* This variable is just to help catch type mismatches. */ p = arpreq.arp_ha.sa_data; bcopy(haddr, p, halen); #endif /* WIN_TCP */ #ifdef SVR4 /* * And now the stuff for System V Rel 4.x which does not * appear to allow SIOCxxx ioctls on a socket descriptor. * Thanks to several people: (all sent the same fix) * Barney Wolff , * bear@upsys.se (Bj|rn Sj|holm), * Michael Kuschke , */ { int fd; struct strioctl iocb; if ((fd=open("/dev/arp", O_RDWR)) < 0) { report(LOG_ERR, "open /dev/arp: %s\n", get_errmsg()); } iocb.ic_cmd = SIOCSARP; iocb.ic_timout = 0; iocb.ic_dp = (char *)&arpreq; iocb.ic_len = sizeof(arpreq); if (ioctl(fd, I_STR, (caddr_t)&iocb) < 0) { report(LOG_ERR, "ioctl I_STR: %s\n", get_errmsg()); } close (fd); } #else /* SVR4 */ /* * On SunOS, the ioctl sometimes returns ENXIO, and it * appears to happen when the ARP cache entry you tried * to add is already in the cache. (Sigh...) * XXX - Should this error simply be ignored? -gwr */ if (ioctl(s, SIOCSARP, (caddr_t) &arpreq) < 0) { report(LOG_ERR, "ioctl SIOCSARP: %s", get_errmsg()); } #endif /* SVR4 */ #else /* SIOCSARP */ #if defined(BSD) && (BSD >= 199306) bsd_arp_set(ia, haddr, halen); #else /* * Oh well, SIOCSARP is not defined. Just run arp(8). * Need to delete partial entry first on some systems. * XXX - Gag! */ int status; char buf[256]; char *a; extern char *inet_ntoa(); a = inet_ntoa(*ia); snprintf(buf, sizeof(buf), "arp -d %s; arp -s %s %s temp", a, a, haddrtoa(haddr, halen)); if (debug > 2) report(LOG_INFO, "%s", buf); status = system(buf); if (status) report(LOG_ERR, "arp failed, exit code=0x%x", status); return; #endif /* ! 4.4 BSD */ #endif /* SIOCSARP */ } /* * Convert a hardware address to an ASCII string. */ char * haddrtoa(haddr, hlen) u_char *haddr; int hlen; { static char haddrbuf[3 * MAXHADDRLEN + 1]; char *bufptr; if (hlen > MAXHADDRLEN) hlen = MAXHADDRLEN; bufptr = haddrbuf; while (hlen > 0) { sprintf(bufptr, "%02X:", (unsigned) (*haddr++ & 0xFF)); bufptr += 3; hlen--; } bufptr[-1] = 0; return (haddrbuf); } /* * haddr_conv802() * -------------- * * Converts a backwards address to a canonical address and a canonical address * to a backwards address. * * INPUTS: * adr_in - pointer to six byte string to convert (unsigned char *) * addr_len - how many bytes to convert * * OUTPUTS: * addr_out - The string is updated to contain the converted address. * * CALLER: * many * * DATA: * Uses conv802table to bit-reverse the address bytes. */ static u_char conv802table[256] = { /* 0x00 */ 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, /* 0x08 */ 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, /* 0x10 */ 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, /* 0x18 */ 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, /* 0x20 */ 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, /* 0x28 */ 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, /* 0x30 */ 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, /* 0x38 */ 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, /* 0x40 */ 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, /* 0x48 */ 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, /* 0x50 */ 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, /* 0x58 */ 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA, /* 0x60 */ 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, /* 0x68 */ 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, /* 0x70 */ 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, /* 0x78 */ 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, /* 0x80 */ 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, /* 0x88 */ 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1, /* 0x90 */ 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, /* 0x98 */ 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, /* 0xA0 */ 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, /* 0xA8 */ 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, /* 0xB0 */ 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, /* 0xB8 */ 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD, /* 0xC0 */ 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, /* 0xC8 */ 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, /* 0xD0 */ 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, /* 0xD8 */ 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, /* 0xE0 */ 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, /* 0xE8 */ 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, /* 0xF0 */ 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, /* 0xF8 */ 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF, }; void haddr_conv802(addr_in, addr_out, len) - register u_char *addr_in, *addr_out; + u_char *addr_in, *addr_out; int len; { u_char *lim; lim = addr_out + len; while (addr_out < lim) *addr_out++ = conv802table[*addr_in++]; } #if 0 /* * For the record, here is a program to generate the * bit-reverse table above. */ static int bitrev(n) int n; { int i, r; r = 0; for (i = 0; i < 8; i++) { r <<= 1; r |= (n & 1); n >>= 1; } return r; } main() { int i; for (i = 0; i <= 0xFF; i++) { if ((i & 7) == 0) printf("/* 0x%02X */", i); printf(" 0x%02X,", bitrev(i)); if ((i & 7) == 7) printf("\n"); } } #endif /* * Local Variables: * tab-width: 4 * c-indent-level: 4 * c-argdecl-indent: 4 * c-continued-statement-offset: 4 * c-continued-brace-offset: -4 * c-label-offset: -4 * c-brace-offset: 0 * End: */ Index: head/libexec/bootpd/readfile.c =================================================================== --- head/libexec/bootpd/readfile.c (revision 297864) +++ head/libexec/bootpd/readfile.c (revision 297865) @@ -1,2084 +1,2084 @@ /************************************************************************ Copyright 1988, 1991 by Carnegie Mellon University All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Carnegie Mellon University not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. $FreeBSD$ ************************************************************************/ /* * bootpd configuration file reading code. * * The routines in this file deal with reading, interpreting, and storing * the information found in the bootpd configuration file (usually * /etc/bootptab). */ #include #include #include #include #include #include #include #include #include #include #include #include #ifndef USE_BFUNCS #include /* Yes, memcpy is OK here (no overlapped copies). */ #define bcopy(a,b,c) memcpy(b,a,c) #define bzero(p,l) memset(p,0,l) #define bcmp(a,b,c) memcmp(a,b,c) #endif #include "bootp.h" #include "hash.h" #include "hwaddr.h" #include "lookup.h" #include "readfile.h" #include "report.h" #include "tzone.h" #include "bootpd.h" #define HASHTABLESIZE 257 /* Hash table size (prime) */ /* Non-standard hardware address type (see bootp.h) */ #define HTYPE_DIRECT 0 /* Error codes returned by eval_symbol: */ #define SUCCESS 0 #define E_END_OF_ENTRY (-1) #define E_SYNTAX_ERROR (-2) #define E_UNKNOWN_SYMBOL (-3) #define E_BAD_IPADDR (-4) #define E_BAD_HWADDR (-5) #define E_BAD_LONGWORD (-6) #define E_BAD_HWATYPE (-7) #define E_BAD_PATHNAME (-8) #define E_BAD_VALUE (-9) /* Tag idendities. */ #define SYM_NULL 0 #define SYM_BOOTFILE 1 #define SYM_COOKIE_SERVER 2 #define SYM_DOMAIN_SERVER 3 #define SYM_GATEWAY 4 #define SYM_HWADDR 5 #define SYM_HOMEDIR 6 #define SYM_HTYPE 7 #define SYM_IMPRESS_SERVER 8 #define SYM_IPADDR 9 #define SYM_LOG_SERVER 10 #define SYM_LPR_SERVER 11 #define SYM_NAME_SERVER 12 #define SYM_RLP_SERVER 13 #define SYM_SUBNET_MASK 14 #define SYM_TIME_OFFSET 15 #define SYM_TIME_SERVER 16 #define SYM_VENDOR_MAGIC 17 #define SYM_SIMILAR_ENTRY 18 #define SYM_NAME_SWITCH 19 #define SYM_BOOTSIZE 20 #define SYM_BOOT_SERVER 22 #define SYM_TFTPDIR 23 #define SYM_DUMP_FILE 24 #define SYM_DOMAIN_NAME 25 #define SYM_SWAP_SERVER 26 #define SYM_ROOT_PATH 27 #define SYM_EXTEN_FILE 28 #define SYM_REPLY_ADDR 29 #define SYM_NIS_DOMAIN 30 /* RFC 1533 */ #define SYM_NIS_SERVER 31 /* RFC 1533 */ #define SYM_NTP_SERVER 32 /* RFC 1533 */ #define SYM_EXEC_FILE 33 /* YORK_EX_OPTION */ #define SYM_MSG_SIZE 34 #define SYM_MIN_WAIT 35 /* XXX - Add new tags here */ #define OP_ADDITION 1 /* Operations on tags */ #define OP_DELETION 2 #define OP_BOOLEAN 3 #define MAXINADDRS 16 /* Max size of an IP address list */ #define MAXBUFLEN 256 /* Max temp buffer space */ #define MAXENTRYLEN 2048 /* Max size of an entire entry */ /* * Structure used to map a configuration-file symbol (such as "ds") to a * unique integer. */ struct symbolmap { char *symbol; int symbolcode; }; struct htypename { char *name; byte htype; }; PRIVATE int nhosts; /* Number of hosts (/w hw or IP address) */ PRIVATE int nentries; /* Total number of entries */ PRIVATE int32 modtime = 0; /* Last modification time of bootptab */ PRIVATE char *current_hostname; /* Name of the current entry. */ PRIVATE char current_tagname[8]; /* * List of symbolic names used in the bootptab file. The order and actual * values of the symbol codes (SYM_. . .) are unimportant, but they must * all be unique. */ PRIVATE struct symbolmap symbol_list[] = { {"bf", SYM_BOOTFILE}, {"bs", SYM_BOOTSIZE}, {"cs", SYM_COOKIE_SERVER}, {"df", SYM_DUMP_FILE}, {"dn", SYM_DOMAIN_NAME}, {"ds", SYM_DOMAIN_SERVER}, {"ef", SYM_EXTEN_FILE}, {"ex", SYM_EXEC_FILE}, /* YORK_EX_OPTION */ {"gw", SYM_GATEWAY}, {"ha", SYM_HWADDR}, {"hd", SYM_HOMEDIR}, {"hn", SYM_NAME_SWITCH}, {"ht", SYM_HTYPE}, {"im", SYM_IMPRESS_SERVER}, {"ip", SYM_IPADDR}, {"lg", SYM_LOG_SERVER}, {"lp", SYM_LPR_SERVER}, {"ms", SYM_MSG_SIZE}, {"mw", SYM_MIN_WAIT}, {"ns", SYM_NAME_SERVER}, {"nt", SYM_NTP_SERVER}, {"ra", SYM_REPLY_ADDR}, {"rl", SYM_RLP_SERVER}, {"rp", SYM_ROOT_PATH}, {"sa", SYM_BOOT_SERVER}, {"sm", SYM_SUBNET_MASK}, {"sw", SYM_SWAP_SERVER}, {"tc", SYM_SIMILAR_ENTRY}, {"td", SYM_TFTPDIR}, {"to", SYM_TIME_OFFSET}, {"ts", SYM_TIME_SERVER}, {"vm", SYM_VENDOR_MAGIC}, {"yd", SYM_NIS_DOMAIN}, {"ys", SYM_NIS_SERVER}, /* XXX - Add new tags here */ }; /* * List of symbolic names for hardware types. Name translates into * hardware type code listed with it. Names must begin with a letter * and must be all lowercase. This is searched linearly, so put * commonly-used entries near the beginning. */ PRIVATE struct htypename htnamemap[] = { {"ethernet", HTYPE_ETHERNET}, {"ethernet3", HTYPE_EXP_ETHERNET}, {"ether", HTYPE_ETHERNET}, {"ether3", HTYPE_EXP_ETHERNET}, {"ieee802", HTYPE_IEEE802}, {"tr", HTYPE_IEEE802}, {"token-ring", HTYPE_IEEE802}, {"pronet", HTYPE_PRONET}, {"chaos", HTYPE_CHAOS}, {"arcnet", HTYPE_ARCNET}, {"ax.25", HTYPE_AX25}, {"direct", HTYPE_DIRECT}, {"serial", HTYPE_DIRECT}, {"slip", HTYPE_DIRECT}, {"ppp", HTYPE_DIRECT} }; /* * Externals and forward declarations. */ extern boolean iplookcmp(); boolean nmcmp(hash_datum *, hash_datum *); PRIVATE void adjust(char **); PRIVATE void del_string(struct shared_string *); PRIVATE void del_bindata(struct shared_bindata *); PRIVATE void del_iplist(struct in_addr_list *); PRIVATE void eat_whitespace(char **); PRIVATE int eval_symbol(char **, struct host *); PRIVATE void fill_defaults(struct host *, char **); PRIVATE void free_host(hash_datum *); PRIVATE struct in_addr_list * get_addresses(char **); PRIVATE struct shared_string * get_shared_string(char **); PRIVATE char * get_string(char **, char *, u_int *); PRIVATE u_int32 get_u_long(char **); PRIVATE boolean goodname(char *); PRIVATE boolean hwinscmp(hash_datum *, hash_datum *); PRIVATE int interp_byte(char **, byte *); PRIVATE void makelower(char *); PRIVATE boolean nullcmp(hash_datum *, hash_datum *); PRIVATE int process_entry(struct host *, char *); PRIVATE int process_generic(char **, struct shared_bindata **, u_int); PRIVATE byte * prs_haddr(char **, u_int); PRIVATE int prs_inetaddr(char **, u_int32 *); PRIVATE void read_entry(FILE *, char *, u_int *); PRIVATE char * smalloc(u_int); /* * Vendor magic cookies for CMU and RFC1048 */ u_char vm_cmu[4] = VM_CMU; u_char vm_rfc1048[4] = VM_RFC1048; /* * Main hash tables */ hash_tbl *hwhashtable; hash_tbl *iphashtable; hash_tbl *nmhashtable; /* * Allocate hash tables for hardware address, ip address, and hostname * (shared by bootpd and bootpef) */ void rdtab_init() { hwhashtable = hash_Init(HASHTABLESIZE); iphashtable = hash_Init(HASHTABLESIZE); nmhashtable = hash_Init(HASHTABLESIZE); if (!(hwhashtable && iphashtable && nmhashtable)) { report(LOG_ERR, "Unable to allocate hash tables."); exit(1); } } /* * Read bootptab database file. Avoid rereading the file if the * write date hasn't changed since the last time we read it. */ void readtab(force) int force; { struct host *hp; FILE *fp; struct stat st; unsigned hashcode, buflen; static char buffer[MAXENTRYLEN]; /* * Check the last modification time. */ if (stat(bootptab, &st) < 0) { report(LOG_ERR, "stat on \"%s\": %s", bootptab, get_errmsg()); return; } #ifdef DEBUG if (debug > 3) { char timestr[28]; strcpy(timestr, ctime(&(st.st_mtime))); /* zap the newline */ timestr[24] = '\0'; report(LOG_INFO, "bootptab mtime: %s", timestr); } #endif if ((force == 0) && (st.st_mtime == modtime) && st.st_nlink) { /* * hasn't been modified or deleted yet. */ return; } if (debug) report(LOG_INFO, "reading %s\"%s\"", (modtime != 0L) ? "new " : "", bootptab); /* * Open bootptab file. */ if ((fp = fopen(bootptab, "r")) == NULL) { report(LOG_ERR, "error opening \"%s\": %s", bootptab, get_errmsg()); return; } /* * Record file modification time. */ if (fstat(fileno(fp), &st) < 0) { report(LOG_ERR, "fstat: %s", get_errmsg()); fclose(fp); return; } modtime = st.st_mtime; /* * Entirely erase all hash tables. */ hash_Reset(hwhashtable, free_host); hash_Reset(iphashtable, free_host); hash_Reset(nmhashtable, free_host); nhosts = 0; nentries = 0; while (TRUE) { buflen = sizeof(buffer); read_entry(fp, buffer, &buflen); if (buflen == 0) { /* More entries? */ break; } hp = (struct host *) smalloc(sizeof(struct host)); bzero((char *) hp, sizeof(*hp)); /* the link count it zero */ /* * Get individual info */ if (process_entry(hp, buffer) < 0) { hp->linkcount = 1; free_host((hash_datum *) hp); continue; } /* * If this is not a dummy entry, and the IP or HW * address is not yet set, try to get them here. * Dummy entries have . as first char of name. */ if (goodname(hp->hostname->string)) { char *hn = hp->hostname->string; u_int32 value; if (hp->flags.iaddr == 0) { if (lookup_ipa(hn, &value)) { report(LOG_ERR, "can not get IP addr for %s", hn); report(LOG_ERR, "(dummy names should start with '.')"); } else { hp->iaddr.s_addr = value; hp->flags.iaddr = TRUE; } } /* Set default subnet mask. */ if (hp->flags.subnet_mask == 0) { if (lookup_netmask(hp->iaddr.s_addr, &value)) { report(LOG_ERR, "can not get netmask for %s", hn); } else { hp->subnet_mask.s_addr = value; hp->flags.subnet_mask = TRUE; } } } if (hp->flags.iaddr) { nhosts++; } - /* Register by HW addr if known. */ + /* by HW addr if known. */ if (hp->flags.htype && hp->flags.haddr) { /* We will either insert it or free it. */ hp->linkcount++; hashcode = hash_HashFunction(hp->haddr, haddrlength(hp->htype)); if (hash_Insert(hwhashtable, hashcode, hwinscmp, hp, hp) < 0) { report(LOG_NOTICE, "duplicate %s address: %s", netname(hp->htype), haddrtoa(hp->haddr, haddrlength(hp->htype))); free_host((hash_datum *) hp); continue; } } - /* Register by IP addr if known. */ + /* by IP addr if known. */ if (hp->flags.iaddr) { hashcode = hash_HashFunction((u_char *) & (hp->iaddr.s_addr), 4); if (hash_Insert(iphashtable, hashcode, nullcmp, hp, hp) < 0) { report(LOG_ERR, "hash_Insert() failed on IP address insertion"); } else { /* Just inserted the host struct in a new hash list. */ hp->linkcount++; } } - /* Register by Name (always known) */ + /* by Name (always known) */ hashcode = hash_HashFunction((u_char *) hp->hostname->string, strlen(hp->hostname->string)); if (hash_Insert(nmhashtable, hashcode, nullcmp, hp->hostname->string, hp) < 0) { report(LOG_ERR, "hash_Insert() failed on insertion of hostname: \"%s\"", hp->hostname->string); } else { /* Just inserted the host struct in a new hash list. */ hp->linkcount++; } nentries++; } fclose(fp); if (debug) report(LOG_INFO, "read %d entries (%d hosts) from \"%s\"", nentries, nhosts, bootptab); return; } /* * Read an entire host entry from the file pointed to by "fp" and insert it * into the memory pointed to by "buffer". Leading whitespace and comments * starting with "#" are ignored (removed). Backslashes (\) always quote * the next character except that newlines preceded by a backslash cause * line-continuation onto the next line. The entry is terminated by a * newline character which is not preceded by a backslash. Sequences * surrounded by double quotes are taken literally (including newlines, but * not backslashes). * * The "bufsiz" parameter points to an unsigned int which specifies the * maximum permitted buffer size. Upon return, this value will be replaced * with the actual length of the entry (not including the null terminator). * * This code is a little scary. . . . I don't like using gotos in C * either, but I first wrote this as an FSM diagram and gotos seemed like * the easiest way to implement it. Maybe later I'll clean it up. */ PRIVATE void read_entry(fp, buffer, bufsiz) FILE *fp; char *buffer; unsigned *bufsiz; { int c, length; length = 0; /* * Eat whitespace, blank lines, and comment lines. */ top: c = fgetc(fp); if (c < 0) { goto done; /* Exit if end-of-file */ } if (isspace(c)) { goto top; /* Skip over whitespace */ } if (c == '#') { while (TRUE) { /* Eat comments after # */ c = fgetc(fp); if (c < 0) { goto done; /* Exit if end-of-file */ } if (c == '\n') { goto top; /* Try to read the next line */ } } } ungetc(c, fp); /* Other character, push it back to reprocess it */ /* * Now we're actually reading a data entry. Get each character and * assemble it into the data buffer, processing special characters like * double quotes (") and backslashes (\). */ mainloop: c = fgetc(fp); switch (c) { case EOF: case '\n': goto done; /* Exit on EOF or newline */ case '\\': c = fgetc(fp); /* Backslash, read a new character */ if (c < 0) { goto done; /* Exit on EOF */ } *buffer++ = c; /* Store the literal character */ length++; if (length < *bufsiz - 1) { goto mainloop; } else { goto done; } case '"': *buffer++ = '"'; /* Store double-quote */ length++; if (length >= *bufsiz - 1) { goto done; } while (TRUE) { /* Special quote processing loop */ c = fgetc(fp); switch (c) { case EOF: goto done; /* Exit on EOF . . . */ case '"': *buffer++ = '"';/* Store matching quote */ length++; if (length < *bufsiz - 1) { goto mainloop; /* And continue main loop */ } else { goto done; } case '\\': if ((c = fgetc(fp)) < 0) { /* Backslash */ goto done; /* EOF. . . .*/ } /* FALLTHROUGH */ default: *buffer++ = c; /* Other character, store it */ length++; if (length >= *bufsiz - 1) { goto done; } } } case ':': *buffer++ = c; /* Store colons */ length++; if (length >= *bufsiz - 1) { goto done; } do { /* But remove whitespace after them */ c = fgetc(fp); if ((c < 0) || (c == '\n')) { goto done; } } while (isspace(c)); /* Skip whitespace */ if (c == '\\') { /* Backslash quotes next character */ c = fgetc(fp); if (c < 0) { goto done; } if (c == '\n') { goto top; /* Backslash-newline continuation */ } } /* FALLTHROUGH if "other" character */ default: *buffer++ = c; /* Store other characters */ length++; if (length >= *bufsiz - 1) { goto done; } } goto mainloop; /* Keep going */ done: *buffer = '\0'; /* Terminate string */ *bufsiz = length; /* Tell the caller its length */ } /* * Parse out all the various tags and parameters in the host entry pointed * to by "src". Stuff all the data into the appropriate fields of the * host structure pointed to by "host". If there is any problem with the * entry, an error message is reported via report(), no further processing * is done, and -1 is returned. Successful calls return 0. * * (Some errors probably shouldn't be so completely fatal. . . .) */ PRIVATE int process_entry(host, src) struct host *host; char *src; { int retval; char *msg; if (!host || *src == '\0') { return -1; } host->hostname = get_shared_string(&src); #if 0 /* Be more liberal for the benefit of dummy tag names. */ if (!goodname(host->hostname->string)) { report(LOG_ERR, "bad hostname: \"%s\"", host->hostname->string); del_string(host->hostname); return -1; } #endif current_hostname = host->hostname->string; adjust(&src); while (TRUE) { retval = eval_symbol(&src, host); if (retval == SUCCESS) { adjust(&src); continue; } if (retval == E_END_OF_ENTRY) { /* The default subnet mask is set in readtab() */ return 0; } /* Some kind of error. */ switch (retval) { case E_SYNTAX_ERROR: msg = "bad syntax"; break; case E_UNKNOWN_SYMBOL: msg = "unknown symbol"; break; case E_BAD_IPADDR: msg = "bad INET address"; break; case E_BAD_HWADDR: msg = "bad hardware address"; break; case E_BAD_LONGWORD: msg = "bad longword value"; break; case E_BAD_HWATYPE: msg = "bad HW address type"; break; case E_BAD_PATHNAME: msg = "bad pathname (need leading '/')"; break; case E_BAD_VALUE: msg = "bad value"; break; default: msg = "unknown error"; break; } /* switch */ report(LOG_ERR, "in entry named \"%s\", symbol \"%s\": %s", current_hostname, current_tagname, msg); return -1; } } /* * Macros for use in the function below: */ /* Parse one INET address stored directly in MEMBER. */ #define PARSE_IA1(MEMBER) do \ { \ if (optype == OP_BOOLEAN) \ return E_SYNTAX_ERROR; \ hp->flags.MEMBER = FALSE; \ if (optype == OP_ADDITION) { \ if (prs_inetaddr(symbol, &value) < 0) \ return E_BAD_IPADDR; \ hp->MEMBER.s_addr = value; \ hp->flags.MEMBER = TRUE; \ } \ } while (0) /* Parse a list of INET addresses pointed to by MEMBER */ #define PARSE_IAL(MEMBER) do \ { \ if (optype == OP_BOOLEAN) \ return E_SYNTAX_ERROR; \ if (hp->flags.MEMBER) { \ hp->flags.MEMBER = FALSE; \ assert(hp->MEMBER); \ del_iplist(hp->MEMBER); \ hp->MEMBER = NULL; \ } \ if (optype == OP_ADDITION) { \ hp->MEMBER = get_addresses(symbol); \ if (hp->MEMBER == NULL) \ return E_SYNTAX_ERROR; \ hp->flags.MEMBER = TRUE; \ } \ } while (0) /* Parse a shared string pointed to by MEMBER */ #define PARSE_STR(MEMBER) do \ { \ if (optype == OP_BOOLEAN) \ return E_SYNTAX_ERROR; \ if (hp->flags.MEMBER) { \ hp->flags.MEMBER = FALSE; \ assert(hp->MEMBER); \ del_string(hp->MEMBER); \ hp->MEMBER = NULL; \ } \ if (optype == OP_ADDITION) { \ hp->MEMBER = get_shared_string(symbol); \ if (hp->MEMBER == NULL) \ return E_SYNTAX_ERROR; \ hp->flags.MEMBER = TRUE; \ } \ } while (0) /* Parse an unsigned integer value for MEMBER */ #define PARSE_UINT(MEMBER) do \ { \ if (optype == OP_BOOLEAN) \ return E_SYNTAX_ERROR; \ hp->flags.MEMBER = FALSE; \ if (optype == OP_ADDITION) { \ value = get_u_long(symbol); \ hp->MEMBER = value; \ hp->flags.MEMBER = TRUE; \ } \ } while (0) /* * Evaluate the two-character tag symbol pointed to by "symbol" and place * the data in the structure pointed to by "hp". The pointer pointed to * by "symbol" is updated to point past the source string (but may not * point to the next tag entry). * * Obviously, this need a few more comments. . . . */ PRIVATE int eval_symbol(symbol, hp) char **symbol; struct host *hp; { char tmpstr[MAXSTRINGLEN]; byte *tmphaddr; struct symbolmap *symbolptr; u_int32 value; int32 timeoff; int i, numsymbols; unsigned len; int optype; /* Indicates boolean, addition, or deletion */ eat_whitespace(symbol); /* Make sure this is set before returning. */ current_tagname[0] = (*symbol)[0]; current_tagname[1] = (*symbol)[1]; current_tagname[2] = 0; if ((*symbol)[0] == '\0') { return E_END_OF_ENTRY; } if ((*symbol)[0] == ':') { return SUCCESS; } if ((*symbol)[0] == 'T') { /* generic symbol */ (*symbol)++; value = get_u_long(symbol); snprintf(current_tagname, sizeof(current_tagname), "T%d", (int)value); eat_whitespace(symbol); if ((*symbol)[0] != '=') { return E_SYNTAX_ERROR; } (*symbol)++; if (!(hp->generic)) { hp->generic = (struct shared_bindata *) smalloc(sizeof(struct shared_bindata)); } if (process_generic(symbol, &(hp->generic), (byte) (value & 0xFF))) return E_SYNTAX_ERROR; hp->flags.generic = TRUE; return SUCCESS; } /* * Determine the type of operation to be done on this symbol */ switch ((*symbol)[2]) { case '=': optype = OP_ADDITION; break; case '@': optype = OP_DELETION; break; case ':': case '\0': optype = OP_BOOLEAN; break; default: return E_SYNTAX_ERROR; } symbolptr = symbol_list; numsymbols = sizeof(symbol_list) / sizeof(struct symbolmap); for (i = 0; i < numsymbols; i++) { if (((symbolptr->symbol)[0] == (*symbol)[0]) && ((symbolptr->symbol)[1] == (*symbol)[1])) { break; } symbolptr++; } if (i >= numsymbols) { return E_UNKNOWN_SYMBOL; } /* * Skip past the = or @ character (to point to the data) if this * isn't a boolean operation. For boolean operations, just skip * over the two-character tag symbol (and nothing else. . . .). */ (*symbol) += (optype == OP_BOOLEAN) ? 2 : 3; eat_whitespace(symbol); /* The cases below are in order by symbolcode value. */ switch (symbolptr->symbolcode) { case SYM_BOOTFILE: PARSE_STR(bootfile); break; case SYM_COOKIE_SERVER: PARSE_IAL(cookie_server); break; case SYM_DOMAIN_SERVER: PARSE_IAL(domain_server); break; case SYM_GATEWAY: PARSE_IAL(gateway); break; case SYM_HWADDR: if (optype == OP_BOOLEAN) return E_SYNTAX_ERROR; hp->flags.haddr = FALSE; if (optype == OP_ADDITION) { /* Default the HW type to Ethernet */ if (hp->flags.htype == 0) { hp->flags.htype = TRUE; hp->htype = HTYPE_ETHERNET; } tmphaddr = prs_haddr(symbol, hp->htype); if (!tmphaddr) return E_BAD_HWADDR; bcopy(tmphaddr, hp->haddr, haddrlength(hp->htype)); hp->flags.haddr = TRUE; } break; case SYM_HOMEDIR: PARSE_STR(homedir); break; case SYM_HTYPE: if (optype == OP_BOOLEAN) return E_SYNTAX_ERROR; hp->flags.htype = FALSE; if (optype == OP_ADDITION) { value = 0L; /* Assume an illegal value */ eat_whitespace(symbol); if (isdigit(**symbol)) { value = get_u_long(symbol); } else { len = sizeof(tmpstr); (void) get_string(symbol, tmpstr, &len); makelower(tmpstr); numsymbols = sizeof(htnamemap) / sizeof(struct htypename); for (i = 0; i < numsymbols; i++) { if (!strcmp(htnamemap[i].name, tmpstr)) { break; } } if (i < numsymbols) { value = htnamemap[i].htype; } } if (value >= hwinfocnt) { return E_BAD_HWATYPE; } hp->htype = (byte) (value & 0xFF); hp->flags.htype = TRUE; } break; case SYM_IMPRESS_SERVER: PARSE_IAL(impress_server); break; case SYM_IPADDR: PARSE_IA1(iaddr); break; case SYM_LOG_SERVER: PARSE_IAL(log_server); break; case SYM_LPR_SERVER: PARSE_IAL(lpr_server); break; case SYM_NAME_SERVER: PARSE_IAL(name_server); break; case SYM_RLP_SERVER: PARSE_IAL(rlp_server); break; case SYM_SUBNET_MASK: PARSE_IA1(subnet_mask); break; case SYM_TIME_OFFSET: if (optype == OP_BOOLEAN) return E_SYNTAX_ERROR; hp->flags.time_offset = FALSE; if (optype == OP_ADDITION) { len = sizeof(tmpstr); (void) get_string(symbol, tmpstr, &len); if (!strncmp(tmpstr, "auto", 4)) { hp->time_offset = secondswest; } else { if (sscanf(tmpstr, "%d", (int*)&timeoff) != 1) return E_BAD_LONGWORD; hp->time_offset = timeoff; } hp->flags.time_offset = TRUE; } break; case SYM_TIME_SERVER: PARSE_IAL(time_server); break; case SYM_VENDOR_MAGIC: if (optype == OP_BOOLEAN) return E_SYNTAX_ERROR; hp->flags.vm_cookie = FALSE; if (optype == OP_ADDITION) { if (strncmp(*symbol, "auto", 4)) { /* The string is not "auto" */ if (!strncmp(*symbol, "rfc", 3)) { bcopy(vm_rfc1048, hp->vm_cookie, 4); } else if (!strncmp(*symbol, "cmu", 3)) { bcopy(vm_cmu, hp->vm_cookie, 4); } else { if (!isdigit(**symbol)) return E_BAD_IPADDR; if (prs_inetaddr(symbol, &value) < 0) return E_BAD_IPADDR; bcopy(&value, hp->vm_cookie, 4); } hp->flags.vm_cookie = TRUE; } } break; case SYM_SIMILAR_ENTRY: switch (optype) { case OP_ADDITION: fill_defaults(hp, symbol); break; default: return E_SYNTAX_ERROR; } break; case SYM_NAME_SWITCH: switch (optype) { case OP_ADDITION: return E_SYNTAX_ERROR; case OP_DELETION: hp->flags.send_name = FALSE; hp->flags.name_switch = FALSE; break; case OP_BOOLEAN: hp->flags.send_name = TRUE; hp->flags.name_switch = TRUE; break; } break; case SYM_BOOTSIZE: switch (optype) { case OP_ADDITION: if (!strncmp(*symbol, "auto", 4)) { hp->flags.bootsize = TRUE; hp->flags.bootsize_auto = TRUE; } else { hp->bootsize = (unsigned int) get_u_long(symbol); hp->flags.bootsize = TRUE; hp->flags.bootsize_auto = FALSE; } break; case OP_DELETION: hp->flags.bootsize = FALSE; break; case OP_BOOLEAN: hp->flags.bootsize = TRUE; hp->flags.bootsize_auto = TRUE; break; } break; case SYM_BOOT_SERVER: PARSE_IA1(bootserver); break; case SYM_TFTPDIR: PARSE_STR(tftpdir); if ((hp->tftpdir != NULL) && (hp->tftpdir->string[0] != '/')) return E_BAD_PATHNAME; break; case SYM_DUMP_FILE: PARSE_STR(dump_file); break; case SYM_DOMAIN_NAME: PARSE_STR(domain_name); break; case SYM_SWAP_SERVER: PARSE_IA1(swap_server); break; case SYM_ROOT_PATH: PARSE_STR(root_path); break; case SYM_EXTEN_FILE: PARSE_STR(exten_file); break; case SYM_REPLY_ADDR: PARSE_IA1(reply_addr); break; case SYM_NIS_DOMAIN: PARSE_STR(nis_domain); break; case SYM_NIS_SERVER: PARSE_IAL(nis_server); break; case SYM_NTP_SERVER: PARSE_IAL(ntp_server); break; #ifdef YORK_EX_OPTION case SYM_EXEC_FILE: PARSE_STR(exec_file); break; #endif case SYM_MSG_SIZE: PARSE_UINT(msg_size); if (hp->msg_size < BP_MINPKTSZ || hp->msg_size > MAX_MSG_SIZE) return E_BAD_VALUE; break; case SYM_MIN_WAIT: PARSE_UINT(min_wait); break; /* XXX - Add new tags here */ default: return E_UNKNOWN_SYMBOL; } /* switch symbolcode */ return SUCCESS; } #undef PARSE_IA1 #undef PARSE_IAL #undef PARSE_STR /* * Read a string from the buffer indirectly pointed to through "src" and * move it into the buffer pointed to by "dest". A pointer to the maximum * allowable length of the string (including null-terminator) is passed as * "length". The actual length of the string which was read is returned in * the unsigned integer pointed to by "length". This value is the same as * that which would be returned by applying the strlen() function on the * destination string (i.e the terminating null is not counted as a * character). Trailing whitespace is removed from the string. For * convenience, the function returns the new value of "dest". * * The string is read until the maximum number of characters, an unquoted * colon (:), or a null character is read. The return string in "dest" is * null-terminated. */ PRIVATE char * get_string(src, dest, length) char **src, *dest; unsigned *length; { int n, len, quoteflag; quoteflag = FALSE; n = 0; len = *length - 1; while ((n < len) && (**src)) { if (!quoteflag && (**src == ':')) { break; } if (**src == '"') { (*src)++; quoteflag = !quoteflag; continue; } if (**src == '\\') { (*src)++; if (!**src) { break; } } *dest++ = *(*src)++; n++; } /* * Remove that troublesome trailing whitespace. . . */ while ((n > 0) && isspace(dest[-1])) { dest--; n--; } *dest = '\0'; *length = n; return dest; } /* * Read the string indirectly pointed to by "src", update the caller's * pointer, and return a pointer to a malloc'ed shared_string structure * containing the string. * * The string is read using the same rules as get_string() above. */ PRIVATE struct shared_string * get_shared_string(src) char **src; { char retstring[MAXSTRINGLEN]; struct shared_string *s; unsigned length; length = sizeof(retstring); (void) get_string(src, retstring, &length); s = (struct shared_string *) smalloc(sizeof(struct shared_string) + length); s->linkcount = 1; strcpy(s->string, retstring); return s; } /* * Load RFC1048 generic information directly into a memory buffer. * * "src" indirectly points to the ASCII representation of the generic data. * "dest" points to a string structure which is updated to point to a new * string with the new data appended to the old string. The old string is * freed. * * The given tag value is inserted with the new data. * * The data may be represented as either a stream of hexadecimal numbers * representing bytes (any or all bytes may optionally start with '0x' and * be separated with periods ".") or as a quoted string of ASCII * characters (the quotes are required). */ PRIVATE int process_generic(src, dest, tagvalue) char **src; struct shared_bindata **dest; u_int tagvalue; { byte tmpbuf[MAXBUFLEN]; byte *str; struct shared_bindata *bdata; u_int newlength, oldlength; str = tmpbuf; *str++ = (tagvalue & 0xFF); /* Store tag value */ str++; /* Skip over length field */ if ((*src)[0] == '"') { /* ASCII data */ newlength = sizeof(tmpbuf) - 2; /* Set maximum allowed length */ (void) get_string(src, (char *) str, &newlength); newlength++; /* null terminator */ } else { /* Numeric data */ newlength = 0; while (newlength < sizeof(tmpbuf) - 2) { if (interp_byte(src, str++) < 0) break; newlength++; if (**src == '.') { (*src)++; } } } if ((*src)[0] != ':') return -1; tmpbuf[1] = (newlength & 0xFF); oldlength = ((*dest)->length); bdata = (struct shared_bindata *) smalloc(sizeof(struct shared_bindata) + oldlength + newlength + 1); if (oldlength > 0) { bcopy((*dest)->data, bdata->data, oldlength); } bcopy(tmpbuf, bdata->data + oldlength, newlength + 2); bdata->length = oldlength + newlength + 2; bdata->linkcount = 1; if (*dest) { del_bindata(*dest); } *dest = bdata; return 0; } /* * Verify that the given string makes sense as a hostname (according to * Appendix 1, page 29 of RFC882). * * Return TRUE for good names, FALSE otherwise. */ PRIVATE boolean goodname(hostname) - register char *hostname; + char *hostname; { do { if (!isalpha(*hostname++)) { /* First character must be a letter */ return FALSE; } while (isalnum(*hostname) || (*hostname == '-') || (*hostname == '_') ) { hostname++; /* Alphanumeric or a hyphen */ } if (!isalnum(hostname[-1])) { /* Last must be alphanumeric */ return FALSE; } if (*hostname == '\0') {/* Done? */ return TRUE; } } while (*hostname++ == '.'); /* Dot, loop for next label */ return FALSE; /* If it's not a dot, lose */ } /* * Null compare function -- always returns FALSE so an element is always * inserted into a hash table (i.e. there is never a collision with an * existing element). */ PRIVATE boolean nullcmp(d1, d2) hash_datum *d1, *d2; { return FALSE; } /* * Function for comparing a string with the hostname field of a host * structure. */ boolean nmcmp(d1, d2) hash_datum *d1, *d2; { char *name = (char *) d1; /* XXX - OK? */ struct host *hp = (struct host *) d2; return !strcmp(name, hp->hostname->string); } /* * Compare function to determine whether two hardware addresses are * equivalent. Returns TRUE if "host1" and "host2" are equivalent, FALSE * otherwise. * * If the hardware addresses of "host1" and "host2" are identical, but * they are on different IP subnets, this function returns FALSE. * * This function is used when inserting elements into the hardware address * hash table. */ PRIVATE boolean hwinscmp(d1, d2) hash_datum *d1, *d2; { struct host *host1 = (struct host *) d1; struct host *host2 = (struct host *) d2; if (host1->htype != host2->htype) { return FALSE; } if (bcmp(host1->haddr, host2->haddr, haddrlength(host1->htype))) { return FALSE; } /* XXX - Is the subnet_mask field set yet? */ if ((host1->subnet_mask.s_addr) == (host2->subnet_mask.s_addr)) { if (((host1->iaddr.s_addr) & (host1->subnet_mask.s_addr)) != ((host2->iaddr.s_addr) & (host2->subnet_mask.s_addr))) { return FALSE; } } return TRUE; } /* * Macros for use in the function below: */ #define DUP_COPY(MEMBER) do \ { \ if (!hp->flags.MEMBER) { \ if ((hp->flags.MEMBER = hp2->flags.MEMBER) != 0) { \ hp->MEMBER = hp2->MEMBER; \ } \ } \ } while (0) #define DUP_LINK(MEMBER) do \ { \ if (!hp->flags.MEMBER) { \ if ((hp->flags.MEMBER = hp2->flags.MEMBER) != 0) { \ assert(hp2->MEMBER); \ hp->MEMBER = hp2->MEMBER; \ (hp->MEMBER->linkcount)++; \ } \ } \ } while (0) /* * Process the "similar entry" symbol. * * The host specified as the value of the "tc" symbol is used as a template * for the current host entry. Symbol values not explicitly set in the * current host entry are inferred from the template entry. */ PRIVATE void fill_defaults(hp, src) struct host *hp; char **src; { unsigned int tlen, hashcode; struct host *hp2; char tstring[MAXSTRINGLEN]; tlen = sizeof(tstring); (void) get_string(src, tstring, &tlen); hashcode = hash_HashFunction((u_char *) tstring, tlen); hp2 = (struct host *) hash_Lookup(nmhashtable, hashcode, nmcmp, tstring); if (hp2 == NULL) { report(LOG_ERR, "can't find tc=\"%s\"", tstring); return; } DUP_LINK(bootfile); DUP_LINK(cookie_server); DUP_LINK(domain_server); DUP_LINK(gateway); /* haddr not copied */ DUP_LINK(homedir); DUP_COPY(htype); DUP_LINK(impress_server); /* iaddr not copied */ DUP_LINK(log_server); DUP_LINK(lpr_server); DUP_LINK(name_server); DUP_LINK(rlp_server); DUP_COPY(subnet_mask); DUP_COPY(time_offset); DUP_LINK(time_server); if (!hp->flags.vm_cookie) { if ((hp->flags.vm_cookie = hp2->flags.vm_cookie)) { bcopy(hp2->vm_cookie, hp->vm_cookie, 4); } } if (!hp->flags.name_switch) { if ((hp->flags.name_switch = hp2->flags.name_switch)) { hp->flags.send_name = hp2->flags.send_name; } } if (!hp->flags.bootsize) { if ((hp->flags.bootsize = hp2->flags.bootsize)) { hp->flags.bootsize_auto = hp2->flags.bootsize_auto; hp->bootsize = hp2->bootsize; } } DUP_COPY(bootserver); DUP_LINK(tftpdir); DUP_LINK(dump_file); DUP_LINK(domain_name); DUP_COPY(swap_server); DUP_LINK(root_path); DUP_LINK(exten_file); DUP_COPY(reply_addr); DUP_LINK(nis_domain); DUP_LINK(nis_server); DUP_LINK(ntp_server); #ifdef YORK_EX_OPTION DUP_LINK(exec_file); #endif DUP_COPY(msg_size); DUP_COPY(min_wait); /* XXX - Add new tags here */ DUP_LINK(generic); } #undef DUP_COPY #undef DUP_LINK /* * This function adjusts the caller's pointer to point just past the * first-encountered colon. If it runs into a null character, it leaves * the pointer pointing to it. */ PRIVATE void adjust(s) char **s; { - register char *t; + char *t; t = *s; while (*t && (*t != ':')) { t++; } if (*t) { t++; } *s = t; } /* * This function adjusts the caller's pointer to point to the first * non-whitespace character. If it runs into a null character, it leaves * the pointer pointing to it. */ PRIVATE void eat_whitespace(s) char **s; { - register char *t; + char *t; t = *s; while (*t && isspace(*t)) { t++; } *s = t; } /* * This function converts the given string to all lowercase. */ PRIVATE void makelower(s) char *s; { while (*s) { if (isupper(*s)) { *s = tolower(*s); } s++; } } /* * * N O T E : * * In many of the functions which follow, a parameter such as "src" or * "symbol" is passed as a pointer to a pointer to something. This is * done for the purpose of letting the called function update the * caller's copy of the parameter (i.e. to effect call-by-reference * parameter passing). The value of the actual parameter is only used * to locate the real parameter of interest and then update this indirect * parameter. * * I'm sure somebody out there won't like this. . . . * (Yea, because it usually makes code slower... -gwr) * */ /* * "src" points to a character pointer which points to an ASCII string of * whitespace-separated IP addresses. A pointer to an in_addr_list * structure containing the list of addresses is returned. NULL is * returned if no addresses were found at all. The pointer pointed to by * "src" is updated to point to the first non-address (illegal) character. */ PRIVATE struct in_addr_list * get_addresses(src) char **src; { struct in_addr tmpaddrlist[MAXINADDRS]; struct in_addr *address1, *address2; struct in_addr_list *result; unsigned addrcount, totalsize; address1 = tmpaddrlist; for (addrcount = 0; addrcount < MAXINADDRS; addrcount++) { while (isspace(**src) || (**src == ',')) { (*src)++; } if (!**src) { /* Quit if nothing more */ break; } if (prs_inetaddr(src, &(address1->s_addr)) < 0) { break; } address1++; /* Point to next address slot */ } if (addrcount < 1) { result = NULL; } else { totalsize = sizeof(struct in_addr_list) + (addrcount - 1) * sizeof(struct in_addr); result = (struct in_addr_list *) smalloc(totalsize); result->linkcount = 1; result->addrcount = addrcount; address1 = tmpaddrlist; address2 = result->addr; for (; addrcount > 0; addrcount--) { address2->s_addr = address1->s_addr; address1++; address2++; } } return result; } /* * prs_inetaddr(src, result) * * "src" is a value-result parameter; the pointer it points to is updated * to point to the next data position. "result" points to an unsigned long * in which an address is returned. * * This function parses the IP address string in ASCII "dot notation" pointed * to by (*src) and places the result (in network byte order) in the unsigned * long pointed to by "result". For malformed addresses, -1 is returned, * (*src) points to the first illegal character, and the unsigned long pointed * to by "result" is unchanged. Successful calls return 0. */ PRIVATE int prs_inetaddr(src, result) char **src; u_int32 *result; { char tmpstr[MAXSTRINGLEN]; - register u_int32 value; + u_int32 value; u_int32 parts[4], *pp; int n; char *s, *t; /* Leading alpha char causes IP addr lookup. */ if (isalpha(**src)) { /* Lookup IP address. */ s = *src; t = tmpstr; while ((isalnum(*s) || (*s == '.') || (*s == '-') || (*s == '_') ) && (t < &tmpstr[MAXSTRINGLEN - 1]) ) *t++ = *s++; *t = '\0'; *src = s; n = lookup_ipa(tmpstr, result); if (n < 0) report(LOG_ERR, "can not get IP addr for %s", tmpstr); return n; } /* * Parse an address in Internet format: * a.b.c.d * a.b.c (with c treated as 16-bits) * a.b (with b treated as 24 bits) */ pp = parts; loop: /* If it's not a digit, return error. */ if (!isdigit(**src)) return -1; *pp++ = get_u_long(src); if (**src == '.') { if (pp < (parts + 4)) { (*src)++; goto loop; } return (-1); } #if 0 /* This is handled by the caller. */ if (**src && !(isspace(**src) || (**src == ':'))) { return (-1); } #endif /* * Construct the address according to * the number of parts specified. */ n = pp - parts; switch (n) { case 1: /* a -- 32 bits */ value = parts[0]; break; case 2: /* a.b -- 8.24 bits */ value = (parts[0] << 24) | (parts[1] & 0xFFFFFF); break; case 3: /* a.b.c -- 8.8.16 bits */ value = (parts[0] << 24) | ((parts[1] & 0xFF) << 16) | (parts[2] & 0xFFFF); break; case 4: /* a.b.c.d -- 8.8.8.8 bits */ value = (parts[0] << 24) | ((parts[1] & 0xFF) << 16) | ((parts[2] & 0xFF) << 8) | (parts[3] & 0xFF); break; default: return (-1); } *result = htonl(value); return (0); } /* * "src" points to a pointer which in turn points to a hexadecimal ASCII * string. This string is interpreted as a hardware address and returned * as a pointer to the actual hardware address, represented as an array of * bytes. * * The ASCII string must have the proper number of digits for the specified * hardware type (e.g. twelve digits for a 48-bit Ethernet address). * Two-digit sequences (bytes) may be separated with periods (.) and/or * prefixed with '0x' for readability, but this is not required. * * For bad addresses, the pointer which "src" points to is updated to point * to the start of the first two-digit sequence which was bad, and the * function returns a NULL pointer. */ PRIVATE byte * prs_haddr(src, htype) char **src; u_int htype; { static byte haddr[MAXHADDRLEN]; byte *hap; char tmpstr[MAXSTRINGLEN]; u_int tmplen; unsigned hal; char *p; hal = haddrlength(htype); /* Get length of this address type */ if (hal <= 0) { report(LOG_ERR, "Invalid addr type for HW addr parse"); return NULL; } tmplen = sizeof(tmpstr); get_string(src, tmpstr, &tmplen); p = tmpstr; /* If it's a valid host name, try to lookup the HW address. */ if (goodname(p)) { /* Lookup Hardware Address for hostname. */ if ((hap = lookup_hwa(p, htype)) != NULL) return hap; /* success */ report(LOG_ERR, "Add 0x prefix if hex value starts with A-F"); /* OK, assume it must be numeric. */ } hap = haddr; while (hap < haddr + hal) { if ((*p == '.') || (*p == ':')) p++; if (interp_byte(&p, hap++) < 0) { return NULL; } } return haddr; } /* * "src" is a pointer to a character pointer which in turn points to a * hexadecimal ASCII representation of a byte. This byte is read, the * character pointer is updated, and the result is deposited into the * byte pointed to by "retbyte". * * The usual '0x' notation is allowed but not required. The number must be * a two digit hexadecimal number. If the number is invalid, "src" and * "retbyte" are left untouched and -1 is returned as the function value. * Successful calls return 0. */ PRIVATE int interp_byte(src, retbyte) char **src; byte *retbyte; { int v; if ((*src)[0] == '0' && ((*src)[1] == 'x' || (*src)[1] == 'X')) { (*src) += 2; /* allow 0x for hex, but don't require it */ } if (!isxdigit((*src)[0]) || !isxdigit((*src)[1])) { return -1; } if (sscanf(*src, "%2x", &v) != 1) { return -1; } (*src) += 2; *retbyte = (byte) (v & 0xFF); return 0; } /* * The parameter "src" points to a character pointer which points to an * ASCII string representation of an unsigned number. The number is * returned as an unsigned long and the character pointer is updated to * point to the first illegal character. */ PRIVATE u_int32 get_u_long(src) char **src; { - register u_int32 value, base; + u_int32 value, base; char c; /* * Collect number up to first illegal character. Values are specified * as for C: 0x=hex, 0=octal, other=decimal. */ value = 0; base = 10; if (**src == '0') { base = 8; (*src)++; } if (**src == 'x' || **src == 'X') { base = 16; (*src)++; } while ((c = **src)) { if (isdigit(c)) { value = (value * base) + (c - '0'); (*src)++; continue; } if (base == 16 && isxdigit(c)) { value = (value << 4) + ((c & ~32) + 10 - 'A'); (*src)++; continue; } break; } return value; } /* * Routines for deletion of data associated with the main data structure. */ /* * Frees the entire host data structure given. Does nothing if the passed * pointer is NULL. */ PRIVATE void free_host(hmp) hash_datum *hmp; { struct host *hostptr = (struct host *) hmp; if (hostptr == NULL) return; assert(hostptr->linkcount > 0); if (--(hostptr->linkcount)) return; /* Still has references */ del_iplist(hostptr->cookie_server); del_iplist(hostptr->domain_server); del_iplist(hostptr->gateway); del_iplist(hostptr->impress_server); del_iplist(hostptr->log_server); del_iplist(hostptr->lpr_server); del_iplist(hostptr->name_server); del_iplist(hostptr->rlp_server); del_iplist(hostptr->time_server); del_iplist(hostptr->nis_server); del_iplist(hostptr->ntp_server); /* * XXX - Add new tags here * (if the value is an IP list) */ del_string(hostptr->hostname); del_string(hostptr->homedir); del_string(hostptr->bootfile); del_string(hostptr->tftpdir); del_string(hostptr->root_path); del_string(hostptr->domain_name); del_string(hostptr->dump_file); del_string(hostptr->exten_file); del_string(hostptr->nis_domain); #ifdef YORK_EX_OPTION del_string(hostptr->exec_file); #endif /* * XXX - Add new tags here * (if it is a shared string) */ del_bindata(hostptr->generic); free((char *) hostptr); } /* * Decrements the linkcount on the given IP address data structure. If the * linkcount goes to zero, the memory associated with the data is freed. */ PRIVATE void del_iplist(iplist) struct in_addr_list *iplist; { if (iplist) { if (!(--(iplist->linkcount))) { free((char *) iplist); } } } /* * Decrements the linkcount on a string data structure. If the count * goes to zero, the memory associated with the string is freed. Does * nothing if the passed pointer is NULL. */ PRIVATE void del_string(stringptr) struct shared_string *stringptr; { if (stringptr) { if (!(--(stringptr->linkcount))) { free((char *) stringptr); } } } /* * Decrements the linkcount on a shared_bindata data structure. If the * count goes to zero, the memory associated with the data is freed. Does * nothing if the passed pointer is NULL. */ PRIVATE void del_bindata(dataptr) struct shared_bindata *dataptr; { if (dataptr) { if (!(--(dataptr->linkcount))) { free((char *) dataptr); } } } /* smalloc() -- safe malloc() * * Always returns a valid pointer (if it returns at all). The allocated * memory is initialized to all zeros. If malloc() returns an error, a * message is printed using the report() function and the program aborts * with a status of 1. */ PRIVATE char * smalloc(nbytes) unsigned nbytes; { char *retvalue; retvalue = malloc(nbytes); if (!retvalue) { report(LOG_ERR, "malloc() failure -- exiting"); exit(1); } bzero(retvalue, nbytes); return retvalue; } /* * Compare function to determine whether two hardware addresses are * equivalent. Returns TRUE if "host1" and "host2" are equivalent, FALSE * otherwise. * * This function is used when retrieving elements from the hardware address * hash table. */ boolean hwlookcmp(d1, d2) hash_datum *d1, *d2; { struct host *host1 = (struct host *) d1; struct host *host2 = (struct host *) d2; if (host1->htype != host2->htype) { return FALSE; } if (bcmp(host1->haddr, host2->haddr, haddrlength(host1->htype))) { return FALSE; } return TRUE; } /* * Compare function for doing IP address hash table lookup. */ boolean iplookcmp(d1, d2) hash_datum *d1, *d2; { struct host *host1 = (struct host *) d1; struct host *host2 = (struct host *) d2; return (host1->iaddr.s_addr == host2->iaddr.s_addr); } /* * Local Variables: * tab-width: 4 * c-indent-level: 4 * c-argdecl-indent: 4 * c-continued-statement-offset: 4 * c-continued-brace-offset: -4 * c-label-offset: -4 * c-brace-offset: 0 * End: */ Index: head/libexec/bootpd/rtmsg.c =================================================================== --- head/libexec/bootpd/rtmsg.c (revision 297864) +++ head/libexec/bootpd/rtmsg.c (revision 297865) @@ -1,239 +1,239 @@ /* * Copyright (c) 1984, 1993 * The Regents of the University of California. All rights reserved. * Copyright (c) 1994 * Geoffrey M. Rehmet, All rights reserved. * * This code is derived from software which forms part of the 4.4-Lite * Berkeley software distribution, which was in derived from software * contributed to Berkeley by Sun Microsystems, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * from arp.c 8.2 (Berkeley) 1/2/94 */ #include __FBSDID("$FreeBSD$"); #include /* * Verify that we are at least 4.4 BSD */ #if defined(BSD) #if BSD >= 199306 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "report.h" static int rtmsg(int); static int s = -1; /* routing socket */ /* * Open the routing socket */ static void getsocket () { if (s < 0) { s = socket(PF_ROUTE, SOCK_RAW, 0); if (s < 0) { report(LOG_ERR, "socket %s", strerror(errno)); exit(1); } } else { /* * Drain the socket of any unwanted routing messages. */ int n; char buf[512]; ioctl(s, FIONREAD, &n); while (n > 0) { read(s, buf, sizeof buf); ioctl(s, FIONREAD, &n); } } } static struct sockaddr_in so_mask = {8, 0, 0, { 0xffffffff}}; static struct sockaddr_in blank_sin = {sizeof(blank_sin), AF_INET }, sin_m; static struct sockaddr_dl blank_sdl = {sizeof(blank_sdl), AF_LINK }, sdl_m; static int expire_time, flags, doing_proxy; static struct { struct rt_msghdr m_rtm; char m_space[512]; } m_rtmsg; /* * Set an individual arp entry */ int bsd_arp_set(ia, eaddr, len) struct in_addr *ia; char *eaddr; int len; { - register struct sockaddr_in *sin = &sin_m; - register struct sockaddr_dl *sdl; - register struct rt_msghdr *rtm = &(m_rtmsg.m_rtm); + struct sockaddr_in *sin = &sin_m; + struct sockaddr_dl *sdl; + struct rt_msghdr *rtm = &(m_rtmsg.m_rtm); u_char *ea; struct timespec tp; int op = RTM_ADD; getsocket(); sdl_m = blank_sdl; sin_m = blank_sin; sin->sin_addr = *ia; ea = (u_char *)LLADDR(&sdl_m); bcopy(eaddr, ea, len); sdl_m.sdl_alen = len; doing_proxy = flags = expire_time = 0; /* make arp entry temporary */ clock_gettime(CLOCK_MONOTONIC, &tp); expire_time = tp.tv_sec + 20 * 60; tryagain: if (rtmsg(RTM_GET) < 0) { report(LOG_WARNING, "rtmget: %s", strerror(errno)); return (1); } sin = (struct sockaddr_in *)(rtm + 1); sdl = (struct sockaddr_dl *)(sin->sin_len + (char *)sin); if (sin->sin_addr.s_addr == sin_m.sin_addr.s_addr) { if (sdl->sdl_family == AF_LINK && !(rtm->rtm_flags & RTF_GATEWAY)) switch (sdl->sdl_type) { case IFT_ETHER: case IFT_FDDI: case IFT_ISO88023: case IFT_ISO88024: case IFT_ISO88025: op = RTM_CHANGE; goto overwrite; } if (doing_proxy == 0) { report(LOG_WARNING, "set: can only proxy for %s\n", inet_ntoa(sin->sin_addr)); return (1); } goto tryagain; } overwrite: if (sdl->sdl_family != AF_LINK) { report(LOG_WARNING, "cannot intuit interface index and type for %s\n", inet_ntoa(sin->sin_addr)); return (1); } sdl_m.sdl_type = sdl->sdl_type; sdl_m.sdl_index = sdl->sdl_index; return (rtmsg(op)); } static int rtmsg(cmd) int cmd; { static int seq; int rlen; - register struct rt_msghdr *rtm = &m_rtmsg.m_rtm; - register char *cp = m_rtmsg.m_space; - register int l; + struct rt_msghdr *rtm = &m_rtmsg.m_rtm; + char *cp = m_rtmsg.m_space; + int l; errno = 0; bzero((char *)&m_rtmsg, sizeof(m_rtmsg)); rtm->rtm_flags = flags; rtm->rtm_version = RTM_VERSION; switch (cmd) { default: report(LOG_ERR, "set_arp: internal wrong cmd - exiting"); exit(1); case RTM_ADD: case RTM_CHANGE: rtm->rtm_addrs |= RTA_GATEWAY; rtm->rtm_rmx.rmx_expire = expire_time; rtm->rtm_inits = RTV_EXPIRE; rtm->rtm_flags |= (RTF_HOST | RTF_STATIC | RTF_LLDATA); if (doing_proxy) { rtm->rtm_addrs |= RTA_NETMASK; rtm->rtm_flags &= ~RTF_HOST; } /* FALLTHROUGH */ case RTM_GET: rtm->rtm_addrs |= RTA_DST; } #define NEXTADDR(w, s) \ if (rtm->rtm_addrs & (w)) { \ bcopy((char *)&s, cp, sizeof(s)); cp += sizeof(s);} NEXTADDR(RTA_DST, sin_m); NEXTADDR(RTA_GATEWAY, sdl_m); NEXTADDR(RTA_NETMASK, so_mask); rtm->rtm_msglen = cp - (char *)&m_rtmsg; l = rtm->rtm_msglen; rtm->rtm_seq = ++seq; rtm->rtm_type = cmd; if ((rlen = write(s, (char *)&m_rtmsg, l)) < 0) { if ((errno != ESRCH) && !(errno == EEXIST && cmd == RTM_ADD)){ report(LOG_WARNING, "writing to routing socket: %s", strerror(errno)); return (-1); } } do { l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg)); } while (l > 0 && (rtm->rtm_type != cmd || rtm->rtm_seq != seq || rtm->rtm_pid != getpid())); if (l < 0) report(LOG_WARNING, "arp: read from routing socket: %s\n", strerror(errno)); return (0); } #endif /* BSD */ #endif /* BSD >= 199306 */ Index: head/libexec/bootpd/tools/bootptest/bootptest.c =================================================================== --- head/libexec/bootpd/tools/bootptest/bootptest.c (revision 297864) +++ head/libexec/bootpd/tools/bootptest/bootptest.c (revision 297865) @@ -1,520 +1,520 @@ /* * bootptest.c - Test out a bootp server. * * This simple program was put together from pieces taken from * various places, including the CMU BOOTP client and server. * The packet printing routine is from the Berkeley "tcpdump" * program with some enhancements I added. The print-bootp.c * file was shared with my copy of "tcpdump" and therefore uses * some unusual utility routines that would normally be provided * by various parts of the tcpdump program. Gordon W. Ross * * Boilerplate: * * This program includes software developed by the University of * California, Lawrence Berkeley Laboratory and its contributors. * (See the copyright notice in print-bootp.c) * * The remainder of this program is public domain. You may do * whatever you like with it except claim that you wrote it. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * HISTORY: * * 12/02/93 Released version 1.4 (with bootp-2.3.2) * 11/05/93 Released version 1.3 * 10/14/93 Released version 1.2 * 10/11/93 Released version 1.1 * 09/28/93 Released version 1.0 * 09/93 Original developed by Gordon W. Ross * */ #include __FBSDID("$FreeBSD$"); char *usage = "bootptest [-h] server-name [vendor-data-template-file]"; #include #include #include #include #include #include #include #include #include #include /* inet_ntoa */ #ifndef NO_UNISTD #include #endif #include #include #include #include #include #include #include #include #include #include "bootp.h" #include "bootptest.h" #include "getif.h" #include "getether.h" #include "patchlevel.h" static void send_request(); #define LOG_ERR 1 #define BUFLEN 1024 #define WAITSECS 1 #define MAXWAIT 10 int vflag = 1; int tflag = 0; int thiszone; char *progname; unsigned char *packetp; unsigned char *snapend; int snaplen; /* * IP port numbers for client and server obtained from /etc/services */ u_short bootps_port, bootpc_port; /* * Internet socket and interface config structures */ struct sockaddr_in sin_server; /* where to send requests */ struct sockaddr_in sin_client; /* for bind and listen */ struct sockaddr_in sin_from; /* Packet source */ u_char eaddr[16]; /* Ethernet address */ /* * General */ int debug = 1; /* Debugging flag (level) */ char *sndbuf; /* Send packet buffer */ char *rcvbuf; /* Receive packet buffer */ struct utsname my_uname; char *hostname; /* * Vendor magic cookies for CMU and RFC1048 */ unsigned char vm_cmu[4] = VM_CMU; unsigned char vm_rfc1048[4] = VM_RFC1048; short secs; /* How long client has waited */ char *get_errmsg(); extern void bootp_print(); /* * Initialization such as command-line processing is done, then * the receiver loop is started. Die when interrupted. */ int main(argc, argv) int argc; char **argv; { struct bootp *bp; struct servent *sep; struct hostent *hep; char *servername = NULL; char *vendor_file = NULL; char *bp_file = NULL; int32 server_addr; /* inet addr, network order */ int s; /* Socket file descriptor */ int n, fromlen, recvcnt; int use_hwa = 0; int32 vend_magic; int32 xid; progname = strrchr(argv[0], '/'); if (progname) progname++; else progname = argv[0]; argc--; argv++; if (debug) printf("%s: version %s.%d\n", progname, VERSION, PATCHLEVEL); /* * Verify that "struct bootp" has the correct official size. * (Catch evil compilers that do struct padding.) */ assert(sizeof(struct bootp) == BP_MINPKTSZ); if (uname(&my_uname) < 0) errx(1, "can't get hostname"); hostname = my_uname.nodename; sndbuf = malloc(BUFLEN); rcvbuf = malloc(BUFLEN); if (!sndbuf || !rcvbuf) { printf("malloc failed\n"); exit(1); } /* default magic number */ bcopy(vm_rfc1048, (char*)&vend_magic, 4); /* Handle option switches. */ while (argc > 0) { if (argv[0][0] != '-') break; switch (argv[0][1]) { case 'f': /* File name to request. */ if (argc < 2) goto error; argc--; argv++; bp_file = *argv; break; case 'h': /* Use hardware address. */ use_hwa = 1; break; case 'm': /* Magic number value. */ if (argc < 2) goto error; argc--; argv++; vend_magic = inet_addr(*argv); break; error: default: puts(usage); exit(1); } argc--; argv++; } /* Get server name (or address) for query. */ if (argc > 0) { servername = *argv; argc--; argv++; } /* Get optional vendor-data-template-file. */ if (argc > 0) { vendor_file = *argv; argc--; argv++; } if (!servername) { printf("missing server name.\n"); puts(usage); exit(1); } /* * Create a socket. */ if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket"); exit(1); } /* * Get server's listening port number */ sep = getservbyname("bootps", "udp"); if (sep) { bootps_port = ntohs((u_short) sep->s_port); } else { warnx("bootps/udp: unknown service -- using port %d", IPPORT_BOOTPS); bootps_port = (u_short) IPPORT_BOOTPS; } /* * Set up server socket address (for send) */ if (servername) { if (isdigit(servername[0])) server_addr = inet_addr(servername); else { hep = gethostbyname(servername); if (!hep) errx(1, "%s: unknown host", servername); bcopy(hep->h_addr, &server_addr, sizeof(server_addr)); } } else { /* Get broadcast address */ /* XXX - not yet */ server_addr = INADDR_ANY; } sin_server.sin_family = AF_INET; sin_server.sin_port = htons(bootps_port); sin_server.sin_addr.s_addr = server_addr; /* * Get client's listening port number */ sep = getservbyname("bootpc", "udp"); if (sep) { bootpc_port = ntohs(sep->s_port); } else { warnx("bootpc/udp: unknown service -- using port %d", IPPORT_BOOTPC); bootpc_port = (u_short) IPPORT_BOOTPC; } /* * Set up client socket address (for listen) */ sin_client.sin_family = AF_INET; sin_client.sin_port = htons(bootpc_port); sin_client.sin_addr.s_addr = INADDR_ANY; /* * Bind client socket to BOOTPC port. */ if (bind(s, (struct sockaddr *) &sin_client, sizeof(sin_client)) < 0) { if (errno == EACCES) { warn("bind BOOTPC port"); errx(1, "you need to run this as root"); } else err(1, "bind BOOTPC port"); } /* * Build a request. */ bp = (struct bootp *) sndbuf; bzero(bp, sizeof(*bp)); bp->bp_op = BOOTREQUEST; xid = (int32) getpid(); bp->bp_xid = (u_int32) htonl(xid); if (bp_file) strncpy(bp->bp_file, bp_file, BP_FILE_LEN); /* * Fill in the hardware address (or client IP address) */ if (use_hwa) { struct ifreq *ifr; ifr = getif(s, &sin_server.sin_addr); if (!ifr) { printf("No interface for %s\n", servername); exit(1); } if (getether(ifr->ifr_name, (char*)eaddr)) { printf("Can not get ether addr for %s\n", ifr->ifr_name); exit(1); } /* Copy Ethernet address into request packet. */ bp->bp_htype = 1; bp->bp_hlen = 6; bcopy(eaddr, bp->bp_chaddr, bp->bp_hlen); } else { /* Fill in the client IP address. */ hep = gethostbyname(hostname); if (!hep) { printf("Can not get my IP address\n"); exit(1); } bcopy(hep->h_addr, &bp->bp_ciaddr, hep->h_length); } /* * Copy in the default vendor data. */ bcopy((char*)&vend_magic, bp->bp_vend, 4); if (vend_magic) bp->bp_vend[4] = TAG_END; /* * Read in the "options" part of the request. * This also determines the size of the packet. */ snaplen = sizeof(*bp); if (vendor_file) { int fd = open(vendor_file, 0); if (fd < 0) { perror(vendor_file); exit(1); } /* Compute actual space for options. */ n = BUFLEN - sizeof(*bp) + BP_VEND_LEN; n = read(fd, bp->bp_vend, n); close(fd); if (n < 0) { perror(vendor_file); exit(1); } printf("read %d bytes of vendor template\n", n); if (n > BP_VEND_LEN) { printf("warning: extended options in use (len > %d)\n", BP_VEND_LEN); snaplen += (n - BP_VEND_LEN); } } /* * Set globals needed by print_bootp * (called by send_request) */ packetp = (unsigned char *) eaddr; snapend = (unsigned char *) sndbuf + snaplen; /* Send a request once per second while waiting for replies. */ recvcnt = 0; bp->bp_secs = secs = 0; send_request(s); while (1) { struct timeval tv; int readfds; tv.tv_sec = WAITSECS; tv.tv_usec = 0L; readfds = (1 << s); n = select(s + 1, (fd_set *) & readfds, NULL, NULL, &tv); if (n < 0) { perror("select"); break; } if (n == 0) { /* * We have not received a response in the last second. * If we have ever received any responses, exit now. * Otherwise, bump the "wait time" field and re-send. */ if (recvcnt > 0) exit(0); secs += WAITSECS; if (secs > MAXWAIT) break; bp->bp_secs = htons(secs); send_request(s); continue; } fromlen = sizeof(sin_from); n = recvfrom(s, rcvbuf, BUFLEN, 0, (struct sockaddr *) &sin_from, &fromlen); if (n <= 0) { continue; } if (n < sizeof(struct bootp)) { printf("received short packet\n"); continue; } recvcnt++; /* Print the received packet. */ printf("Recvd from %s", inet_ntoa(sin_from.sin_addr)); /* set globals needed by bootp_print() */ snaplen = n; snapend = (unsigned char *) rcvbuf + snaplen; bootp_print(rcvbuf, n, sin_from.sin_port, 0); putchar('\n'); /* * This no longer exits immediately after receiving * one response because it is useful to know if the * client might get multiple responses. This code * will now listen for one second after a response. */ } errx(1, "no response from %s", servername); } static void send_request(s) int s; { /* Print the request packet. */ printf("Sending to %s", inet_ntoa(sin_server.sin_addr)); bootp_print(sndbuf, snaplen, sin_from.sin_port, 0); putchar('\n'); /* Send the request packet. */ if (sendto(s, sndbuf, snaplen, 0, (struct sockaddr *) &sin_server, sizeof(sin_server)) < 0) { perror("sendto server"); exit(1); } } /* * Print out a filename (or other ascii string). * Return true if truncated. */ int printfn(s, ep) - register u_char *s, *ep; + u_char *s, *ep; { - register u_char c; + u_char c; putchar('"'); while ((c = *s++) != '\0') { if (s > ep) { putchar('"'); return (1); } if (!isascii(c)) { c = toascii(c); putchar('M'); putchar('-'); } if (!isprint(c)) { c ^= 0x40; /* DEL to ?, others to alpha */ putchar('^'); } putchar(c); } putchar('"'); return (0); } /* * Convert an IP addr to a string. * (like inet_ntoa, but ina is a pointer) */ char * ipaddr_string(ina) struct in_addr *ina; { static char b[24]; u_char *p; p = (u_char *) ina; snprintf(b, sizeof(b), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]); return (b); } /* * Local Variables: * tab-width: 4 * c-indent-level: 4 * c-argdecl-indent: 4 * c-continued-statement-offset: 4 * c-continued-brace-offset: -4 * c-label-offset: -4 * c-brace-offset: 0 * End: */ Index: head/libexec/bootpd/tools/bootptest/print-bootp.c =================================================================== --- head/libexec/bootpd/tools/bootptest/print-bootp.c (revision 297864) +++ head/libexec/bootpd/tools/bootptest/print-bootp.c (revision 297865) @@ -1,491 +1,488 @@ /* * Copyright (c) 1988-1990 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: * 1. Source code distributions retain the above copyright * notice and this paragraph in its entirety * 2. Distributions including binary code include the above copyright * notice and this paragraph in its entirety in the documentation * or other materials provided with the distribution, and * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Format and print bootp packets. * * This file was copied from tcpdump-2.1.1 and modified. * There is an e-mail list for tcpdump: * * $FreeBSD$ */ #include #include #include #include #include /* for struct timeval in net/if.h */ #include #include #include #include #include "bootp.h" #include "bootptest.h" /* These decode the vendor data. */ extern int printfn(); static void rfc1048_print(); static void cmu_print(); static void other_print(); static void dump_hex(); /* * Print bootp requests */ void bootp_print(bp, length, sport, dport) struct bootp *bp; int length; u_short sport, dport; { static char tstr[] = " [|bootp]"; static unsigned char vm_cmu[4] = VM_CMU; static unsigned char vm_rfc1048[4] = VM_RFC1048; u_char *ep; int vdlen; #define TCHECK(var, l) if ((u_char *)&(var) > ep - l) goto trunc /* Note funny sized packets */ if (length != sizeof(struct bootp)) (void) printf(" [len=%d]", length); /* 'ep' points to the end of avaible data. */ ep = (u_char *) snapend; switch (bp->bp_op) { case BOOTREQUEST: /* Usually, a request goes from a client to a server */ if (sport != IPPORT_BOOTPC || dport != IPPORT_BOOTPS) printf(" (request)"); break; case BOOTREPLY: /* Usually, a reply goes from a server to a client */ if (sport != IPPORT_BOOTPS || dport != IPPORT_BOOTPC) printf(" (reply)"); break; default: printf(" bootp-#%d", bp->bp_op); } /* The usual hardware address type is 1 (10Mb Ethernet) */ if (bp->bp_htype != 1) printf(" htype:%d", bp->bp_htype); /* The usual length for 10Mb Ethernet address is 6 bytes */ if (bp->bp_hlen != 6) printf(" hlen:%d", bp->bp_hlen); /* Client's Hardware address */ if (bp->bp_hlen) { - register struct ether_header *eh; - register char *e; + struct ether_header *eh; + char *e; TCHECK(bp->bp_chaddr[0], 6); eh = (struct ether_header *) packetp; if (bp->bp_op == BOOTREQUEST) e = (char *) ESRC(eh); else if (bp->bp_op == BOOTREPLY) e = (char *) EDST(eh); else - e = 0; - if (e == 0 || bcmp((char *) bp->bp_chaddr, e, 6)) + e = NULL; + if (e == NULL || bcmp((char *) bp->bp_chaddr, e, 6)) dump_hex(bp->bp_chaddr, bp->bp_hlen); } /* Only print interesting fields */ if (bp->bp_hops) printf(" hops:%d", bp->bp_hops); if (bp->bp_xid) printf(" xid:%ld", (long)ntohl(bp->bp_xid)); if (bp->bp_secs) printf(" secs:%d", ntohs(bp->bp_secs)); /* Client's ip address */ TCHECK(bp->bp_ciaddr, sizeof(bp->bp_ciaddr)); if (bp->bp_ciaddr.s_addr) printf(" C:%s", ipaddr_string(&bp->bp_ciaddr)); /* 'your' ip address (bootp client) */ TCHECK(bp->bp_yiaddr, sizeof(bp->bp_yiaddr)); if (bp->bp_yiaddr.s_addr) printf(" Y:%s", ipaddr_string(&bp->bp_yiaddr)); /* Server's ip address */ TCHECK(bp->bp_siaddr, sizeof(bp->bp_siaddr)); if (bp->bp_siaddr.s_addr) printf(" S:%s", ipaddr_string(&bp->bp_siaddr)); /* Gateway's ip address */ TCHECK(bp->bp_giaddr, sizeof(bp->bp_giaddr)); if (bp->bp_giaddr.s_addr) printf(" G:%s", ipaddr_string(&bp->bp_giaddr)); TCHECK(bp->bp_sname[0], sizeof(bp->bp_sname)); if (*bp->bp_sname) { printf(" sname:"); if (printfn(bp->bp_sname, ep)) { fputs(tstr + 1, stdout); return; } } TCHECK(bp->bp_file[0], sizeof(bp->bp_file)); if (*bp->bp_file) { printf(" file:"); if (printfn(bp->bp_file, ep)) { fputs(tstr + 1, stdout); return; } } /* Don't try to decode the vendor buffer unless we're verbose */ if (vflag <= 0) return; vdlen = sizeof(bp->bp_vend); /* Vendor data can extend to the end of the packet. */ if (vdlen < (ep - bp->bp_vend)) vdlen = (ep - bp->bp_vend); TCHECK(bp->bp_vend[0], vdlen); printf(" vend"); if (!bcmp(bp->bp_vend, vm_rfc1048, sizeof(u_int32))) rfc1048_print(bp->bp_vend, vdlen); else if (!bcmp(bp->bp_vend, vm_cmu, sizeof(u_int32))) cmu_print(bp->bp_vend, vdlen); else other_print(bp->bp_vend, vdlen); return; trunc: fputs(tstr, stdout); #undef TCHECK } /* * Option description data follows. * These are described in: RFC-1048, RFC-1395, RFC-1497, RFC-1533 * * The first char of each option string encodes the data format: * ?: unknown * a: ASCII * b: byte (8-bit) * i: inet address * l: int32 * s: short (16-bit) */ char * rfc1048_opts[] = { /* Originally from RFC-1048: */ "?PAD", /* 0: Padding - special, no data. */ "iSM", /* 1: subnet mask (RFC950)*/ "lTZ", /* 2: time offset, seconds from UTC */ "iGW", /* 3: gateways (or routers) */ "iTS", /* 4: time servers (RFC868) */ "iINS", /* 5: IEN name servers (IEN116) */ "iDNS", /* 6: domain name servers (RFC1035)(1034?) */ "iLOG", /* 7: MIT log servers */ "iCS", /* 8: cookie servers (RFC865) */ "iLPR", /* 9: lpr server (RFC1179) */ "iIPS", /* 10: impress servers (Imagen) */ "iRLP", /* 11: resource location servers (RFC887) */ "aHN", /* 12: host name (ASCII) */ "sBFS", /* 13: boot file size (in 512 byte blocks) */ /* Added by RFC-1395: */ "aDUMP", /* 14: Merit Dump File */ "aDNAM", /* 15: Domain Name (for DNS) */ "iSWAP", /* 16: Swap Server */ "aROOT", /* 17: Root Path */ /* Added by RFC-1497: */ "aEXTF", /* 18: Extensions Path (more options) */ /* Added by RFC-1533: (many, many options...) */ #if 1 /* These might not be worth recognizing by name. */ /* IP Layer Parameters, per-host (RFC-1533, sect. 4) */ "bIP-forward", /* 19: IP Forwarding flag */ "bIP-srcroute", /* 20: IP Source Routing Enable flag */ "iIP-filters", /* 21: IP Policy Filter (addr pairs) */ "sIP-maxudp", /* 22: IP Max-UDP reassembly size */ "bIP-ttlive", /* 23: IP Time to Live */ "lIP-pmtuage", /* 24: IP Path MTU aging timeout */ "sIP-pmtutab", /* 25: IP Path MTU plateau table */ /* IP parameters, per-interface (RFC-1533, sect. 5) */ "sIP-mtu-sz", /* 26: IP MTU size */ "bIP-mtu-sl", /* 27: IP MTU all subnets local */ "bIP-bcast1", /* 28: IP Broadcast Addr ones flag */ "bIP-mask-d", /* 29: IP do mask discovery */ "bIP-mask-s", /* 30: IP do mask supplier */ "bIP-rt-dsc", /* 31: IP do router discovery */ "iIP-rt-sa", /* 32: IP router solicitation addr */ "iIP-routes", /* 33: IP static routes (dst,router) */ /* Link Layer parameters, per-interface (RFC-1533, sect. 6) */ "bLL-trailer", /* 34: do tralier encapsulation */ "lLL-arp-tmo", /* 35: ARP cache timeout */ "bLL-ether2", /* 36: Ethernet version 2 (IEEE 802.3) */ /* TCP parameters (RFC-1533, sect. 7) */ "bTCP-def-ttl", /* 37: default time to live */ "lTCP-KA-tmo", /* 38: keepalive time interval */ "bTCP-KA-junk", /* 39: keepalive sends extra junk */ /* Application and Service Parameters (RFC-1533, sect. 8) */ "aNISDOM", /* 40: NIS Domain (Sun YP) */ "iNISSRV", /* 41: NIS Servers */ "iNTPSRV", /* 42: NTP (time) Servers (RFC 1129) */ "?VSINFO", /* 43: Vendor Specific Info (encapsulated) */ "iNBiosNS", /* 44: NetBIOS Name Server (RFC-1001,1..2) */ "iNBiosDD", /* 45: NetBIOS Datagram Dist. Server. */ "bNBiosNT", /* 46: NetBIOS Note Type */ "?NBiosS", /* 47: NetBIOS Scope */ "iXW-FS", /* 48: X Window System Font Servers */ "iXW-DM", /* 49: X Window System Display Managers */ /* DHCP extensions (RFC-1533, sect. 9) */ #endif }; #define KNOWN_OPTIONS (sizeof(rfc1048_opts) / sizeof(rfc1048_opts[0])) static void rfc1048_print(bp, length) - register u_char *bp; + u_char *bp; int length; { u_char tag; u_char *ep; - register int len; + int len; u_int32 ul; u_short us; struct in_addr ia; char *optstr; printf("-rfc1395"); /* Step over magic cookie */ bp += sizeof(int32); /* Setup end pointer */ ep = bp + length; while (bp < ep) { tag = *bp++; /* Check for tags with no data first. */ if (tag == TAG_PAD) continue; if (tag == TAG_END) return; if (tag < KNOWN_OPTIONS) { optstr = rfc1048_opts[tag]; printf(" %s:", optstr + 1); } else { printf(" T%d:", tag); optstr = "?"; } /* Now scan the length byte. */ len = *bp++; if (bp + len > ep) { /* truncated option */ printf(" |(%d>%td)", len, ep - bp); return; } /* Print the option value(s). */ switch (optstr[0]) { case 'a': /* ASCII string */ printfn(bp, bp + len); bp += len; len = 0; break; case 's': /* Word formats */ while (len >= 2) { bcopy((char *) bp, (char *) &us, 2); printf("%d", ntohs(us)); bp += 2; len -= 2; if (len) printf(","); } if (len) printf("(junk=%d)", len); break; case 'l': /* Long words */ while (len >= 4) { bcopy((char *) bp, (char *) &ul, 4); printf("%ld", (long)ntohl(ul)); bp += 4; len -= 4; if (len) printf(","); } if (len) printf("(junk=%d)", len); break; case 'i': /* INET addresses */ while (len >= 4) { bcopy((char *) bp, (char *) &ia, 4); printf("%s", ipaddr_string(&ia)); bp += 4; len -= 4; if (len) printf(","); } if (len) printf("(junk=%d)", len); break; case 'b': default: break; } /* switch */ /* Print as characters, if appropriate. */ if (len) { dump_hex(bp, len); if (isascii(*bp) && isprint(*bp)) { printf("("); printfn(bp, bp + len); printf(")"); } bp += len; len = 0; } } /* while bp < ep */ } static void cmu_print(bp, length) - register u_char *bp; + u_char *bp; int length; { struct cmu_vend *v; - u_char *ep; printf("-cmu"); v = (struct cmu_vend *) bp; if (length < sizeof(*v)) { printf(" |L=%d", length); return; } - /* Setup end pointer */ - ep = bp + length; /* Subnet mask */ if (v->v_flags & VF_SMASK) { printf(" SM:%s", ipaddr_string(&v->v_smask)); } /* Default gateway */ if (v->v_dgate.s_addr) printf(" GW:%s", ipaddr_string(&v->v_dgate)); /* Domain name servers */ if (v->v_dns1.s_addr) printf(" DNS1:%s", ipaddr_string(&v->v_dns1)); if (v->v_dns2.s_addr) printf(" DNS2:%s", ipaddr_string(&v->v_dns2)); /* IEN-116 name servers */ if (v->v_ins1.s_addr) printf(" INS1:%s", ipaddr_string(&v->v_ins1)); if (v->v_ins2.s_addr) printf(" INS2:%s", ipaddr_string(&v->v_ins2)); /* Time servers */ if (v->v_ts1.s_addr) printf(" TS1:%s", ipaddr_string(&v->v_ts1)); if (v->v_ts2.s_addr) printf(" TS2:%s", ipaddr_string(&v->v_ts2)); } /* * Print out arbitrary, unknown vendor data. */ static void other_print(bp, length) - register u_char *bp; + u_char *bp; int length; { u_char *ep; /* end pointer */ u_char *zp; /* points one past last non-zero byte */ /* Setup end pointer */ ep = bp + length; /* Find the last non-zero byte. */ for (zp = ep; zp > bp; zp--) { if (zp[-1] != 0) break; } /* Print the all-zero case in a compact representation. */ if (zp == bp) { printf("-all-zero"); return; } printf("-unknown"); /* Are there enough trailing zeros to make "00..." worthwhile? */ if (zp + 2 > ep) zp = ep; /* print them all normally */ /* Now just print all the non-zero data. */ while (bp < zp) { printf(".%02X", *bp); bp++; } if (zp < ep) printf(".00..."); return; } static void dump_hex(bp, len) u_char *bp; int len; { while (len > 0) { printf("%02X", *bp); bp++; len--; if (len) printf("."); } } /* * Local Variables: * tab-width: 4 * c-indent-level: 4 * c-argdecl-indent: 4 * c-continued-statement-offset: 4 * c-continued-brace-offset: -4 * c-label-offset: -4 * c-brace-offset: 0 * End: */