?? dhcpclib.c
字號(hào):
/* dhcpcLib.c - Dynamic Host Configuration Protocol (DHCP) run-time client API *//* Copyright 1984 - 2002 Wind River Systems, Inc. */#include "copyright_wrs.h"/*modification history--------------------02k,25apr02,wap Correct arguments passed to dhcpcOptionAdd() for little-endian targets (SPR #73769)02j,23apr02,wap use dhcpTime() instead of time() (SPR #68900)02i,08mar02,wap Allow DHCP to work at boot time when the boot device is not a network interface (SPR #73762)02h,10dec01,wap Fix bugs in dhcpcConfigSet() (SPR #72056)02g,07dec01,vvv test dhcpcEventAdd return value in dhcpcRelease02f,03dec01,vvv fixed interface configuration after dhcpcRelease (SPR #70026)02e,05nov01,wap dhcpcLeaseCleanup() fails to remove pLeaseData pointers from global dhcpcLeaseList (SPR #68981)02d,26oct01,vvv fixed dhcpcBind doc02c,15oct01,rae merge from truestack ver 02f, base 01u (SPRs 28985, 65264, 67272, 65380, 65424, 29785)02b,24may01,mil Bump up dhcp state task stack size to 5000.02a,17nov00,spm added support for BSD Ethernet devices01z,16nov00,spm enabled new DHCP lease for runtime device setup (SPR #20438)01y,16nov00,spm fixed modification history after tor3_x merge01x,13nov00,kbw changed text of dhcpcParamsGet man page (SPR 28985)01w,23oct00,niq merged from version 01z of tor3_x branch (base version 01u)01v,19oct00,dgr docs: clarified sname/file retrieval with dhcpcParamsGet()01u,17mar99,spm fixed dhcpcRelease() and dhcpcVerify() routines (SPR #25482)01t,05feb99,dgp document errno values01s,10dec97,kbw fixed minor spelling issues in man pages01r,04dec97,spm added code review modifications; increased stack size for monitor task to 50% over maximum for ss5 board01q,27oct97,spm corrected name field to contain device name only01p,21oct97,kbw fixed minor spelling issues in man pages01o,06oct97,spm removed reference to deleted endDriver global; replaced with support for dynamic driver type detection01n,25sep97,gnn SENS beta feedback fixes01m,02sep97,spm removed unused global variable for event hook routine01l,26aug97,spm major overhaul: reorganized code and changed user interface to support multiple leases at runtime01k,12aug97,gnn changes necessitated by MUX/END update.01j,06aug97,spm removed parameters linked list to reduce memory required; corrected minor error in man pages introduced by 01i revision01i,30jul97,kbw fixed man page problems found in beta review01h,15jul97,spm fixed byte ordering of netmask from DHCP client (SPR #8739)01g,10jun97,spm fixed code layout and error in client lease indicator01f,02jun97,spm changed DHCP option tags to prevent name conflicts (SPR #8667) and updated man pages01e,30apr97,spm changed dhcpcOptionGet() to return length; expanded man pages01d,15apr97,kbw fixed format problems in man page text, changed some wording01c,07apr97,spm altered to use current value of configAll.h defines, fixed user requests, inserted code previously in usrNetwork.c, rewrote documentation01b,29jan97,spm added END driver support and modified to fit coding standards.01a,03oct96,spm created by modifying WIDE Project DHCP Implementation.*//*DESCRIPTIONThis library implements the run-time access to the client side of the Dynamic Host Configuration Protocol (DHCP). DHCP is an extension of BOOTP. Like BOOTP, the protocol allows a host to initialize automatically by obtainingits IP address, boot file name, and boot host's IP address over a network. Additionally, DHCP provides a client with the complete set of parametersdefined in the Host Requirements RFCs and allows automatic reuse of network addresses by specifying individual leases for each set of configuration parameters. The compatible message format allows DHCP participants to interact with BOOTP participants. The dhcpcLibInit() routine links this library into the VxWorks image. This happens automatically if INCLUDE_DHCPC is defined at the time the image is built.CONFIGURATION INTERFACEWhen used during run time, the DHCP client library establishes and maintainsone or more DHCP leases. Each lease provides access to a set of configuration parameters. If requested, the parameters retrieved will be used to reconfigure the associated network interface, but may also be handled separately through an event hook. The dhcpcEventHookAdd() routine specifies a function which is invoked whenever the lease status changes. The dhcpcEventHookDelete() routine will disable that notification. The automatic reconfiguration must be limited to one lease for a particular network interface. Otherwise, multiple leases would attempt to reconfigure the same device, with unpredictable results.HIGH-LEVEL INTERFACETo access the DHCP client during run time, an application must first call the dhcpcInit() routine with a pointer to the network interface to be used for communication with a DHCP server. Each call to the initialization routine returns a unique identifier to be used in subsequent calls to the DHCP client routines. Next, the application must specify a client identifier for the lease using the dhcpcOptionSet() call. Typically, the link-level hardware address is used for this purpose. Additional calls to the option set routine may be used to request specific DHCP options. After all calls to that routine are completed, a call to dhcpcBind() will retrieve a set of configuration parameters according to the client-server interaction detailed in RFC 1541.Each sequence of the three function calls described above, if successful,will retrieve a set of configuration parameters from a DHCP server. ThedhcpcServerGet() routine retrieves the address of the server that provided a particular lease. The dhcpcTimerGet() routine will retrieve the current values for both lease timers. Alternatively, the dhcpcParamsGet() and dhcpcOptionGet() routines will access any options provided by a DHCP server. In addition to the lease identifierobtained from the initialization routine, the dhcpcParamsGet() routine accepts a parameter descriptor structure that selects any combination of the options described in RFC 1533 for retrieval. Similarly, the dhcpcOptionGet() routine retrieves the values associated with a single option.LOW-LEVEL INTERFACEThis library also contains several routines which explicitly generate DHCP messages. The dhcpcVerify() routine causes the client to renew a particularlease, regardless of the time remaining. The dhcpcRelease() routine relinquishes the specified lease. The associated parameters are no longer valid. If those parameters were used by the underlying network device, the routine also shuts off all network processing for that interface. Finally,the dhcpcShutdown() routine will release all active leases and disable allthe DHCP client library routines.OPTIONAL INTERFACEThe dhcpcCacheHookAdd() routine registers a function that the client willuse to store and retrieve lease data. The client can then re-use this information if it is rebooted. The dhcpcCacheHookDelete() routine prevents the re-use of lease data. Initially, a function to access permanent storage is not provided.INTERNALThe diagram below defines the structure chart of dhcpcLib. | | | v v v dhcpcLibInit dhcpcSetup dhcpcConfigSet -------\ | / | \ \ v | | | | dhcpcMon v | v |(spawned task) dhcpcInit | dhcpcBind | | | | | | | v v dhcpcOptionSet dhcpcParamsGetThis library provides a wrapper for the WIDE project DHCP code found in thedirectory /vobs/wpwr/target/src/dhcp, which contains the state machine andother supporting functions. The monitor task redirects incoming messages,timeout events, and user requests to the appropriate state in the statemachine. The input hook used to retrieve incoming messages and themonitor task routines are both in the dhcpcCommonLib module in this directory.The current RFC specification does not allow users to obtain parameterswith DHCP without also obtaining a new IP address. This limitation requiresnetwork shutdown if the lease used by an interface is not maintained. It also artificially limits the use of this library to routines involving an active lease. The draft RFC for the successor to RFC 1541 adds a new message which avoids this problem. Once published, DHCP can safely be used within an application without risking network shutdown for any interface which was statically configured during system boot. The code which shuts down the network should then be limited to execute conditionally on interfaces whichhave no backup source of addressing information.INCLUDE FILES: dhcpcLib.hSEE ALSO: RFC 1541, RFC 1533*//* includes */#include "dhcp/copyright_dhcp.h"#include "vxWorks.h"#include "bootLib.h"#include "sockLib.h"#include "ioLib.h" /* ioctl() declaration */#include "vxLib.h" /* checksum() declaration */#include "sysLib.h"#include "wdLib.h"#include "semLib.h"#include "inetLib.h"#include "taskLib.h"#ifdef DHCPC_DEBUG#include "logLib.h"#endif#include "muxLib.h"#include "stdio.h"#include "stdlib.h"#include "unistd.h"#include "string.h"#include "errno.h"#include "signal.h"#include "fcntl.h"#include "sys/types.h"#include "sys/socket.h"#include "sys/ioctl.h"#include "net/if.h"#include "netinet/in.h"#include "netinet/in_systm.h"#include "netinet/if_ether.h"#include "netinet/ip.h"#include "netinet/udp.h"#include "arpa/inet.h"#include "time.h"#include "dhcpcLib.h"#include "dhcp/dhcpcStateLib.h"#include "dhcp/dhcpcCommonLib.h"#include "dhcp/dhcpcInternal.h"#include "end.h"#include "ipProto.h"#include "bpfDrv.h"/* defines */#define _DHCP_MAX_OPTLEN 255 /* Max. number of bytes in an option */#define _DHCPC_MAX_DEVNAME 21 /* "/bpf/dhcpc" + max unit number *//* externals */IMPORT RING_ID dhcpcEventRing; /* Ring buffer of DHCP events */IMPORT SEM_ID dhcpcEventSem; /* DHCP event notification */IMPORT int dhcpcReadTaskId; /* Identifier for data retrieval task */IMPORT int _dhcpcReadTaskPriority; /* Priority level of data retriever */IMPORT int _dhcpcReadTaskOptions; /* Option settings of data retriever */IMPORT int _dhcpcReadTaskStackSize; /* Stack size of data retriever */IMPORT struct bpf_insn dhcpfilter[]; /* Needed to update client port. */IMPORT struct bpf_program dhcpread; /* Installs filter for DHCP messages */IMPORT LEASE_DATA ** dhcpcLeaseList; /* List of available cookies. */IMPORT MESSAGE_DATA * dhcpcMessageList; /* Available DHCP messages. */IMPORT int dhcpcMaxLeases; /* configAll.h #define value */IMPORT int dhcpcMinLease; /* configAll.h #define value */IMPORT int dhcpcBufSize; /* sets size of transmit and receive buffers */IMPORT int dhcpcDataSock; /* Receives DHCP messages *//* globals */void * pDhcpcBootCookie = NULL; /* Access to boot-time lease. */BOOL dhcpcInitialized = FALSE; /* Client initialized? */SEM_ID dhcpcMutexSem; /* Protects the DHCP status indicator */DHCP_LEASE_DATA dhcpcBootLease; /* Boot-time lease settings. */int _dhcpcStateTaskPriority = 56; /* Priority level of lease monitor */int _dhcpcStateTaskOptions = 0; /* Option settings of lease monitor */int _dhcpcStateTaskStackSize = 5000; /* Stack size of lease monitor */LOCAL int dhcpcOfferTimeout; /* configAll.h #define value */LOCAL int dhcpcDefaultLease; /* configAll.h #define value */LOCAL FUNCPTR dhcpcCacheHookRtn; /* Data storage/retrieval function */LOCAL int dhcpcSignalSock; /* Indicates start of lease session */LOCAL char dhcpcSignalData [UDPHL + IPHL + 1]; /* Contents of signal */LOCAL int dhcpcSignalSize = UDPHL + IPHL + 1;/* forward declarations */LOCAL void dhcpcState (void); /* Monitor pending/active leases */LOCAL STATUS dhcpcEventGet (EVENT_DATA *);LOCAL STATUS dhcpcEventHandle (EVENT_DATA *);LOCAL void dhcpcCleanup (void);LOCAL char *dhcpcOptionFind (LEASE_DATA *, int, int *); /* Locate option */IMPORT void dhcpcRead (void); /* Retrieve incoming DHCP messages */STATUS dhcpcVerify (void *); /* Renew lease *//********************************************************************************* dhcpcLibInit - DHCP client library initialization** This routine creates and initializes the global data structures used by * the DHCP client library to maintain multiple leases, up to the limit * specified by the <maxLeases> parameter. Every subsequent lease attempt will* collect additional DHCP offers until the interval specified by <offerTimeout>* expires and will request the lease duration indicated by <defaultLease>.* The <maxSize> parameter specifies the maximum length supported for any DHCP* message, including the UDP and IP headers and the largest link level header* for all supported devices. The maximum length of the DHCP options field is* based on this value or the MTU size for a lease's underlying interface,* whichever is less. The smallest valid value for the <maxSize> parameter is* 576 bytes, corresponding to the minimum IP datagram a host must accept.* Larger values will allow the client to handle longer DHCP messages.** This routine must be called before calling any other library routines. The * routine is called automatically if INCLUDE_DHCPC is defined at the time the * system is built and assigns the global lease settings to the values specified* by DHCPC_SPORT, DHCPC_CPORT, DHCPC_MAX_LEASES, DHCPC_MAX_MSGSIZE,* DHCPC_DEFAULT_LEASE, and DHCPC_OFFER_TIMEOUT.** RETURNS: OK, or ERROR if initialization fails.** ERRNO: S_dhcpcLib_MEM_ERROR* */STATUS dhcpcLibInit ( int serverPort, /* port used by DHCP servers (default 67) */ int clientPort, /* port used by DHCP clients (default 68) */ int maxLeases, /* max number of simultaneous leases allowed */ int maxSize, /* largest DHCP message supported, in bytes */ int offerTimeout, /* interval to get additional DHCP offers */ int defaultLease, /* default value for requested lease length */ int minLease /* minimum accepted lease length */ ) { int offset; int loop; int bufSize; /* Size of receive buffer (maxSize + BPF header) */ int stateTaskId; /* Identifier for client monitor task */ STATUS result; struct sockaddr_in dstaddr; struct ip * pIph; struct udphdr * pUdph; if (dhcpcInitialized) return (OK); if (maxSize < DFLTDHCPLEN + UDPHL + IPHL) { errno = S_dhcpcLib_MEM_ERROR; return (ERROR); } /* Create a socket to signal the read task when a new session starts. */ dhcpcSignalSock = socket (AF_INET, SOCK_RAW, IPPROTO_RAW); if (dhcpcSignalSock < 0) return (ERROR); offset = 1; result = setsockopt (dhcpcSignalSock, IPPROTO_IP, IP_HDRINCL, (char *)&offset, sizeof (int)); if (result != OK) { close (dhcpcSignalSock); return (ERROR); } bzero ( (char *)&dstaddr, sizeof (dstaddr)); dstaddr.sin_family = AF_INET; dstaddr.sin_addr.s_addr = htonl (0x7f000001); /* 127.0.0.1: loopback */ result = connect (dhcpcSignalSock, (struct sockaddr *) &dstaddr, sizeof (dstaddr)); if (result != OK) { close (dhcpcSignalSock); return (ERROR); } /* Create the signalling message (sent to loopback at DHCP client port). */ bzero (dhcpcSignalData, UDPHL + IPHL + 1); pIph = (struct ip *)dhcpcSignalData; pUdph = (struct udphdr *) (dhcpcSignalData + IPHL); pIph->ip_v = IPVERSION; pIph->ip_hl = IPHL >> 2; pIph->ip_tos = 0; pIph->ip_len = UDPHL + IPHL + 1; pIph->ip_id = htons (0xF1C); pIph->ip_off = IP_DF; pIph->ip_ttl = 0x20; pIph->ip_p = IPPROTO_UDP; pIph->ip_src.s_addr = 0; pIph->ip_dst.s_addr = htonl(0x7f000001); /* 127.0.0.1: loopback */ pIph->ip_sum = checksum ( (u_short *)pIph, IPHL);
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -