diff --git a/libexec/bootpd/bootpd.c b/libexec/bootpd/bootpd.c index 86e4f56ab61a..42f1cd8c5912 100644 --- a/libexec/bootpd/bootpd.c +++ b/libexec/bootpd/bootpd.c @@ -1,1419 +1,1411 @@ /************************************************************************ 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. ************************************************************************/ /* * BOOTP (bootstrap protocol) server daemon. * * Answers BOOTP request packets from booting client machines. * See [SRI-NIC]RFC951.TXT for a description of the protocol. * See [SRI-NIC]RFC1048.TXT for vendor-information extensions. * See RFC 1395 for option tags 14-17. * See accompanying man page -- bootpd.8 * * HISTORY * See ./Changes * * BUGS * See ./ToDo */ #include __FBSDID("$FreeBSD$"); #include #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 #include #ifdef NO_SETSID # include /* for O_RDONLY, etc */ #endif -#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 "bootpd.h" #include "dovend.h" #include "getif.h" #include "readfile.h" #include "report.h" #include "tzone.h" #include "patchlevel.h" #ifndef CONFIG_FILE #define CONFIG_FILE "/etc/bootptab" #endif #ifndef DUMPTAB_FILE #define DUMPTAB_FILE "/tmp/bootpd.dump" #endif /* * Externals, forward declarations, and global variables */ extern void dumptab(char *); PRIVATE void catcher(int); PRIVATE int chk_access(char *, int32 *); #ifdef VEND_CMU PRIVATE void dovend_cmu(struct bootp *, struct host *); #endif PRIVATE void dovend_rfc1048(struct bootp *, struct host *, int32); PRIVATE void handle_reply(void); PRIVATE void handle_request(void); PRIVATE void sendreply(int forward, int32 dest_override); PRIVATE void usage(void); /* * 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 bind_addr; /* Listening */ struct sockaddr_in recv_addr; /* Packet source */ struct sockaddr_in send_addr; /* destination */ /* * option defaults */ int debug = 0; /* Debugging flag (level) */ struct timeval actualtimeout = { /* fifteen minutes */ 15 * 60L, /* tv_sec */ 0 /* tv_usec */ }; int arpmod = TRUE; /* modify the ARP table */ /* * General */ int s; /* Socket file descriptor */ char *pktbuf; /* Receive packet buffer */ int pktlen; char *progname; char *chdir_path; struct in_addr my_ip_addr; static const char *hostname; static char default_hostname[MAXHOSTNAMELEN]; /* Flags set by signal catcher. */ PRIVATE int do_readtab = 0; PRIVATE int do_dumptab = 0; /* * Globals below are associated with the bootp database file (bootptab). */ char *bootptab = CONFIG_FILE; char *bootpd_dump = DUMPTAB_FILE; /* * Initialization such as command-line processing is done and then the * main server loop is started. */ int main(argc, argv) int argc; char **argv; { struct timeval *timeout; struct bootp *bp; struct servent *servp; struct hostent *hep; char *stmp; socklen_t ba_len, ra_len; int n; int nfound; fd_set readfds; int standalone; #ifdef SA_NOCLDSTOP /* Have POSIX sigaction(2). */ struct sigaction sa; #endif progname = strrchr(argv[0], '/'); if (progname) progname++; else progname = argv[0]; /* * Initialize logging. */ report_init(0); /* uses progname */ /* * Log startup */ report(LOG_INFO, "version %s.%d", VERSION, PATCHLEVEL); /* Debugging for compilers with struct padding. */ assert(sizeof(struct bootp) == BP_MINPKTSZ); /* Get space for receiving packets and composing replies. */ pktbuf = malloc(MAX_MSG_SIZE); if (!pktbuf) { report(LOG_ERR, "malloc failed"); exit(1); } bp = (struct bootp *) pktbuf; /* * Check to see if a socket was passed to us from inetd. * * Use getsockname() to determine if descriptor 0 is indeed a socket * (and thus we are probably a child of inetd) or if it is instead * something else and we are running standalone. */ s = 0; ba_len = sizeof(bind_addr); bzero((char *) &bind_addr, ba_len); errno = 0; standalone = TRUE; if (getsockname(s, (struct sockaddr *) &bind_addr, &ba_len) == 0) { /* * Descriptor 0 is a socket. Assume we are a child of inetd. */ if (bind_addr.sin_family == AF_INET) { standalone = FALSE; bootps_port = ntohs(bind_addr.sin_port); } else { /* Some other type of socket? */ report(LOG_ERR, "getsockname: not an INET socket"); } } /* * Set defaults that might be changed by option switches. */ stmp = NULL; timeout = &actualtimeout; if (gethostname(default_hostname, sizeof(default_hostname) - 1) < 0) { report(LOG_ERR, "bootpd: can't get hostname\n"); exit(1); } default_hostname[sizeof(default_hostname) - 1] = '\0'; hostname = default_hostname; /* * Read switches. */ for (argc--, argv++; argc > 0; argc--, argv++) { if (argv[0][0] != '-') break; switch (argv[0][1]) { case 'a': /* don't modify the ARP table */ arpmod = FALSE; break; case 'c': /* chdir_path */ if (argv[0][2]) { stmp = &(argv[0][2]); } else { argc--; argv++; stmp = argv[0]; } if (!stmp || (stmp[0] != '/')) { report(LOG_ERR, "bootpd: invalid chdir specification\n"); break; } chdir_path = stmp; break; case 'd': /* debug level */ if (argv[0][2]) { stmp = &(argv[0][2]); } else if (argv[1] && argv[1][0] == '-') { /* * Backwards-compatible behavior: * no parameter, so just increment the debug flag. */ debug++; break; } else { argc--; argv++; stmp = argv[0]; } if (!stmp || (sscanf(stmp, "%d", &n) != 1) || (n < 0)) { report(LOG_ERR, "%s: invalid debug level\n", progname); break; } debug = n; break; case 'h': /* override hostname */ if (argv[0][2]) { stmp = &(argv[0][2]); } else { argc--; argv++; stmp = argv[0]; } if (!stmp) { report(LOG_ERR, "bootpd: missing hostname\n"); break; } hostname = stmp; break; case 'i': /* inetd mode */ standalone = FALSE; break; case 's': /* standalone mode */ standalone = TRUE; break; case 't': /* timeout */ if (argv[0][2]) { stmp = &(argv[0][2]); } else { argc--; argv++; stmp = argv[0]; } if (!stmp || (sscanf(stmp, "%d", &n) != 1) || (n < 0)) { report(LOG_ERR, "%s: invalid timeout specification\n", progname); break; } actualtimeout.tv_sec = (int32) (60 * n); /* * If the actual timeout is zero, pass a NULL pointer * to select so it blocks indefinitely, otherwise, * point to the actual timeout value. */ timeout = (n > 0) ? &actualtimeout : NULL; break; default: report(LOG_ERR, "%s: unknown switch: -%c\n", progname, argv[0][1]); usage(); break; } /* switch */ } /* for args */ /* * Override default file names if specified on the command line. */ if (argc > 0) bootptab = argv[0]; if (argc > 1) bootpd_dump = argv[1]; /* * Get my hostname and IP address. */ hep = gethostbyname(hostname); if (!hep) { report(LOG_ERR, "Can not get my IP address\n"); exit(1); } bcopy(hep->h_addr, (char *)&my_ip_addr, sizeof(my_ip_addr)); if (standalone) { /* * Go into background and disassociate from controlling terminal. */ if (debug < 3) { if (fork()) exit(0); #ifdef NO_SETSID setpgrp(0,0); #ifdef TIOCNOTTY n = open(_PATH_TTY, O_RDWR); if (n >= 0) { ioctl(n, TIOCNOTTY, (char *) 0); (void) close(n); } #endif /* TIOCNOTTY */ #else /* SETSID */ if (setsid() < 0) perror("setsid"); #endif /* SETSID */ } /* if debug < 3 */ /* * Nuke any timeout value */ timeout = NULL; } /* if standalone (1st) */ /* Set the cwd (i.e. to /tftpboot) */ if (chdir_path) { if (chdir(chdir_path) < 0) report(LOG_ERR, "%s: chdir failed", chdir_path); } /* Get the timezone. */ tzone_init(); /* Allocate hash tables. */ rdtab_init(); /* * Read the bootptab file. */ readtab(1); /* force read */ if (standalone) { /* * Create a socket. */ if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { report(LOG_ERR, "socket: %s", get_network_errmsg()); exit(1); } /* * Get server's listening port number */ servp = getservbyname("bootps", "udp"); if (servp) { bootps_port = ntohs((u_short) servp->s_port); } else { bootps_port = (u_short) IPPORT_BOOTPS; report(LOG_ERR, "bootps/udp: unknown service -- using port %d", bootps_port); } /* * Bind socket to BOOTPS port. */ bind_addr.sin_family = AF_INET; bind_addr.sin_addr.s_addr = INADDR_ANY; bind_addr.sin_port = htons(bootps_port); if (bind(s, (struct sockaddr *) &bind_addr, sizeof(bind_addr)) < 0) { report(LOG_ERR, "bind: %s", get_network_errmsg()); exit(1); } } /* if standalone (2nd)*/ /* * Get destination port number so we can reply to client */ servp = getservbyname("bootpc", "udp"); if (servp) { bootpc_port = ntohs(servp->s_port); } else { report(LOG_ERR, "bootpc/udp: unknown service -- using port %d", IPPORT_BOOTPC); bootpc_port = (u_short) IPPORT_BOOTPC; } /* * Set up signals to read or dump the table. */ #ifdef SA_NOCLDSTOP /* Have POSIX sigaction(2). */ sa.sa_handler = catcher; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; if (sigaction(SIGHUP, &sa, NULL) < 0) { report(LOG_ERR, "sigaction: %s", get_errmsg()); exit(1); } if (sigaction(SIGUSR1, &sa, NULL) < 0) { report(LOG_ERR, "sigaction: %s", get_errmsg()); exit(1); } #else /* SA_NOCLDSTOP */ /* Old-fashioned UNIX signals */ if ((int) signal(SIGHUP, catcher) < 0) { report(LOG_ERR, "signal: %s", get_errmsg()); exit(1); } if ((int) signal(SIGUSR1, catcher) < 0) { report(LOG_ERR, "signal: %s", get_errmsg()); exit(1); } #endif /* SA_NOCLDSTOP */ /* * Process incoming requests. */ FD_ZERO(&readfds); for (;;) { struct timeval tv; FD_SET(s, &readfds); if (timeout) tv = *timeout; nfound = select(s + 1, &readfds, NULL, NULL, (timeout) ? &tv : NULL); if (nfound < 0) { if (errno != EINTR) { report(LOG_ERR, "select: %s", get_errmsg()); } /* * Call readtab() or dumptab() here to avoid the * dangers of doing I/O from a signal handler. */ if (do_readtab) { do_readtab = 0; readtab(1); /* force read */ } if (do_dumptab) { do_dumptab = 0; dumptab(bootpd_dump); } continue; } if (!FD_ISSET(s, &readfds)) { if (debug > 1) report(LOG_INFO, "exiting after %jd minutes of inactivity", (intmax_t)actualtimeout.tv_sec / 60); exit(0); } ra_len = sizeof(recv_addr); n = recvfrom(s, pktbuf, MAX_MSG_SIZE, 0, (struct sockaddr *) &recv_addr, &ra_len); if (n <= 0) { continue; } if (debug > 1) { report(LOG_INFO, "recvd pkt from IP addr %s", inet_ntoa(recv_addr.sin_addr)); } if (n < sizeof(struct bootp)) { if (debug) { report(LOG_NOTICE, "received short packet"); } continue; } pktlen = n; readtab(0); /* maybe re-read bootptab */ switch (bp->bp_op) { case BOOTREQUEST: handle_request(); break; case BOOTREPLY: handle_reply(); break; } } return 0; } /* * Print "usage" message and exit */ PRIVATE void usage() { fprintf(stderr, "usage: bootpd [-a] [-i | -s] [-c chdir-path] [-d level] [-h hostname]\n" " [-t timeout] [bootptab [dumpfile]]\n"); fprintf(stderr, " -a\tdon't modify ARP table\n"); fprintf(stderr, " -c n\tset current directory\n"); fprintf(stderr, " -d n\tset debug level\n"); fprintf(stderr, " -h n\tset the hostname to listen on\n"); fprintf(stderr, " -i\tforce inetd mode (run as child of inetd)\n"); fprintf(stderr, " -s\tforce standalone mode (run without inetd)\n"); fprintf(stderr, " -t n\tset inetd exit timeout to n minutes\n"); exit(1); } /* Signal catchers */ PRIVATE void catcher(sig) int sig; { if (sig == SIGHUP) do_readtab = 1; if (sig == SIGUSR1) do_dumptab = 1; #if !defined(SA_NOCLDSTOP) && defined(SYSV) /* For older "System V" derivatives with no sigaction(). */ signal(sig, catcher); #endif } /* * Process BOOTREQUEST packet. * * Note: This version of the bootpd.c server never forwards * a request to another server. That is the job of a gateway * program such as the "bootpgw" program included here. * * (Also this version does not interpret the hostname field of * the request packet; it COULD do a name->address lookup and * forward the request there.) */ PRIVATE void handle_request() { struct bootp *bp = (struct bootp *) pktbuf; struct host *hp = NULL; struct host dummyhost; int32 bootsize = 0; unsigned hlen, hashcode; int32 dest; char realpath[1024]; char *clntpath; char *homedir, *bootfile; int n; if (bp->bp_htype >= hwinfocnt) { report(LOG_NOTICE, "bad hw addr type %u", bp->bp_htype); return; } bp->bp_file[sizeof(bp->bp_file)-1] = '\0'; /* XXX - SLIP init: Set bp_ciaddr = recv_addr here? */ /* * If the servername field is set, compare it against us. * If we're not being addressed, ignore this request. * If the server name field is null, throw in our name. */ if (strlen(bp->bp_sname)) { if (strcmp(bp->bp_sname, hostname)) { if (debug) report(LOG_INFO, "\ ignoring request for server %s from client at %s address %s", bp->bp_sname, netname(bp->bp_htype), haddrtoa(bp->bp_chaddr, bp->bp_hlen)); /* XXX - Is it correct to ignore such a request? -gwr */ return; } } else { strcpy(bp->bp_sname, hostname); } /* Convert the request into a reply. */ bp->bp_op = BOOTREPLY; if (bp->bp_ciaddr.s_addr == 0) { /* * client doesn't know his IP address, * search by hardware address. */ if (debug > 1) { report(LOG_INFO, "request from %s address %s", netname(bp->bp_htype), haddrtoa(bp->bp_chaddr, bp->bp_hlen)); } hlen = haddrlength(bp->bp_htype); if (hlen != bp->bp_hlen) { report(LOG_NOTICE, "bad addr len from %s address %s", netname(bp->bp_htype), haddrtoa(bp->bp_chaddr, hlen)); } dummyhost.htype = bp->bp_htype; bcopy(bp->bp_chaddr, dummyhost.haddr, hlen); hashcode = hash_HashFunction(bp->bp_chaddr, hlen); hp = (struct host *) hash_Lookup(hwhashtable, hashcode, hwlookcmp, &dummyhost); if (hp == NULL && bp->bp_htype == HTYPE_IEEE802) { /* Try again with address in "canonical" form. */ haddr_conv802(bp->bp_chaddr, dummyhost.haddr, hlen); if (debug > 1) { report(LOG_INFO, "\ HW addr type is IEEE 802. convert to %s and check again\n", haddrtoa(dummyhost.haddr, bp->bp_hlen)); } hashcode = hash_HashFunction(dummyhost.haddr, hlen); hp = (struct host *) hash_Lookup(hwhashtable, hashcode, hwlookcmp, &dummyhost); } if (hp == NULL) { /* * XXX - Add dynamic IP address assignment? */ if (debug) report(LOG_NOTICE, "unknown client %s address %s", netname(bp->bp_htype), haddrtoa(bp->bp_chaddr, bp->bp_hlen)); return; /* not found */ } (bp->bp_yiaddr).s_addr = hp->iaddr.s_addr; } else { /* * search by IP address. */ if (debug > 1) { report(LOG_INFO, "request from IP addr %s", inet_ntoa(bp->bp_ciaddr)); } dummyhost.iaddr.s_addr = bp->bp_ciaddr.s_addr; hashcode = hash_HashFunction((u_char *) &(bp->bp_ciaddr.s_addr), 4); hp = (struct host *) hash_Lookup(iphashtable, hashcode, iplookcmp, &dummyhost); if (hp == NULL) { if (debug) { report(LOG_NOTICE, "IP address not found: %s", inet_ntoa(bp->bp_ciaddr)); } return; } } if (debug) { report(LOG_INFO, "found %s (%s)", inet_ntoa(hp->iaddr), hp->hostname->string); } /* * If there is a response delay threshold, ignore requests * with a timestamp lower than the threshold. */ if (hp->flags.min_wait) { u_int32 t = (u_int32) ntohs(bp->bp_secs); if (t < hp->min_wait) { if (debug > 1) report(LOG_INFO, "ignoring request due to timestamp (%d < %d)", t, hp->min_wait); return; } } #ifdef YORK_EX_OPTION /* * The need for the "ex" tag arose out of the need to empty * shared networked drives on diskless PCs. This solution is * not very clean but it does work fairly well. * Written by Edmund J. Sutcliffe * * XXX - This could compromise security if a non-trusted user * managed to write an entry in the bootptab with :ex=trojan: * so I would leave this turned off unless you need it. -gwr */ /* Run a program, passing the client name as a parameter. */ if (hp->flags.exec_file) { char tst[100]; /* XXX - Check string lengths? -gwr */ strcpy (tst, hp->exec_file->string); strcat (tst, " "); strcat (tst, hp->hostname->string); strcat (tst, " &"); if (debug) report(LOG_INFO, "executing %s", tst); system(tst); /* Hope this finishes soon... */ } #endif /* YORK_EX_OPTION */ /* * If a specific TFTP server address was specified in the bootptab file, * fill it in, otherwise zero it. * XXX - Rather than zero it, should it be the bootpd address? -gwr */ (bp->bp_siaddr).s_addr = (hp->flags.bootserver) ? hp->bootserver.s_addr : 0L; #ifdef STANFORD_PROM_COMPAT /* * Stanford bootp PROMs (for a Sun?) have no way to leave * the boot file name field blank (because the boot file * name is automatically generated from some index). * As a work-around, this little hack allows those PROMs to * specify "sunboot14" with the same effect as a NULL name. * (The user specifies boot device 14 or some such magic.) */ if (strcmp(bp->bp_file, "sunboot14") == 0) bp->bp_file[0] = '\0'; /* treat it as unspecified */ #endif /* * Fill in the client's proper bootfile. * * If the client specifies an absolute path, try that file with a * ".host" suffix and then without. If the file cannot be found, no * reply is made at all. * * If the client specifies a null or relative file, use the following * table to determine the appropriate action: * * Homedir Bootfile Client's file * specified? specified? specification Action * ------------------------------------------------------------------- * No No Null Send null filename * No No Relative Discard request * No Yes Null Send if absolute else null * No Yes Relative Discard request *XXX * Yes No Null Send null filename * Yes No Relative Lookup with ".host" * Yes Yes Null Send home/boot or bootfile * Yes Yes Relative Lookup with ".host" *XXX * */ /* * XXX - I don't like the policy of ignoring a client when the * boot file is not accessible. The TFTP server might not be * running on the same machine as the BOOTP server, in which * case checking accessibility of the boot file is pointless. * * Therefore, file accessibility is now demanded ONLY if you * define CHECK_FILE_ACCESS in the Makefile options. -gwr */ /* * The "real" path is as seen by the BOOTP daemon on this * machine, while the client path is relative to the TFTP * daemon chroot directory (i.e. /tftpboot). */ if (hp->flags.tftpdir) { snprintf(realpath, sizeof(realpath), "%s", hp->tftpdir->string); clntpath = &realpath[strlen(realpath)]; } else { realpath[0] = '\0'; clntpath = realpath; } /* * Determine client's requested homedir and bootfile. */ homedir = NULL; bootfile = NULL; if (bp->bp_file[0]) { homedir = bp->bp_file; bootfile = strrchr(homedir, '/'); if (bootfile) { if (homedir == bootfile) homedir = NULL; *bootfile++ = '\0'; } else { /* no "/" in the string */ bootfile = homedir; homedir = NULL; } if (debug > 2) { report(LOG_INFO, "requested path=\"%s\" file=\"%s\"", (homedir) ? homedir : "", (bootfile) ? bootfile : ""); } } /* * Specifications in bootptab override client requested values. */ if (hp->flags.homedir) homedir = hp->homedir->string; if (hp->flags.bootfile) bootfile = hp->bootfile->string; /* * Construct bootfile path. */ if (homedir) { if (homedir[0] != '/') strcat(clntpath, "/"); strcat(clntpath, homedir); homedir = NULL; } if (bootfile) { if (bootfile[0] != '/') strcat(clntpath, "/"); strcat(clntpath, bootfile); bootfile = NULL; } /* * First try to find the file with a ".host" suffix */ n = strlen(clntpath); strcat(clntpath, "."); strcat(clntpath, hp->hostname->string); if (chk_access(realpath, &bootsize) < 0) { clntpath[n] = 0; /* Try it without the suffix */ if (chk_access(realpath, &bootsize) < 0) { /* neither "file.host" nor "file" was found */ #ifdef CHECK_FILE_ACCESS if (bp->bp_file[0]) { /* * Client wanted specific file * and we didn't have it. */ report(LOG_NOTICE, "requested file not found: \"%s\"", clntpath); return; } /* * Client didn't ask for a specific file and we couldn't * access the default file, so just zero-out the bootfile * field in the packet and continue processing the reply. */ bzero(bp->bp_file, sizeof(bp->bp_file)); goto null_file_name; #else /* CHECK_FILE_ACCESS */ /* Complain only if boot file size was needed. */ if (hp->flags.bootsize_auto) { report(LOG_ERR, "can not determine size of file \"%s\"", clntpath); } #endif /* CHECK_FILE_ACCESS */ } } strncpy(bp->bp_file, clntpath, BP_FILE_LEN); if (debug > 2) report(LOG_INFO, "bootfile=\"%s\"", clntpath); #ifdef CHECK_FILE_ACCESS null_file_name: #endif /* CHECK_FILE_ACCESS */ /* * Handle vendor options based on magic number. */ if (debug > 1) { report(LOG_INFO, "vendor magic field is %d.%d.%d.%d", (int) ((bp->bp_vend)[0]), (int) ((bp->bp_vend)[1]), (int) ((bp->bp_vend)[2]), (int) ((bp->bp_vend)[3])); } /* * If this host isn't set for automatic vendor info then copy the * specific cookie into the bootp packet, thus forcing a certain * reply format. Only force reply format if user specified it. */ if (hp->flags.vm_cookie) { /* Slam in the user specified magic number. */ bcopy(hp->vm_cookie, bp->bp_vend, 4); } /* * Figure out the format for the vendor-specific info. * Note that bp->bp_vend may have been set above. */ if (!bcmp(bp->bp_vend, vm_rfc1048, 4)) { /* RFC1048 conformant bootp client */ dovend_rfc1048(bp, hp, bootsize); if (debug > 1) { report(LOG_INFO, "sending reply (with RFC1048 options)"); } } #ifdef VEND_CMU else if (!bcmp(bp->bp_vend, vm_cmu, 4)) { dovend_cmu(bp, hp); if (debug > 1) { report(LOG_INFO, "sending reply (with CMU options)"); } } #endif else { if (debug > 1) { report(LOG_INFO, "sending reply (with no options)"); } } dest = (hp->flags.reply_addr) ? hp->reply_addr.s_addr : 0L; /* not forwarded */ sendreply(0, dest); } /* * Process BOOTREPLY packet. */ PRIVATE void handle_reply() { if (debug) { report(LOG_INFO, "processing boot reply"); } /* forwarded, no destination override */ sendreply(1, 0); } /* * Send a reply packet to the client. 'forward' flag is set if we are * not the originator of this reply packet. */ PRIVATE void sendreply(forward, dst_override) int forward; int32 dst_override; { struct bootp *bp = (struct bootp *) pktbuf; struct in_addr dst; u_short port = bootpc_port; unsigned char *ha; int len, haf; /* * XXX - Should honor bp_flags "broadcast" bit here. * Temporary workaround: use the :ra=ADDR: option to * set the reply address to the broadcast address. */ /* * If the destination address was specified explicitly * (i.e. the broadcast address for HP compatibility) * then send the response to that address. Otherwise, * act in accordance with RFC951: * If the client IP address is specified, use that * else if gateway IP address is specified, use that * else make a temporary arp cache entry for the client's * NEW IP/hardware address and use that. */ if (dst_override) { dst.s_addr = dst_override; if (debug > 1) { report(LOG_INFO, "reply address override: %s", inet_ntoa(dst)); } } else if (bp->bp_ciaddr.s_addr) { dst = bp->bp_ciaddr; } else if (bp->bp_giaddr.s_addr && forward == 0) { dst = bp->bp_giaddr; port = bootps_port; if (debug > 1) { report(LOG_INFO, "sending reply to gateway %s", inet_ntoa(dst)); } } else { dst = bp->bp_yiaddr; ha = bp->bp_chaddr; len = bp->bp_hlen; if (len > MAXHADDRLEN) len = MAXHADDRLEN; haf = (int) bp->bp_htype; if (haf == 0) haf = HTYPE_ETHERNET; if (arpmod) { if (debug > 1) report(LOG_INFO, "setarp %s - %s", inet_ntoa(dst), haddrtoa(ha, len)); setarp(s, &dst, haf, ha, len); } } if ((forward == 0) && (bp->bp_siaddr.s_addr == 0)) { struct ifreq *ifr; struct in_addr siaddr; /* * If we are originating this reply, we * need to find our own interface address to * put in the bp_siaddr field of the reply. * If this server is multi-homed, pick the * 'best' interface (the one on the same net * as the client). Of course, the client may * be on the other side of a BOOTP gateway... */ ifr = getif(s, &dst); if (ifr) { struct sockaddr_in *sip; sip = (struct sockaddr_in *) &(ifr->ifr_addr); siaddr = sip->sin_addr; } else { /* Just use my "official" IP address. */ siaddr = my_ip_addr; } /* XXX - No need to set bp_giaddr here. */ /* Finally, set the server address field. */ bp->bp_siaddr = siaddr; } /* Set up socket address for send. */ send_addr.sin_family = AF_INET; send_addr.sin_port = htons(port); send_addr.sin_addr = dst; /* Send reply with same size packet as request used. */ if (sendto(s, pktbuf, pktlen, 0, (struct sockaddr *) &send_addr, sizeof(send_addr)) < 0) { report(LOG_ERR, "sendto: %s", get_network_errmsg()); } } /* sendreply */ /* nmatch() - now in getif.c */ /* setarp() - now in hwaddr.c */ /* * This call checks read access to a file. It returns 0 if the file given * by "path" exists and is publicly readable. A value of -1 is returned if * access is not permitted or an error occurs. Successful calls also * return the file size in bytes using the long pointer "filesize". * * The read permission bit for "other" users is checked. This bit must be * set for tftpd(8) to allow clients to read the file. */ PRIVATE int chk_access(path, filesize) char *path; int32 *filesize; { struct stat st; if ((stat(path, &st) == 0) && (st.st_mode & (S_IREAD >> 6))) { *filesize = (int32) st.st_size; return 0; } else { return -1; } } /* * Now in dumptab.c : * dumptab() * dump_host() * list_ipaddresses() */ #ifdef VEND_CMU /* * Insert the CMU "vendor" data for the host pointed to by "hp" into the * bootp packet pointed to by "bp". */ PRIVATE void dovend_cmu(bp, hp) struct bootp *bp; struct host *hp; { struct cmu_vend *vendp; struct in_addr_list *taddr; /* * Initialize the entire vendor field to zeroes. */ bzero(bp->bp_vend, sizeof(bp->bp_vend)); /* * Fill in vendor information. Subnet mask, default gateway, * domain name server, ien name server, time server */ vendp = (struct cmu_vend *) bp->bp_vend; strcpy(vendp->v_magic, (char *)vm_cmu); if (hp->flags.subnet_mask) { (vendp->v_smask).s_addr = hp->subnet_mask.s_addr; (vendp->v_flags) |= VF_SMASK; if (hp->flags.gateway) { (vendp->v_dgate).s_addr = hp->gateway->addr->s_addr; } } if (hp->flags.domain_server) { taddr = hp->domain_server; if (taddr->addrcount > 0) { (vendp->v_dns1).s_addr = (taddr->addr)[0].s_addr; if (taddr->addrcount > 1) { (vendp->v_dns2).s_addr = (taddr->addr)[1].s_addr; } } } if (hp->flags.name_server) { taddr = hp->name_server; if (taddr->addrcount > 0) { (vendp->v_ins1).s_addr = (taddr->addr)[0].s_addr; if (taddr->addrcount > 1) { (vendp->v_ins2).s_addr = (taddr->addr)[1].s_addr; } } } if (hp->flags.time_server) { taddr = hp->time_server; if (taddr->addrcount > 0) { (vendp->v_ts1).s_addr = (taddr->addr)[0].s_addr; if (taddr->addrcount > 1) { (vendp->v_ts2).s_addr = (taddr->addr)[1].s_addr; } } } /* Log message now done by caller. */ } /* dovend_cmu */ #endif /* VEND_CMU */ /* * Insert the RFC1048 vendor data for the host pointed to by "hp" into the * bootp packet pointed to by "bp". */ #define NEED(LEN, MSG) do \ if (bytesleft < (LEN)) { \ report(LOG_NOTICE, noroom, \ hp->hostname->string, MSG); \ return; \ } while (0) PRIVATE void dovend_rfc1048(bp, hp, bootsize) struct bootp *bp; struct host *hp; int32 bootsize; { int bytesleft, len; byte *vp; static const char noroom[] = "%s: No room for \"%s\" option"; vp = bp->bp_vend; if (hp->flags.msg_size) { pktlen = hp->msg_size; } else { /* * If the request was longer than the official length, build * a response of that same length where the additional length * is assumed to be part of the bp_vend (options) area. */ if (pktlen > sizeof(*bp)) { if (debug > 1) report(LOG_INFO, "request message length=%d", pktlen); } /* * Check whether the request contains the option: * Maximum DHCP Message Size (RFC1533 sec. 9.8) * and if so, override the response length with its value. * This request must lie within the first BP_VEND_LEN * bytes of the option space. */ { byte *p, *ep; byte tag, len; short msgsz = 0; p = vp + 4; ep = p + BP_VEND_LEN - 4; while (p < ep) { tag = *p++; /* Check for tags with no data first. */ if (tag == TAG_PAD) continue; if (tag == TAG_END) break; /* Now scan the length byte. */ len = *p++; switch (tag) { case TAG_MAX_MSGSZ: if (len == 2) { bcopy(p, (char*)&msgsz, 2); msgsz = ntohs(msgsz); } break; case TAG_SUBNET_MASK: /* XXX - Should preserve this if given... */ break; } /* swtich */ p += len; } if (msgsz > sizeof(*bp) + BP_MSG_OVERHEAD) { if (debug > 1) report(LOG_INFO, "request has DHCP msglen=%d", msgsz); pktlen = msgsz - BP_MSG_OVERHEAD; } } } if (pktlen < sizeof(*bp)) { report(LOG_ERR, "invalid response length=%d", pktlen); pktlen = sizeof(*bp); } bytesleft = ((byte*)bp + pktlen) - vp; if (pktlen > sizeof(*bp)) { if (debug > 1) report(LOG_INFO, "extended reply, length=%d, options=%d", pktlen, bytesleft); } /* Copy in the magic cookie */ bcopy(vm_rfc1048, vp, 4); vp += 4; bytesleft -= 4; if (hp->flags.subnet_mask) { /* always enough room here. */ *vp++ = TAG_SUBNET_MASK;/* -1 byte */ *vp++ = 4; /* -1 byte */ insert_u_long(hp->subnet_mask.s_addr, &vp); /* -4 bytes */ bytesleft -= 6; /* Fix real count */ if (hp->flags.gateway) { (void) insert_ip(TAG_GATEWAY, hp->gateway, &vp, &bytesleft); } } if (hp->flags.bootsize) { /* always enough room here */ bootsize = (hp->flags.bootsize_auto) ? ((bootsize + 511) / 512) : (hp->bootsize); /* Round up */ *vp++ = TAG_BOOT_SIZE; *vp++ = 2; *vp++ = (byte) ((bootsize >> 8) & 0xFF); *vp++ = (byte) (bootsize & 0xFF); bytesleft -= 4; /* Tag, length, and 16 bit blocksize */ } /* * This one is special: Remaining options go in the ext file. * Only the subnet_mask, bootsize, and gateway should precede. */ if (hp->flags.exten_file) { /* * Check for room for exten_file. Add 3 to account for * TAG_EXTEN_FILE, length, and TAG_END. */ len = strlen(hp->exten_file->string); NEED((len + 3), "ef"); *vp++ = TAG_EXTEN_FILE; *vp++ = (byte) (len & 0xFF); bcopy(hp->exten_file->string, vp, len); vp += len; *vp++ = TAG_END; bytesleft -= len + 3; return; /* no more options here. */ } /* * The remaining options are inserted by the following * function (which is shared with bootpef.c). * Keep back one byte for the TAG_END. */ len = dovend_rfc1497(hp, vp, bytesleft - 1); vp += len; bytesleft -= len; /* There should be at least one byte left. */ NEED(1, "(end)"); *vp++ = TAG_END; bytesleft--; /* Log message done by caller. */ if (bytesleft > 0) { /* * Zero out any remaining part of the vendor area. */ bzero(vp, bytesleft); } } /* dovend_rfc1048 */ #undef NEED /* * Now in readfile.c: * hwlookcmp() * iplookcmp() */ /* haddrtoa() - now in hwaddr.c */ /* * Now in dovend.c: * insert_ip() * insert_generic() * insert_u_long() */ /* get_errmsg() - now in report.c */ /* * 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: */ diff --git a/libexec/bootpd/bootpgw/bootpgw.c b/libexec/bootpd/bootpgw/bootpgw.c index 2e2df9e71a2a..3c128c03a9a6 100644 --- a/libexec/bootpd/bootpgw/bootpgw.c +++ b/libexec/bootpd/bootpgw/bootpgw.c @@ -1,687 +1,679 @@ /* * bootpgw.c - BOOTP GateWay * This program forwards BOOTP Request packets to a BOOTP server. */ /************************************************************************ 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. ************************************************************************/ /* * BOOTPGW is typically used to forward BOOTP client requests from * one subnet to a BOOTP server on a different subnet. */ #include __FBSDID("$FreeBSD$"); #include #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 #include #ifdef NO_SETSID # include /* for O_RDONLY, etc */ #endif -#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 "getif.h" #include "hwaddr.h" #include "report.h" #include "patchlevel.h" /* Local definitions: */ #define MAX_MSG_SIZE (3*512) /* Maximum packet size */ #define TRUE 1 #define FALSE 0 #define get_network_errmsg get_errmsg /* * Externals, forward declarations, and global variables */ static void usage(void); static void handle_reply(void); static void handle_request(void); /* * 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 bind_addr; /* Listening */ struct sockaddr_in recv_addr; /* Packet source */ struct sockaddr_in send_addr; /* destination */ /* * option defaults */ int debug = 0; /* Debugging flag (level) */ struct timeval actualtimeout = { /* fifteen minutes */ 15 * 60L, /* tv_sec */ 0 /* tv_usec */ }; u_char maxhops = 4; /* Number of hops allowed for requests. */ u_int minwait = 3; /* Number of seconds client must wait before its bootrequest packets are forwarded. */ int arpmod = TRUE; /* modify the ARP table */ /* * General */ int s; /* Socket file descriptor */ char *pktbuf; /* Receive packet buffer */ int pktlen; char *progname; char *servername; int32 server_ipa; /* Real server IP address, network order. */ struct in_addr my_ip_addr; struct utsname my_uname; char *hostname; /* * Initialization such as command-line processing is done and then the * main server loop is started. */ int main(argc, argv) int argc; char **argv; { struct timeval *timeout; struct bootp *bp; struct servent *servp; struct hostent *hep; char *stmp; int n, ba_len, ra_len; int nfound, readfds; int standalone; progname = strrchr(argv[0], '/'); if (progname) progname++; else progname = argv[0]; /* * Initialize logging. */ report_init(0); /* uses progname */ /* * Log startup */ report(LOG_INFO, "version %s.%d", VERSION, PATCHLEVEL); /* Debugging for compilers with struct padding. */ assert(sizeof(struct bootp) == BP_MINPKTSZ); /* Get space for receiving packets and composing replies. */ pktbuf = malloc(MAX_MSG_SIZE); if (!pktbuf) { report(LOG_ERR, "malloc failed"); exit(1); } bp = (struct bootp *) pktbuf; /* * Check to see if a socket was passed to us from inetd. * * Use getsockname() to determine if descriptor 0 is indeed a socket * (and thus we are probably a child of inetd) or if it is instead * something else and we are running standalone. */ s = 0; ba_len = sizeof(bind_addr); bzero((char *) &bind_addr, ba_len); errno = 0; standalone = TRUE; if (getsockname(s, (struct sockaddr *) &bind_addr, &ba_len) == 0) { /* * Descriptor 0 is a socket. Assume we are a child of inetd. */ if (bind_addr.sin_family == AF_INET) { standalone = FALSE; bootps_port = ntohs(bind_addr.sin_port); } else { /* Some other type of socket? */ report(LOG_INFO, "getsockname: not an INET socket"); } } /* * Set defaults that might be changed by option switches. */ stmp = NULL; timeout = &actualtimeout; if (uname(&my_uname) < 0) errx(1, "can't get hostname"); hostname = my_uname.nodename; hep = gethostbyname(hostname); if (!hep) { printf("Can not get my IP address\n"); exit(1); } bcopy(hep->h_addr, (char *)&my_ip_addr, sizeof(my_ip_addr)); /* * Read switches. */ for (argc--, argv++; argc > 0; argc--, argv++) { if (argv[0][0] != '-') break; switch (argv[0][1]) { case 'a': /* don't modify the ARP table */ arpmod = FALSE; break; case 'd': /* debug level */ if (argv[0][2]) { stmp = &(argv[0][2]); } else if (argv[1] && argv[1][0] == '-') { /* * Backwards-compatible behavior: * no parameter, so just increment the debug flag. */ debug++; break; } else { argc--; argv++; stmp = argv[0]; } if (!stmp || (sscanf(stmp, "%d", &n) != 1) || (n < 0)) { warnx("invalid debug level"); break; } debug = n; break; case 'h': /* hop count limit */ if (argv[0][2]) { stmp = &(argv[0][2]); } else { argc--; argv++; stmp = argv[0]; } if (!stmp || (sscanf(stmp, "%d", &n) != 1) || (n < 0) || (n > 16)) { warnx("invalid hop count limit"); break; } maxhops = (u_char)n; break; case 'i': /* inetd mode */ standalone = FALSE; break; case 's': /* standalone mode */ standalone = TRUE; break; case 't': /* timeout */ if (argv[0][2]) { stmp = &(argv[0][2]); } else { argc--; argv++; stmp = argv[0]; } if (!stmp || (sscanf(stmp, "%d", &n) != 1) || (n < 0)) { warnx("invalid timeout specification"); break; } actualtimeout.tv_sec = (int32) (60 * n); /* * If the actual timeout is zero, pass a NULL pointer * to select so it blocks indefinitely, otherwise, * point to the actual timeout value. */ timeout = (n > 0) ? &actualtimeout : NULL; break; case 'w': /* wait time */ if (argv[0][2]) { stmp = &(argv[0][2]); } else { argc--; argv++; stmp = argv[0]; } if (!stmp || (sscanf(stmp, "%d", &n) != 1) || (n < 0) || (n > 60)) { warnx("invalid wait time"); break; } minwait = (u_int)n; break; default: warnx("unknown switch: -%c", argv[0][1]); usage(); break; } /* switch */ } /* for args */ /* Make sure server name argument is suplied. */ servername = argv[0]; if (!servername) { warnx("missing server name"); usage(); } /* * Get address of real bootp server. */ if (isdigit(servername[0])) server_ipa = inet_addr(servername); else { hep = gethostbyname(servername); if (!hep) errx(1, "can't get addr for %s", servername); bcopy(hep->h_addr, (char *)&server_ipa, sizeof(server_ipa)); } if (standalone) { /* * Go into background and disassociate from controlling terminal. * XXX - This is not the POSIX way (Should use setsid). -gwr */ if (debug < 3) { if (fork()) exit(0); #ifdef NO_SETSID setpgrp(0,0); #ifdef TIOCNOTTY n = open(_PATH_TTY, O_RDWR); if (n >= 0) { ioctl(n, TIOCNOTTY, (char *) 0); (void) close(n); } #endif /* TIOCNOTTY */ #else /* SETSID */ if (setsid() < 0) perror("setsid"); #endif /* SETSID */ } /* if debug < 3 */ /* * Nuke any timeout value */ timeout = NULL; /* * Here, bootpd would do: * chdir * tzone_init * rdtab_init * readtab */ /* * Create a socket. */ if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { report(LOG_ERR, "socket: %s", get_network_errmsg()); exit(1); } /* * Get server's listening port number */ servp = getservbyname("bootps", "udp"); if (servp) { bootps_port = ntohs((u_short) servp->s_port); } else { bootps_port = (u_short) IPPORT_BOOTPS; report(LOG_ERR, "bootps/udp: unknown service -- using port %d", bootps_port); } /* * Bind socket to BOOTPS port. */ bind_addr.sin_family = AF_INET; bind_addr.sin_port = htons(bootps_port); bind_addr.sin_addr.s_addr = INADDR_ANY; if (bind(s, (struct sockaddr *) &bind_addr, sizeof(bind_addr)) < 0) { report(LOG_ERR, "bind: %s", get_network_errmsg()); exit(1); } } /* if standalone */ /* * Get destination port number so we can reply to client */ servp = getservbyname("bootpc", "udp"); if (servp) { bootpc_port = ntohs(servp->s_port); } else { report(LOG_ERR, "bootpc/udp: unknown service -- using port %d", IPPORT_BOOTPC); bootpc_port = (u_short) IPPORT_BOOTPC; } /* no signal catchers */ /* * Process incoming requests. */ for (;;) { struct timeval tv; readfds = 1 << s; if (timeout) tv = *timeout; nfound = select(s + 1, (fd_set *)&readfds, NULL, NULL, (timeout) ? &tv : NULL); if (nfound < 0) { if (errno != EINTR) { report(LOG_ERR, "select: %s", get_errmsg()); } continue; } if (!(readfds & (1 << s))) { report(LOG_INFO, "exiting after %ld minutes of inactivity", (long)(actualtimeout.tv_sec / 60)); exit(0); } ra_len = sizeof(recv_addr); n = recvfrom(s, pktbuf, MAX_MSG_SIZE, 0, (struct sockaddr *) &recv_addr, &ra_len); if (n <= 0) { continue; } if (debug > 3) { report(LOG_INFO, "recvd pkt from IP addr %s", inet_ntoa(recv_addr.sin_addr)); } if (n < sizeof(struct bootp)) { if (debug) { report(LOG_INFO, "received short packet"); } continue; } pktlen = n; switch (bp->bp_op) { case BOOTREQUEST: handle_request(); break; case BOOTREPLY: handle_reply(); break; } } return 0; } /* * Print "usage" message and exit */ static void usage() { fprintf(stderr, "usage: bootpgw [-a] [-i | -s] [-d level] [-h count] [-t timeout]\n" " [-w time] server\n"); fprintf(stderr, "\t -a\tdon't modify ARP table\n"); fprintf(stderr, "\t -d n\tset debug level\n"); fprintf(stderr, "\t -h n\tset max hop count\n"); fprintf(stderr, "\t -i\tforce inetd mode (run as child of inetd)\n"); fprintf(stderr, "\t -s\tforce standalone mode (run without inetd)\n"); fprintf(stderr, "\t -t n\tset inetd exit timeout to n minutes\n"); fprintf(stderr, "\t -w n\tset min wait time (secs)\n"); exit(1); } /* * Process BOOTREQUEST packet. * * Note, this just forwards the request to a real server. */ static void handle_request() { struct bootp *bp = (struct bootp *) pktbuf; u_short secs; u_char hops; /* XXX - SLIP init: Set bp_ciaddr = recv_addr here? */ if (debug) { report(LOG_INFO, "request from %s", inet_ntoa(recv_addr.sin_addr)); } /* Has the client been waiting long enough? */ secs = ntohs(bp->bp_secs); if (secs < minwait) return; /* Has this packet hopped too many times? */ hops = bp->bp_hops; if (++hops > maxhops) { report(LOG_NOTICE, "request from %s reached hop limit", inet_ntoa(recv_addr.sin_addr)); return; } bp->bp_hops = hops; /* * Here one might discard a request from the same subnet as the * real server, but we can assume that the real server will send * a reply to the client before it waits for minwait seconds. */ /* If gateway address is not set, put in local interface addr. */ if (bp->bp_giaddr.s_addr == 0) { #if 0 /* BUG */ struct sockaddr_in *sip; struct ifreq *ifr; /* * XXX - This picks the wrong interface when the receive addr * is the broadcast address. There is no portable way to * find out which interface a broadcast was received on. -gwr * (Thanks to for finding this bug!) */ ifr = getif(s, &recv_addr.sin_addr); if (!ifr) { report(LOG_NOTICE, "no interface for request from %s", inet_ntoa(recv_addr.sin_addr)); return; } sip = (struct sockaddr_in *) &(ifr->ifr_addr); bp->bp_giaddr = sip->sin_addr; #else /* BUG */ /* * XXX - Just set "giaddr" to our "official" IP address. * RFC 1532 says giaddr MUST be set to the address of the * interface on which the request was received. Setting * it to our "default" IP address is not strictly correct, * but is good enough to allow the real BOOTP server to * get the reply back here. Then, before we forward the * reply to the client, the giaddr field is corrected. * (In case the client uses giaddr, which it should not.) * See handle_reply() */ bp->bp_giaddr = my_ip_addr; #endif /* BUG */ /* * XXX - DHCP says to insert a subnet mask option into the * options area of the request (if vendor magic == std). */ } /* Set up socket address for send. */ send_addr.sin_family = AF_INET; send_addr.sin_port = htons(bootps_port); send_addr.sin_addr.s_addr = server_ipa; /* Send reply with same size packet as request used. */ if (sendto(s, pktbuf, pktlen, 0, (struct sockaddr *) &send_addr, sizeof(send_addr)) < 0) { report(LOG_ERR, "sendto: %s", get_network_errmsg()); } } /* * Process BOOTREPLY packet. */ static void handle_reply() { struct bootp *bp = (struct bootp *) pktbuf; struct ifreq *ifr; struct sockaddr_in *sip; unsigned char *ha; int len, haf; if (debug) { report(LOG_INFO, " reply for %s", inet_ntoa(bp->bp_yiaddr)); } /* Make sure client is directly accessible. */ ifr = getif(s, &(bp->bp_yiaddr)); if (!ifr) { report(LOG_NOTICE, "no interface for reply to %s", inet_ntoa(bp->bp_yiaddr)); return; } #if 1 /* Experimental (see BUG above) */ /* #ifdef CATER_TO_OLD_CLIENTS ? */ /* * The giaddr field has been set to our "default" IP address * which might not be on the same interface as the client. * In case the client looks at giaddr, (which it should not) * giaddr is now set to the address of the correct interface. */ sip = (struct sockaddr_in *) &(ifr->ifr_addr); bp->bp_giaddr = sip->sin_addr; #endif /* Set up socket address for send to client. */ send_addr.sin_family = AF_INET; send_addr.sin_addr = bp->bp_yiaddr; send_addr.sin_port = htons(bootpc_port); if (arpmod) { /* Create an ARP cache entry for the client. */ ha = bp->bp_chaddr; len = bp->bp_hlen; struct in_addr dst; if (len > MAXHADDRLEN) len = MAXHADDRLEN; haf = (int) bp->bp_htype; if (haf == 0) haf = HTYPE_ETHERNET; if (debug > 1) report(LOG_INFO, "setarp %s - %s", inet_ntoa(dst), haddrtoa(ha, len)); setarp(s, &dst, haf, ha, len); } /* Send reply with same size packet as request used. */ if (sendto(s, pktbuf, pktlen, 0, (struct sockaddr *) &send_addr, sizeof(send_addr)) < 0) { report(LOG_ERR, "sendto: %s", get_network_errmsg()); } } /* * 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: */ diff --git a/libexec/bootpd/dovend.c b/libexec/bootpd/dovend.c index cb0b4a0448c4..65543a2700c0 100644 --- a/libexec/bootpd/dovend.c +++ b/libexec/bootpd/dovend.c @@ -1,408 +1,399 @@ /* * dovend.c : Inserts all but the first few vendor options. * * $FreeBSD$ */ #include #include #include /* inet_ntoa */ #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) -# define index strchr -#endif - #include "bootp.h" #include "bootpd.h" #include "report.h" #include "dovend.h" PRIVATE int insert_generic(struct shared_bindata *, byte **, int *); /* * Insert the 2nd part of the options into an option buffer. * Return amount of space used. * * This inserts everything EXCEPT: * magic cookie, subnet mask, gateway, bootsize, extension file * Those are handled separately (in bootpd.c) to allow this function * to be shared between bootpd and bootpef. * * When an "extension file" is in use, the options inserted by * this function go into the exten_file, not the bootp response. */ int dovend_rfc1497(hp, buf, len) struct host *hp; byte *buf; int len; { int bytesleft = len; byte *vp = buf; static const char noroom[] = "%s: No room for \"%s\" option"; #define NEED(LEN, MSG) do \ if (bytesleft < (LEN)) { \ report(LOG_NOTICE, noroom, \ hp->hostname->string, MSG); \ return (vp - buf); \ } while (0) /* * Note that the following have already been inserted: * magic_cookie, subnet_mask, gateway, bootsize * * The remaining options are inserted in order of importance. * (Of course the importance of each is a matter of opinion.) * The option insertion order should probably be configurable. * * This is the order used in the NetBSD version. Can anyone * explain why the time_offset and swap_server are first? * Also, why is the hostname so far down the list? -gwr */ if (hp->flags.time_offset) { NEED(6, "to"); *vp++ = TAG_TIME_OFFSET;/* -1 byte */ *vp++ = 4; /* -1 byte */ insert_u_long(htonl(hp->time_offset), &vp); /* -4 bytes */ bytesleft -= 6; } /* * swap server, root path, dump path */ if (hp->flags.swap_server) { NEED(6, "sw"); /* There is just one SWAP_SERVER, so it is not an iplist. */ *vp++ = TAG_SWAP_SERVER;/* -1 byte */ *vp++ = 4; /* -1 byte */ insert_u_long(hp->swap_server.s_addr, &vp); /* -4 bytes */ bytesleft -= 6; /* Fix real count */ } if (hp->flags.root_path) { /* * Check for room for root_path. Add 2 to account for * TAG_ROOT_PATH and length. */ len = strlen(hp->root_path->string); NEED((len + 2), "rp"); *vp++ = TAG_ROOT_PATH; *vp++ = (byte) (len & 0xFF); bcopy(hp->root_path->string, vp, len); vp += len; bytesleft -= len + 2; } if (hp->flags.dump_file) { /* * Check for room for dump_file. Add 2 to account for * TAG_DUMP_FILE and length. */ len = strlen(hp->dump_file->string); NEED((len + 2), "df"); *vp++ = TAG_DUMP_FILE; *vp++ = (byte) (len & 0xFF); bcopy(hp->dump_file->string, vp, len); vp += len; bytesleft -= len + 2; } /* * DNS server and domain */ if (hp->flags.domain_server) { if (insert_ip(TAG_DOMAIN_SERVER, hp->domain_server, &vp, &bytesleft)) NEED(8, "ds"); } if (hp->flags.domain_name) { /* * Check for room for domain_name. Add 2 to account for * TAG_DOMAIN_NAME and length. */ len = strlen(hp->domain_name->string); NEED((len + 2), "dn"); *vp++ = TAG_DOMAIN_NAME; *vp++ = (byte) (len & 0xFF); bcopy(hp->domain_name->string, vp, len); vp += len; bytesleft -= len + 2; } /* * NIS (YP) server and domain */ if (hp->flags.nis_server) { if (insert_ip(TAG_NIS_SERVER, hp->nis_server, &vp, &bytesleft)) NEED(8, "ys"); } if (hp->flags.nis_domain) { /* * Check for room for nis_domain. Add 2 to account for * TAG_NIS_DOMAIN and length. */ len = strlen(hp->nis_domain->string); NEED((len + 2), "yn"); *vp++ = TAG_NIS_DOMAIN; *vp++ = (byte) (len & 0xFF); bcopy(hp->nis_domain->string, vp, len); vp += len; bytesleft -= len + 2; } /* IEN 116 name server */ if (hp->flags.name_server) { if (insert_ip(TAG_NAME_SERVER, hp->name_server, &vp, &bytesleft)) NEED(8, "ns"); } if (hp->flags.rlp_server) { if (insert_ip(TAG_RLP_SERVER, hp->rlp_server, &vp, &bytesleft)) NEED(8, "rl"); } /* Time server (RFC 868) */ if (hp->flags.time_server) { if (insert_ip(TAG_TIME_SERVER, hp->time_server, &vp, &bytesleft)) NEED(8, "ts"); } /* NTP (time) Server (RFC 1129) */ if (hp->flags.ntp_server) { if (insert_ip(TAG_NTP_SERVER, hp->ntp_server, &vp, &bytesleft)) NEED(8, "nt"); } /* * I wonder: If the hostname were "promoted" into the BOOTP * response part, might these "extension" files possibly be * shared between several clients? * * Also, why not just use longer BOOTP packets with all the * additional length used as option data. This bootpd version * already supports that feature by replying with the same * packet length as the client request packet. -gwr */ if (hp->flags.name_switch && hp->flags.send_name) { /* * Check for room for hostname. Add 2 to account for * TAG_HOST_NAME and length. */ len = strlen(hp->hostname->string); #if 0 /* * XXX - Too much magic. The user can always set the hostname * to the short version in the bootptab file. -gwr */ if ((len + 2) > bytesleft) { /* * Not enough room for full (domain-qualified) hostname, try * stripping it down to just the first field (host). */ char *tmpstr = hp->hostname->string; len = 0; while (*tmpstr && (*tmpstr != '.')) { tmpstr++; len++; } } #endif NEED((len + 2), "hn"); *vp++ = TAG_HOST_NAME; *vp++ = (byte) (len & 0xFF); bcopy(hp->hostname->string, vp, len); vp += len; bytesleft -= len + 2; } /* * The rest of these are less important, so they go last. */ if (hp->flags.lpr_server) { if (insert_ip(TAG_LPR_SERVER, hp->lpr_server, &vp, &bytesleft)) NEED(8, "lp"); } if (hp->flags.cookie_server) { if (insert_ip(TAG_COOKIE_SERVER, hp->cookie_server, &vp, &bytesleft)) NEED(8, "cs"); } if (hp->flags.log_server) { if (insert_ip(TAG_LOG_SERVER, hp->log_server, &vp, &bytesleft)) NEED(8, "lg"); } /* * XXX - Add new tags here (to insert options) */ if (hp->flags.generic) { if (insert_generic(hp->generic, &vp, &bytesleft)) NEED(64, "(generic)"); } /* * The end marker is inserted by the caller. */ return (vp - buf); #undef NEED } /* dovend_rfc1497 */ /* * Insert a tag value, a length value, and a list of IP addresses into the * memory buffer indirectly pointed to by "dest". "tag" is the RFC1048 tag * number to use, "iplist" is a pointer to a list of IP addresses * (struct in_addr_list), and "bytesleft" points to an integer which * indicates the size of the "dest" buffer. * * Return zero if everything fits. * * This is used to fill the vendor-specific area of a bootp packet in * conformance to RFC1048. */ int insert_ip(tag, iplist, dest, bytesleft) byte tag; struct in_addr_list *iplist; byte **dest; int *bytesleft; { struct in_addr *addrptr; unsigned addrcount = 1; byte *d; if (iplist == NULL) return (0); if (*bytesleft >= 6) { d = *dest; /* Save pointer for later */ **dest = tag; (*dest) += 2; (*bytesleft) -= 2; /* Account for tag and length */ addrptr = iplist->addr; addrcount = iplist->addrcount; while ((*bytesleft >= 4) && (addrcount > 0)) { insert_u_long(addrptr->s_addr, dest); addrptr++; addrcount--; (*bytesleft) -= 4; /* Four bytes per address */ } d[1] = (byte) ((*dest - d - 2) & 0xFF); } return (addrcount); } /* * Insert generic data into a bootp packet. The data is assumed to already * be in RFC1048 format. It is inserted using a first-fit algorithm which * attempts to insert as many tags as possible. Tags and data which are * too large to fit are skipped; any remaining tags are tried until they * have all been exhausted. * Return zero if everything fits. */ static int insert_generic(gendata, buff, bytesleft) struct shared_bindata *gendata; byte **buff; int *bytesleft; { byte *srcptr; int length, numbytes; int skipped = 0; if (gendata == NULL) return (0); srcptr = gendata->data; length = gendata->length; while ((length > 0) && (*bytesleft > 0)) { switch (*srcptr) { case TAG_END: length = 0; /* Force an exit on next iteration */ break; case TAG_PAD: *(*buff)++ = *srcptr++; (*bytesleft)--; length--; break; default: numbytes = srcptr[1] + 2; if (*bytesleft < numbytes) skipped += numbytes; else { bcopy(srcptr, *buff, numbytes); (*buff) += numbytes; (*bytesleft) -= numbytes; } srcptr += numbytes; length -= numbytes; break; } } /* while */ return (skipped); } /* * Insert the unsigned long "value" into memory starting at the byte * pointed to by the byte pointer (*dest). (*dest) is updated to * point to the next available byte. * * Since it is desirable to internally store network addresses in network * byte order (in struct in_addr's), this routine expects longs to be * passed in network byte order. * * However, due to the nature of the main algorithm, the long must be in * host byte order, thus necessitating the use of ntohl() first. */ void insert_u_long(value, dest) u_int32 value; byte **dest; { byte *temp; int n; value = ntohl(value); /* Must use host byte order here */ temp = (*dest += 4); for (n = 4; n > 0; n--) { *--temp = (byte) (value & 0xFF); value >>= 8; } /* Final result is network byte order */ } /* * 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: */ diff --git a/libexec/bootpd/dumptab.c b/libexec/bootpd/dumptab.c index 43e94ec4cef2..daab93f609a6 100644 --- a/libexec/bootpd/dumptab.c +++ b/libexec/bootpd/dumptab.c @@ -1,378 +1,371 @@ /* * dumptab.c - handles dumping the database * * $FreeBSD$ */ #include #include #include /* inet_ntoa */ #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 "report.h" #include "patchlevel.h" #include "bootpd.h" #ifdef DEBUG static void dump_generic(FILE *, struct shared_bindata *); static void dump_host(FILE *, struct host *); static void list_ipaddresses(FILE *, struct in_addr_list *); #endif #ifndef DEBUG void dumptab(filename) char *filename; { report(LOG_INFO, "No dumptab support!"); } #else /* DEBUG */ /* * Dump the internal memory database to bootpd_dump. */ void dumptab(filename) char *filename; { int n; struct host *hp; FILE *fp; time_t t; /* Print symbols in alphabetical order for reader's convenience. */ static char legend[] = "#\n# Legend:\t(see bootptab.5)\n\ #\tfirst field -- hostname (not indented)\n\ #\tbf -- bootfile\n\ #\tbs -- bootfile size in 512-octet blocks\n\ #\tcs -- cookie servers\n\ #\tdf -- dump file name\n\ #\tdn -- domain name\n\ #\tds -- domain name servers\n\ #\tef -- extension file\n\ #\tex -- exec file (YORK_EX_OPTION)\n\ #\tgw -- gateways\n\ #\tha -- hardware address\n\ #\thd -- home directory for bootfiles\n\ #\thn -- host name set for client\n\ #\tht -- hardware type\n\ #\tim -- impress servers\n\ #\tip -- host IP address\n\ #\tlg -- log servers\n\ #\tlp -- LPR servers\n\ #\tms -- message size\n\ #\tmw -- min wait (secs)\n\ #\tns -- IEN-116 name servers\n\ #\tnt -- NTP servers (RFC 1129)\n\ #\tra -- reply address override\n\ #\trl -- resource location protocol servers\n\ #\trp -- root path\n\ #\tsa -- boot server address\n\ #\tsm -- subnet mask\n\ #\tsw -- swap server\n\ #\ttc -- template host (points to similar host entry)\n\ #\ttd -- TFTP directory\n\ #\tto -- time offset (seconds)\n\ #\tts -- time servers\n\ #\tvm -- vendor magic number\n\ #\tyd -- YP (NIS) domain\n\ #\tys -- YP (NIS) servers\n\ #\tTn -- generic option tag n\n\ \n"; /* * Open bootpd.dump file. */ if ((fp = fopen(filename, "w")) == NULL) { report(LOG_ERR, "error opening \"%s\": %s", filename, get_errmsg()); exit(1); } t = time(NULL); fprintf(fp, "\n# %s %s.%d\n", progname, VERSION, PATCHLEVEL); fprintf(fp, "# %s: dump of bootp server database.\n", filename); fprintf(fp, "# Dump taken %s", ctime(&t)); fwrite(legend, 1, sizeof(legend) - 1, fp); n = 0; for (hp = (struct host *) hash_FirstEntry(nmhashtable); hp != NULL; hp = (struct host *) hash_NextEntry(nmhashtable)) { dump_host(fp, hp); fprintf(fp, "\n"); n++; } fclose(fp); report(LOG_INFO, "dumped %d entries to \"%s\".", n, filename); } /* * Dump all the available information on the host pointed to by "hp". * The output is sent to the file pointed to by "fp". */ static void dump_host(fp, hp) FILE *fp; struct host *hp; { /* Print symbols in alphabetical order for reader's convenience. */ if (hp) { fprintf(fp, "%s:", (hp->hostname ? hp->hostname->string : "?")); if (hp->flags.bootfile) { fprintf(fp, "\\\n\t:bf=%s:", hp->bootfile->string); } if (hp->flags.bootsize) { fprintf(fp, "\\\n\t:bs="); if (hp->flags.bootsize_auto) { fprintf(fp, "auto:"); } else { fprintf(fp, "%lu:", (u_long)hp->bootsize); } } if (hp->flags.cookie_server) { fprintf(fp, "\\\n\t:cs="); list_ipaddresses(fp, hp->cookie_server); fprintf(fp, ":"); } if (hp->flags.dump_file) { fprintf(fp, "\\\n\t:df=%s:", hp->dump_file->string); } if (hp->flags.domain_name) { fprintf(fp, "\\\n\t:dn=%s:", hp->domain_name->string); } if (hp->flags.domain_server) { fprintf(fp, "\\\n\t:ds="); list_ipaddresses(fp, hp->domain_server); fprintf(fp, ":"); } if (hp->flags.exten_file) { fprintf(fp, "\\\n\t:ef=%s:", hp->exten_file->string); } if (hp->flags.exec_file) { fprintf(fp, "\\\n\t:ex=%s:", hp->exec_file->string); } if (hp->flags.gateway) { fprintf(fp, "\\\n\t:gw="); list_ipaddresses(fp, hp->gateway); fprintf(fp, ":"); } /* FdC: swap_server (see below) */ if (hp->flags.homedir) { fprintf(fp, "\\\n\t:hd=%s:", hp->homedir->string); } /* FdC: dump_file (see above) */ /* FdC: domain_name (see above) */ /* FdC: root_path (see below) */ if (hp->flags.name_switch && hp->flags.send_name) { fprintf(fp, "\\\n\t:hn:"); } if (hp->flags.htype) { int hlen = haddrlength(hp->htype); fprintf(fp, "\\\n\t:ht=%u:", (unsigned) hp->htype); if (hp->flags.haddr) { fprintf(fp, "ha=\"%s\":", haddrtoa(hp->haddr, hlen)); } } if (hp->flags.impress_server) { fprintf(fp, "\\\n\t:im="); list_ipaddresses(fp, hp->impress_server); fprintf(fp, ":"); } /* NetBSD: swap_server (see below) */ if (hp->flags.iaddr) { fprintf(fp, "\\\n\t:ip=%s:", inet_ntoa(hp->iaddr)); } if (hp->flags.log_server) { fprintf(fp, "\\\n\t:lg="); list_ipaddresses(fp, hp->log_server); fprintf(fp, ":"); } if (hp->flags.lpr_server) { fprintf(fp, "\\\n\t:lp="); list_ipaddresses(fp, hp->lpr_server); fprintf(fp, ":"); } if (hp->flags.msg_size) { fprintf(fp, "\\\n\t:ms=%lu:", (u_long)hp->msg_size); } if (hp->flags.min_wait) { fprintf(fp, "\\\n\t:mw=%lu:", (u_long)hp->min_wait); } if (hp->flags.name_server) { fprintf(fp, "\\\n\t:ns="); list_ipaddresses(fp, hp->name_server); fprintf(fp, ":"); } if (hp->flags.ntp_server) { fprintf(fp, "\\\n\t:nt="); list_ipaddresses(fp, hp->ntp_server); fprintf(fp, ":"); } if (hp->flags.reply_addr) { fprintf(fp, "\\\n\t:ra=%s:", inet_ntoa(hp->reply_addr)); } if (hp->flags.rlp_server) { fprintf(fp, "\\\n\t:rl="); list_ipaddresses(fp, hp->rlp_server); fprintf(fp, ":"); } if (hp->flags.root_path) { fprintf(fp, "\\\n\t:rp=%s:", hp->root_path->string); } if (hp->flags.bootserver) { fprintf(fp, "\\\n\t:sa=%s:", inet_ntoa(hp->bootserver)); } if (hp->flags.subnet_mask) { fprintf(fp, "\\\n\t:sm=%s:", inet_ntoa(hp->subnet_mask)); } if (hp->flags.swap_server) { fprintf(fp, "\\\n\t:sw=%s:", inet_ntoa(hp->subnet_mask)); } if (hp->flags.tftpdir) { fprintf(fp, "\\\n\t:td=%s:", hp->tftpdir->string); } /* NetBSD: rootpath (see above) */ /* NetBSD: domainname (see above) */ /* NetBSD: dumpfile (see above) */ if (hp->flags.time_offset) { fprintf(fp, "\\\n\t:to=%ld:", (long)hp->time_offset); } if (hp->flags.time_server) { fprintf(fp, "\\\n\t:ts="); list_ipaddresses(fp, hp->time_server); fprintf(fp, ":"); } if (hp->flags.vm_cookie) { fprintf(fp, "\\\n\t:vm="); if (!bcmp(hp->vm_cookie, vm_rfc1048, 4)) { fprintf(fp, "rfc1048:"); } else if (!bcmp(hp->vm_cookie, vm_cmu, 4)) { fprintf(fp, "cmu:"); } else { fprintf(fp, "%d.%d.%d.%d:", (int) ((hp->vm_cookie)[0]), (int) ((hp->vm_cookie)[1]), (int) ((hp->vm_cookie)[2]), (int) ((hp->vm_cookie)[3])); } } if (hp->flags.nis_domain) { fprintf(fp, "\\\n\t:yd=%s:", hp->nis_domain->string); } if (hp->flags.nis_server) { fprintf(fp, "\\\n\t:ys="); list_ipaddresses(fp, hp->nis_server); fprintf(fp, ":"); } /* * XXX - Add new tags here (or above, * so they print in alphabetical order). */ if (hp->flags.generic) { dump_generic(fp, hp->generic); } } } static void dump_generic(fp, generic) FILE *fp; struct shared_bindata *generic; { u_char *bp = generic->data; u_char *ep = bp + generic->length; u_char tag; int len; while (bp < ep) { tag = *bp++; if (tag == TAG_PAD) continue; if (tag == TAG_END) return; len = *bp++; if (bp + len > ep) { fprintf(fp, " #junk in generic! :"); return; } fprintf(fp, "\\\n\t:T%d=", tag); while (len) { fprintf(fp, "%02X", *bp); bp++; len--; if (len) fprintf(fp, "."); } fprintf(fp, ":"); } } /* * Dump an entire struct in_addr_list of IP addresses to the indicated file. * * The addresses are printed in standard ASCII "dot" notation and separated * from one another by a single space. A single leading space is also * printed before the first adddress. * * Null lists produce no output (and no error). */ static void list_ipaddresses(fp, ipptr) FILE *fp; struct in_addr_list *ipptr; { unsigned count; struct in_addr *addrptr; if (ipptr) { count = ipptr->addrcount; addrptr = ipptr->addr; while (count > 0) { fprintf(fp, "%s", inet_ntoa(*addrptr++)); count--; if (count) fprintf(fp, ", "); } } } #endif /* DEBUG */ /* * 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: */ diff --git a/libexec/bootpd/hash.c b/libexec/bootpd/hash.c index 64f49d3b957d..1641a8a092cd 100644 --- a/libexec/bootpd/hash.c +++ b/libexec/bootpd/hash.c @@ -1,416 +1,409 @@ /************************************************************************ 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 #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; { 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; unsigned len; { 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; { 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; { 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: */ diff --git a/libexec/bootpd/hwaddr.c b/libexec/bootpd/hwaddr.c index ff996157b911..293c75a6b3be 100644 --- a/libexec/bootpd/hwaddr.c +++ b/libexec/bootpd/hwaddr.c @@ -1,352 +1,344 @@ /* * 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) 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: */ diff --git a/libexec/bootpd/lookup.c b/libexec/bootpd/lookup.c index 54b3f62242f7..391a1d826d6e 100644 --- a/libexec/bootpd/lookup.c +++ b/libexec/bootpd/lookup.c @@ -1,129 +1,124 @@ /* * lookup.c - Lookup IP address, HW address, netmask * * $FreeBSD$ */ #include #include #include /* for struct timeval in net/if.h */ #include #include #ifdef ETC_ETHERS #include extern int ether_hostton(); #endif #include +#include #include -#ifndef USE_BFUNCS -#include -/* Yes, memcpy is OK here (no overlapped copies). */ -#define bcopy(a,b,c) memcpy(b,a,c) -#endif - #include "bootp.h" #include "lookup.h" #include "report.h" /* * Lookup an Ethernet address and return it. * Return NULL if addr not found. */ u_char * lookup_hwa(hostname, htype) char *hostname; int htype; { switch (htype) { /* XXX - How is this done on other systems? -gwr */ #ifdef ETC_ETHERS case HTYPE_ETHERNET: case HTYPE_IEEE802: { static struct ether_addr ea; /* This does a lookup in /etc/ethers */ if (ether_hostton(hostname, &ea)) { report(LOG_ERR, "no HW addr for host \"%s\"", hostname); return (u_char *) 0; } return (u_char *) & ea; } #endif /* ETC_ETHERS */ default: report(LOG_ERR, "no lookup for HW addr type %d", htype); } /* switch */ /* If the system can't do it, just return an error. */ return (u_char *) 0; } /* * Lookup an IP address. * Return non-zero on failure. */ int lookup_ipa(hostname, result) char *hostname; u_int32 *result; { struct hostent *hp; hp = gethostbyname(hostname); if (!hp) return -1; bcopy(hp->h_addr, result, sizeof(*result)); return 0; } /* * Lookup a netmask * Return non-zero on failure. * * XXX - This is OK as a default, but to really make this automatic, * we would need to get the subnet mask from the ether interface. * If this is wrong, specify the correct value in the bootptab. */ int lookup_netmask(addr, result) u_int32 addr; /* both in network order */ u_int32 *result; { int32 m, a; a = ntohl(addr); m = 0; if (IN_CLASSA(a)) m = IN_CLASSA_NET; if (IN_CLASSB(a)) m = IN_CLASSB_NET; if (IN_CLASSC(a)) m = IN_CLASSC_NET; if (!m) return -1; *result = htonl(m); return 0; } /* * 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: */ diff --git a/libexec/bootpd/readfile.c b/libexec/bootpd/readfile.c index 900d0377279f..c09639300310 100644 --- a/libexec/bootpd/readfile.c +++ b/libexec/bootpd/readfile.c @@ -1,2084 +1,2076 @@ /************************************************************************ 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. */ 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. */ 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) */ 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) 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; { 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; { 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]; 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; { 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: */ diff --git a/libexec/bootpd/tools/bootpef/bootpef.c b/libexec/bootpd/tools/bootpef/bootpef.c index 04089c87b560..7ed3786d892e 100644 --- a/libexec/bootpd/tools/bootpef/bootpef.c +++ b/libexec/bootpd/tools/bootpef/bootpef.c @@ -1,331 +1,323 @@ /************************************************************************ 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$ ************************************************************************/ /* * bootpef - BOOTP Extension File generator * Makes an "Extension File" for each host entry that * defines an and Extension File. (See RFC1497, tag 18.) * * HISTORY * See ./Changes * * BUGS * See ./ToDo */ #include #include #include #include #include /* inet_ntoa */ #ifndef NO_UNISTD #include #endif #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 "bootpd.h" #include "dovend.h" #include "readfile.h" #include "report.h" #include "tzone.h" #include "patchlevel.h" #define BUFFERSIZE 0x4000 #ifndef CONFIG_FILE #define CONFIG_FILE "/etc/bootptab" #endif /* * Externals, forward declarations, and global variables */ static void mktagfile(struct host *); static void usage(void); /* * General */ char *progname; char *chdir_path; int debug = 0; /* Debugging flag (level) */ byte *buffer; /* * Globals below are associated with the bootp database file (bootptab). */ char *bootptab = CONFIG_FILE; /* * Print "usage" message and exit */ static void usage() { fprintf(stderr, "usage: $s [ -c chdir ] [-d level] [-f configfile] [host...]\n"); fprintf(stderr, "\t -c n\tset current directory\n"); fprintf(stderr, "\t -d n\tset debug level\n"); fprintf(stderr, "\t -f n\tconfig file name\n"); exit(1); } /* * Initialization such as command-line processing is done and then the * main server loop is started. */ int main(argc, argv) int argc; char **argv; { struct host *hp; char *stmp; int n; progname = strrchr(argv[0], '/'); if (progname) progname++; else progname = argv[0]; /* Get work space for making tag 18 files. */ buffer = (byte *) malloc(BUFFERSIZE); if (!buffer) { report(LOG_ERR, "malloc failed"); exit(1); } /* * Set defaults that might be changed by option switches. */ stmp = NULL; /* * Read switches. */ for (argc--, argv++; argc > 0; argc--, argv++) { if (argv[0][0] != '-') break; switch (argv[0][1]) { case 'c': /* chdir_path */ if (argv[0][2]) { stmp = &(argv[0][2]); } else { argc--; argv++; stmp = argv[0]; } if (!stmp || (stmp[0] != '/')) { fprintf(stderr, "bootpd: invalid chdir specification\n"); break; } chdir_path = stmp; break; case 'd': /* debug */ if (argv[0][2]) { stmp = &(argv[0][2]); } else if (argv[1] && argv[1][0] == '-') { /* * Backwards-compatible behavior: * no parameter, so just increment the debug flag. */ debug++; break; } else { argc--; argv++; stmp = argv[0]; } if (!stmp || (sscanf(stmp, "%d", &n) != 1) || (n < 0)) { fprintf(stderr, "bootpd: invalid debug level\n"); break; } debug = n; break; case 'f': /* config file */ if (argv[0][2]) { stmp = &(argv[0][2]); } else { argc--; argv++; stmp = argv[0]; } bootptab = stmp; break; default: fprintf(stderr, "bootpd: unknown switch: -%c\n", argv[0][1]); usage(); break; } } /* Get the timezone. */ tzone_init(); /* Allocate hash tables. */ rdtab_init(); /* * Read the bootptab file. */ readtab(1); /* force read */ /* Set the cwd (i.e. to /tftpboot) */ if (chdir_path) { if (chdir(chdir_path) < 0) report(LOG_ERR, "%s: chdir failed", chdir_path); } /* If there are host names on the command line, do only those. */ if (argc > 0) { unsigned int tlen, hashcode; while (argc) { tlen = strlen(argv[0]); hashcode = hash_HashFunction((u_char *)argv[0], tlen); hp = (struct host *) hash_Lookup(nmhashtable, hashcode, nmcmp, argv[0]); if (!hp) { printf("%s: no matching entry\n", argv[0]); exit(1); } if (!hp->flags.exten_file) { printf("%s: no extension file\n", argv[0]); exit(1); } mktagfile(hp); argv++; argc--; } exit(0); } /* No host names specified. Do them all. */ hp = (struct host *) hash_FirstEntry(nmhashtable); while (hp != NULL) { mktagfile(hp); hp = (struct host *) hash_NextEntry(nmhashtable); } return (0); } /* * Make a "TAG 18" file for this host. * (Insert the RFC1497 options.) */ static void mktagfile(hp) struct host *hp; { FILE *fp; int bytesleft, len; byte *vp; if (!hp->flags.exten_file) return; vp = buffer; bytesleft = BUFFERSIZE; bcopy(vm_rfc1048, vp, 4); /* Copy in the magic cookie */ vp += 4; bytesleft -= 4; /* * The "extension file" options are appended by the following * function (which is shared with bootpd.c). */ len = dovend_rfc1497(hp, vp, bytesleft); vp += len; bytesleft -= len; if (bytesleft < 1) { report(LOG_ERR, "%s: too much option data", hp->exten_file->string); return; } *vp++ = TAG_END; bytesleft--; /* Write the buffer to the extension file. */ printf("Updating \"%s\"\n", hp->exten_file->string); if ((fp = fopen(hp->exten_file->string, "w")) == NULL) { report(LOG_ERR, "error opening \"%s\": %s", hp->exten_file->string, get_errmsg()); return; } len = vp - buffer; if (len != fwrite(buffer, 1, len, fp)) { report(LOG_ERR, "write failed on \"%s\" : %s", hp->exten_file->string, get_errmsg()); } fclose(fp); } /* mktagfile */ /* * 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: */ diff --git a/libexec/bootpd/tools/bootptest/bootptest.h b/libexec/bootpd/tools/bootptest/bootptest.h index 2df35dea7ffc..2d9e451bddef 100644 --- a/libexec/bootpd/tools/bootptest/bootptest.h +++ b/libexec/bootpd/tools/bootptest/bootptest.h @@ -1,26 +1,18 @@ /* bootptest.h */ /* $FreeBSD$ */ /* * Hacks for sharing print-bootp.c between tcpdump and bootptest. */ #define ESRC(p) (p) #define EDST(p) (p) -#ifndef USE_BFUNCS -/* Use mem/str functions */ -/* There are no overlapped copies, so memcpy is OK. */ -#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 - extern int vflag; /* verbose flag */ /* global pointers to beginning and end of current packet (during printing) */ extern unsigned char *packetp; extern unsigned char *snapend; void bootp_print(struct bootp *bp, int length, u_short sport, u_short dport); char *ipaddr_string(struct in_addr *); int printfn(u_char *s, u_char *ep);