⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 database.c

📁 VXWORKS源代码
💻 C
📖 第 1 页 / 共 5 页
字号:
/* database.c - DHCP server data retrieval code *//* Copyright 1984 - 2002 Wind River Systems, Inc. */#include "copyright_wrs.h"/*modification history--------------------01o,07may02,wap  Put debug messages under DHCPS_DEBUG (SPR #76495)01n,29oct01,wap  Fix use of get_integer() with htons()/htonl() (SPR #34808)01m,12oct01,rae  merge from truestack ver 01n, base 01j                 SPRs 69547, 65163, 3357601l,24oct00,spm  fixed modification history after tor3_x merge01k,23oct00,niq  merged from version 01l of tor3_x branch (base version 01j)01j,17dec97,spm  fixed byte order of address-based loop boundaries (SPR #20056)01i,04dec97,spm  added code review modifications01h,06oct97,spm  added newlines and component labels to default output01g,26aug97,spm  modified comments for all routines01f,02jun97,spm  added test for optional storage routine and updated man pages01e,08may97,spm  corrected use of storage routines, removed memory leak, and                 documented shutdown of server 01d,30apr97,spm  added missing START call to DHCPS_LEASE_HOOK storage routine01c,18apr97,spm  added conditional include DHCPS_DEBUG for displayed output01b,08apr97,spm  corrected byte ordering when adding MTU plateau table option01a,07apr97,spm  created by modifying WIDE project DHCP implementation*//*DESCRIPTIONThis library contains the code used by the DHCP server to access permanentstorage through two optional function hooks provided by the user. The function specified by dhcpsAddressHookAdd() is used to store and retrieve address pool entries which are added by the user with dhcpsLeaseEntryAdd(). This capability allows the user to bypass the static table definition andadd entries without recompiling the runtime image. If the storage hook isnot provided, only the address pool entries contained in the static tableswill be retained across server reboots. As a result, any client using otheraddress pool entries will be unable to renew its lease.The second storage hook, specified by dhcpsLeaseHookAdd(), is much more critical. It is used to store and retrieve the subset of address pool entries which have been offered to a client, or are currently in use. If this storage hook is not provided, the server might issue network addresses which are already in use, causing unpredictable results.INCLUDE_FILES: dhcpsLib.h*//* * WIDE Project DHCP Implementation * Copyright (c) 1995 Akihiro Tominaga * Copyright (c) 1995 WIDE Project * All rights reserved. * * Permission to use, copy, modify and distribute this software and its * documentation is hereby granted, provided only with the following * conditions are satisfied: * * 1. Both the copyright notice and this permission notice appear in *    all copies of the software, derivative works or modified versions, *    and any portions thereof, and that both notices appear in *    supporting documentation. * 2. All advertising materials mentioning features or use of this software *    must display the following acknowledgement: *      This product includes software developed by WIDE Project and *      its contributors. * 3. Neither the name of WIDE Project nor the names of its contributors *    may be used to endorse or promote products derived from this software *    without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPER ``AS IS'' AND WIDE * PROJECT DISCLAIMS ANY LIABILITY OF ANY KIND FOR ANY DAMAGES * WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. ALSO, THERE * IS NO WARRANTY IMPLIED OR OTHERWISE, NOR IS SUPPORT PROVIDED. * * Feedback of the results generated from any improvements or * extensions made to this software would be much appreciated. * Any such feedback should be sent to: *  *  Akihiro Tominaga *  WIDE Project *  Keio University, Endo 5322, Kanagawa, Japan *  (E-mail: dhcp-dist@wide.ad.jp) * * WIDE project has the rights to redistribute these changes. *//* includes */#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <ctype.h>#include <string.h>#include <time.h>#include <sys/types.h>#include <netinet/in.h>#include <arpa/inet.h>#include <inetLib.h>#include <logLib.h>#include "dhcp/dhcp.h"#include "dhcp/common.h"#include "dhcpsLib.h"#include "dhcp/hash.h"#include "dhcp/database.h"/* global variables for both virtual stack and regular stack */IMPORT long dhcps_dflt_lease; 	/* Default for default lease length. */IMPORT long dhcps_max_lease; 	/* Default for maximum lease length. */IMPORT DHCPS_LEASE_DESC *	pDhcpsLeasePool;#ifndef VIRTUAL_STACK/* globals */struct hash_tbl cidhashtable;struct hash_tbl iphashtable;struct hash_tbl nmhashtable;struct hash_tbl relayhashtable;struct hash_tbl paramhashtable;struct hash_member *bindlist;struct hash_member *reslist;#else#include "netinet/vsLib.h"#include "netinet/vsDhcps.h"#endif /* VIRTUAL_STACK */IMPORT void dhcpsFreeResource (struct dhcp_resource *);/********************************************************************************* dump_bind_db - write all active bindings to permanent storage** This routine takes a snapshot of the linked list which contains the* descriptors for each active or pending lease. It calls a hook routine, * supplied by the user, to record these entries in permanent storage. This * storage is required to maintain the consistency of the server data * structures and is the key to the integrity of the entire DHCP protocol. ** RETURNS: N/A** ERRNO: N/A** NOMANUAL*/void dump_bind_db (void)    {    struct hash_member *bindptr = NULL;    STATUS result;    if (dhcpsLeaseHookRtn == NULL)        return;    result = (* dhcpsLeaseHookRtn) (DHCPS_STORAGE_STOP, NULL, 0);    if (result != OK)          {         logMsg ("Warning: cannot close the binding database.\n",                   0, 0, 0, 0, 0, 0);         return;         }    /* Remove old values. */    result = (* dhcpsLeaseHookRtn) (DHCPS_STORAGE_CLEAR, NULL, 0);    if (result != OK)          {         logMsg ("Warning: cannot clear the binding database.\n",                  0, 0, 0, 0, 0, 0);         return;         }    result = (* dhcpsLeaseHookRtn) (DHCPS_STORAGE_START, NULL, 0);    if (result != OK)          {         logMsg ("Warning: cannot open the binding database.\n",                   0, 0, 0, 0, 0, 0);         return;         }    bindptr = bindlist;    while (bindptr != NULL)         {        dump_bind_entry(bindptr->data);        bindptr = bindptr->next;        }    return;    }/********************************************************************************* dump_bind_entry - write a binding record to permanent storage** This routine calls a hook routine, supplied by the user, to store the entry * for an active lease. The stored entry takes the following form:**    <client ID>:<subnet number>:<H/W address>:<expiration time>:<entry name>** where the entry name identifies the corresponding entry in the address pool.** RETURNS: N/A** ERRNO: N/A** NOMANUAL*/void dump_bind_entry    (     struct dhcp_binding *	bp	/* binding record to add to storage */    )    {    char tmp [30];                /* Maximum length of quoted date string. */    char new_entry [100];         /*                                    * Maximum length of entry -                                   * type/ID, subnet, hardware address,                                   * expiration time, and entry name.                                    */    /*      * Do not store incomplete or static entries. Incomplete entries result     * when the corresponding address fails an ICMP check, indicating     * it is in use by an unknown client. A static binding entry is     * created for each manual lease in the address pool. Since they     * implicitly provide an infinite lease to a specific client, storage      * of their current state is meaningless.      */    if ( (bp->flag & COMPLETE_ENTRY) == 0 || (bp->flag & STATIC_ENTRY) != 0)        return;    /* Convert the data structure into a formatted string. */    sprintf (new_entry, "%s:", cidtos (&bp->cid, 1));    sprintf (tmp, "%s:", haddrtos (&bp->haddr));    strcat (new_entry, tmp);    if (bp->expire_epoch == 0xffffffff)         {        if (bp->flag & BOOTP_ENTRY)            sprintf(tmp, "\"bootp\":");        else            sprintf(tmp, "\"infinity\":");        }    else if (bp->expire_epoch == 0)        sprintf(tmp, "\"\":");    else         {        sprintf (tmp, "\"%s", (char *)ctime (&bp->expire_epoch));            /* Replace '\n' added by ctime() with the closing quote. */        tmp [strlen (tmp) - 1] = '"';        strcat (tmp, ":");            /* Append field delimiter. */        }    strcat (new_entry, tmp);    sprintf (tmp, "%s\n", bp->res_name);    strcat (new_entry, tmp);    /* Call the user-supplied storage hook to save the entry. */    (* dhcpsLeaseHookRtn) (DHCPS_STORAGE_WRITE, new_entry, strlen (new_entry));    return;    }/********************************************************************************* finish - cleanup and remove data structures before exiting** This "routine" contains the functions needed for an orderly shutdown of * the server task. The dump_bind_db() routine stores a snapshot of all active* leases and dhcpsCleanup() removes the installed packet filter device and all* dynamically allocated memory. In the original code, this routine was * triggered by SIGTERM or SIGINT. This is not a working example, since* the server task created at system startup is not removed. The code is not* included in the DHCP release.** RETURNS: N/A** ERRNO: N/A** NOMANUAL*//* void finish (void)    {    dump_bind_db ();    dhcpsCleanup (6);    /@ Instead of exit(), the entry point of the server task should return. @/    exit (0);     }  *//********************************************************************************* add_bind - record lease offers and active leases** This routine stores the pending offers and active leases in the internal* linked list. The contents of the list are periodically written to permanent* storage by the dump_bind_db() routine defined above.** RETURNS: 0 if successful, or -1 on memory allocation error.** ERRNO: N/A** NOMANUAL*/int add_bind    (    struct dhcp_binding *	bind	/* binding record to store in memory */    )    {    struct hash_member *bindptr;#ifndef VIRTUAL_STACK    extern struct hash_member *bindlist;#endif    bindptr = (struct hash_member *)calloc (1, sizeof (struct hash_member));    if (bindptr == NULL)         {#ifdef DHCPS_DEBUG        logMsg ("Warning: memory allocation error adding binding.\n",                 0, 0, 0, 0, 0, 0);#endif        return (-1);        }    bindptr->next = bindlist;    bindptr->data = (hash_datum *)bind;    bindlist = bindptr;    nbind++;    return (0);    }/********************************************************************************* read_idtype - extract identifier type from input string** This routine extracts the single byte which contains the numeric type from * a numeric pair of the form <type>:<value>. It is used when parsing entries * from the client identifier field of the address pool and binding databases, * and for reading from the hardware address field contained in the binding * database. Valid values for the ID type are listed in the "Assigned Numbers" * RFC under the ARP section. RFC 1700 defined the following types:**	 Number Hardware Type (hrd)                 * 	------ -----------------------------------*	      1 Ethernet (10Mb)*	      2 Experimental Ethernet (3Mb)*	      3 Amateur Radio AX.25*	      4 Proteon ProNET Token Ring*	      5 Chaos*	      6 IEEE 802 Networks*	      7 ARCNET*	      8 Hyperchannel*	      9 Lanstar*	     10 Autonet Short Address*	     11 LocalTalk*	     12 LocalNet (IBM PCNet or SYTEK LocalNET)*	     13 Ultra link*	     14 SMDS*	     15 Frame Relay*	     16 Asynchronous Transmission Mode (ATM)*	     17 HDLC*	     18 Fibre Channel*	     19 Asynchronous Transmission Mode (ATM)*	     20 Serial Line*	     21 Asynchronous Transmission Mode (ATM)** RETURNS: 0 if successful, or -1 on parse error.** ERRNO: N/A** NOMANUAL*/static int read_idtype    (    char **cp, 		/* current location in input string */    u_char *idtype 	/* pointer to storage for extracted value */    )    {    char tmpstr [MAXSTRINGLEN];    int j;    get_string (cp, tmpstr);     if (sscanf (tmpstr, "%d", &j) != 1)         {#ifdef DHCPS_DEBUG        logMsg ("Warning: Can't extract type value.\n", 0, 0, 0, 0, 0, 0);#endif        return (-1);        }    *idtype = (u_char) j;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -