Do you have a question about the TMS320C6000 and is the answer not in the manual?
Questions and answers
Summary of Contents for Texas TMS320C6000
Page 1
TMS320C6000 TCP/IP Network Developer’s Kit (NDK) Programmer’s Reference Guide Literature Number: SPRU524A October 2001 Printed on Recycled Paper...
Page 2
IMPORTANT NOTICE Texas Instruments Incorporated and its subsidiaries (TI) reserve the right to make corrections, modifications, enhancements, improvements, and other changes to its products and services at any time and to discontinue any product or service without notice. Customers should obtain the latest relevant information before placing orders and should verify that such information is current and complete.
Page 3
API functions provided by the stack li- braries. It will be the central reference document used when programming the stack. Users should first refer to the TMS320C6000 TCP/IP Network Develop- er’s Kit (NDK) User’s Guide (SPRU523) to familiarize themselves with the stack libraries and in using the stack with DSP/BIOS...
Page 4
The following typographical conventions are used in this specification: Text inside back-quotes (‘‘) represents pseudo-code Program source code, function and macro names, parameters, and com- mand line commands are shown in a mono-spaced font. Trademarks TMS320C6000, Code composer Studio, and DSP/BIOS are trademarks of Texas Instruments.
Chapter 1 Introduction This chapter serves as an introduction to the programming API reference for the TMS320C6000 TCP/IP Network Developer’s Kit (NDK). Topic Page This Document ..........
This Document 1.1 This Document This Programmer’s Reference Guide for the TCP/IP Stack Network Develop- er’s Kit (NDK) is mainly a programming API reference guide. It is intended to aid in the development of network applications and describes the various API functions provided by the stack libraries.
1.2 Additional Documentation The following additional documents are also available. 1.2.1 TMS320C6000 TCP/IP NDK User’s Guide Although this Programmer’s Reference Guide will be the central reference document used when programming the stack, users should first refer to the TCP/IP NDK User’s Guide to familiarize themselves with the stack libraries, and in using the stack with DSP/BIOS and Code Composer Studio.
Chapter 2 Operating System Abstraction API In order to keep the stack system portable, it was coded to a very compact Op- erating System Abstraction. The stack can execute in any operating environ- ment by porting the functions described here. Most of these functions will map directly to a native OS counterpart.
Operating System Configuration 2.1 Operating System Configuration 2.1.1 Synopsis The OS has a couple of configuration options that regulate its behavior. These are stored in a data structure. The types of properties defined in the structure are those that would typically be macros, but using a data structure allows the values to be changed without rebuilding the libraries.
Page 13
Operating System Configuration Debug Message Abort Threshold _oscfg.DbgAbortLevel Default Value DBG_ERROR Description This is the lowest severity level of a system debug message (call to DbgPrintf() function) that will result in a system shutdown (call to NC_NetSop()). The threshold may be raised. The legal values for this variable are: DBG_INFO, DBG_WARN, DBG_ERROR, and DBG_NONE.
Page 14
Operating System Configuration Minimum Task Stack Size _oscfg.TaskStkLow Default Value 3072 Description This is the stack size used for network task that do very little network process- ing, or do not use TCP. Normal Task Stack Size _oscfg.TaskStkNorm Default Value 4096 Description This is the stack size used for a network task with an average network band-...
Task Support 2.2 Task Support 2.2.1 Synopsis The task object provides a method of manipulating task threads using a gener- ic task handle. Task threads are executed on a priority based method, with a least–recently–run algorithm used on those with equal priority. Each task thread has its own private stack.
Page 16
Task Support Priority Task priority level (0–15) StackSize Task stack size Arg1 Optional task function argument 1 Arg2 Optional task function argument 2 Arg3 Optional task function argument 3 Return Value Returns a Task Handle on success or NULL on memory failure. Description Creates a new task object.
Page 17
Task Support Destroy a Task Thread TaskDestroy Syntax void TaskDestroy( HANDLE hTask ); Parameter(s) hTask Handle to target task Return Value nothing Description Terminates execution of the task object specified by the supplied handle hTask, and frees task object from system memory. Note that memory allocated by the task thread is not associated with the task thread and must be freed manually by the programmer.
Page 18
Task Support Get the Handle to the Currently Executing Task Thread TaskSelf Syntax HANDLE TaskSelf(); Parameter(s) none Return Value Handle to currently executing thread, or NULL on error Description Returns the task handle of the currently executing task thread. This function is used mainly in other task object calls where the caller wishes to operate on the current thread, but does not know the current thread’s handle.
Page 19
Task Support Set Task Priority TaskSetPri Syntax int TaskSetPri( HANDLE hTask, int Priority ); Parameter(s) hTask Handle to target task Priority Task priority level Return Value Previous task priority level Description Sets the priority of the target task to the specified value. The value of Priority is constrained only by the size of an int on the target environment, but a range of 0 to 15 is recommended.
Semaphore Support 2.3 Semaphore Support 2.3.1 Synopsis The semaphore object provides a method of manipulating counting sema- phores using a generic handle. Semaphores can be used for both task synchronization and mutual exclusion. 2.3.2 Function Overview The Semaphore Object access functions (in functional order) are as follows: SemCreate() Create new semaphore SemDelete()
Page 21
Semaphore Support Delete Semaphore SemDelete Syntax void SemDelete( HANDLE hSem ); Parameter(s) hSem Handle to Semaphore Return Value nothing Description Deletes the semaphore object and frees related memory. Any task currently waiting on this semaphore is blocked forever – even if it orig- inally specified a timeout to SemPend().
Page 22
Semaphore Support Signal a Semaphore SemPost Syntax void SemPost( HANDLE hSem ); Parameter(s) hSem Handle to Semaphore Return Value nothing Description This function is used to signal a semaphore. If the semaphore count is greater than 0 (or is equal to 0, but without any pend- ing task threads), the semaphore count is incremented and this function imme- diately returns.
Memory Allocation Support 2.4 Memory Allocation Support 2.4.1 Synopsis As part of normal stack operation, memory will be allocated and freed on a reg- ular basis. It is therefore recommended that a memory support system have the ability to allocate and free small memory blocks in a variety of sizes, without memory fragmentation.
Page 24
Memory Allocation Support Allocate Bulk Memory Block mmBulkAlloc Syntax void *mmBulkAlloc( INT32 Size ); Return Value Pointer to allocated memory or NULL on error Description Allocates a memory block of at least size bytes in length. The function returns a pointer to the new memory block, or NULL if memory is not available. The size of the allocation is not restricted.
Print and Debug Support 2.5 Print and Debug Support 2.5.1 Synopsis The OS abstraction includes a family of compact printf() functions that print us- ing a fixed buffer. The size of the buffer (max printf() length) is defined in the OS abstraction layer.
Page 26
Print and Debug Support The value of ErrLevel determines if the message is printed and additionally, if the message results in a system shutdown. Both thresholds can be modified through the OS configuration. The definition of the severity levels are as fol- lows: #define DBG_INFO #define DBG_WARN...
File I/O Support for Embedded Systems 2.6 File I/O Support for Embedded Systems 2.6.1 Synopsis The next section of this document discusses the support for stream IO that is built into the stack library. The support documented in that section is intended to augment the basic functions provided by the native operating system (in the case where the stack is ported to a new environment).
Page 28
File I/O Support for Embedded Systems efs_fread() Read from file efs_fseek() Set file position efs_ftell() Get file position efs_fwrite() Write to file efs_rewind() Reset file position to start of file 2.6.3 EFS Custom API Functions Create (declare) a RAM Based File efs_createfile Syntax void efs_createfile( char *name, INT32 length, UINT8 *pData );...
Page 29
File I/O Support for Embedded Systems A static buffer based system is more efficient for embedded systems since the data must already be present in RAM or ROM. However, the efs_createfile() function could easily be altered to use allocated buffers which are later freed when efs_destroyfile() is called.
Page 30
File I/O Support for Embedded Systems 2.6.4 EFS Standard API Functions Close File efs_fclose Syntax int efs_fclose( EFS_FILE *stream ); Parameter(s) stream Pointer to open stream (file) Return Value Returns EOF if any errors occurred, and zero otherwise Description This function performs a logical “close” on an open file. It is functionally equiva- lent to fclose().
Page 31
File I/O Support for Embedded Systems Read from a File efs_fread Syntax size_t efs_fread( void *ptr, size_t size, size_t nobj, EFS_FILE *stream ); Parameter(s) Pointer to data buffer to receive data size Size in bytes of a read “object” nobj Number of objects to read stream Pointer to open stream (file)
Page 32
File I/O Support for Embedded Systems Write to a File efs_fwrite Syntax size_t efs_fwrite( void *ptr, size_t size, size_t nobj, EFS_FILE *stream ); Parameter(s) Pointer to data buffer to receive data size Size in bytes of a read “object” nobj Number of objects to read stream Pointer to open stream (file)
Chapter 3 Sockets and Stream IO API In order to facilitate a comfortable development environment for the experi- enced network application programmer, and to allow for easier porting of net- work applications, the TCP/IP stack library provides a standard file descriptor environment and a Berkeley compatible sockets API.
File Descriptor Environment 3.1 File Descriptor Environment In most embedded operating system environments, support for file descriptors varies greatly. In most cases, only the bare minimum functionality is provided, and trimmed down support functions are provided using the common “re- served”...
Page 35
File Descriptor Environment 3.1.2.1 When to Initialize the File Descriptor Environment All that is required for correct stack operation, is that a task must open a file descriptor session before calling any file descriptor related functions, and close it when it is done. For example, the most straightforward approach would be for a task to open its file session when it starts, and close it when it completes.
Page 36
File Descriptor Environment The parent task functions would look something like the following: Parent Task Functions: void create_child_task() // Create System Tasks // Create a child task hChildTask = TaskCreate( &child_socket_task, … ); void destroy_child_task() // First close the child’s file session // (This will close all open files) fdSessionClose( hChildTask );...
File Descriptor Programming Interface 3.2 File Descriptor Programming Interface 3.2.1 Synopsis The purpose of supporting a file system is to support the sockets API. Unfortu- nately, the sockets API is not a complete IO API as it was originally designed to integrate into the Unix file system.
Page 38
File Descriptor Programming Interface The fdSelect() function uses file descriptor sets to specify which file descrip- tors are being checked for activity and which have activity detected. There is a small set of MACRO functions for manipulating file descriptor sets. These include the following: FD_SET() Add a file descriptor to a file descriptor set...
Page 39
File Descriptor Programming Interface Wait on One or Multiple File Events fdSelect Syntax int fdSelect( int maxfd, fd_set *readset, fd_set *writeset, fd_set *exceptset, struct timeval *timeout ); Parameter(s) maxfd The highest index contained in any of the three supplied descriptor sets readset Set of file descriptors to check for reading writeset...
Page 40
File Descriptor Programming Interface Note: The error code returned via fdError() is stored in the file descriptor ses- sion associated with a task. If a task calls a file or socket function before it opens a file descriptor session, an error condition results. Obviously however, no error code can be stored for retrieval by fdError() since the file descriptor session doesn’t exist to hold it.
Page 41
File Descriptor Programming Interface hDstTask Handle of task to receive the file descriptor pfddst Pointer to where to write new file descriptor Return Value Returns zero on success or –1 on error. If an error occurs, the state of the file descriptor is not altered.
Page 42
File Descriptor Programming Interface Convert a File Handle to a File Descriptor FileHandleGetFd Syntax int FileHandleGetFd( HANDLE hFile ); Parameter(s) hFile Handle to file to convert Return Value File descriptor or –1 on error. This function is not strictly part of the file descrip- tor function set, and does not elaborate on error conditions via fdError().
Page 43
File Descriptor Programming Interface Return Value Should be treated as a void function. The true return value is dependent on the implementation of the macro. Description This function is used to remove a file descriptor from a file descriptor set, typi- cally after the file descriptor has been “processed”...
Sockets Programming Interfaces 3.3 Sockets Programming Interfaces 3.3.1 Synopsis The socket function API supported by the stack library is consistent with the standard Berkeley sockets API. No parameter adjustments are required. In the interest of brevity, two new types are defined for the socket function dec- larations: typedef struct sockaddr typedef struct sockaddr...
Page 45
Sockets Programming Interfaces Although TCP sockets that use the SOCK_STREAMNC stream type are 100% compatible with the standard TCP socket type, they can also be used with the recvnc() and recvncfrom() functions that UDP and RAW sockets use to elimi- nate the final data copy from the stack to the sockets application.
Page 46
Sockets Programming Interfaces 3.3.4 Sockets API Functions Accept a Connection on a Socket accept Syntax int accept( int s, PSA pName, int *plen ); Parameter(s) Socket pName Name (address) of connected peer plen Pointer to size of pName Return Value If it succeeds, the function returns a non-negative integer that is a descriptor for the accepted socket.
Page 47
Sockets Programming Interfaces Bind a Name (address) to a Socket bind Syntax int bind( int s, PSA pName, int len ); Parameter(s) Socket pName Name (address) of desired local address Size of pName Return Value If it succeeds, the function returns 0. Otherwise, a value of –1 is returned and the function fdError() can be called to determine the error: EBADF The file descriptor (socket) is invalid.
Page 48
Sockets Programming Interfaces EADDRINUSE The specified address is already in use. EISCONN The socket is already connected. ETIMEDOUT Connection establishment timed out without es- tablishing a connection. ECONNREFUSED The attempt to connect was forcefully rejected. ENETUNREACH The network isn’t reachable from this host Description The connect() function establishes a logical (and potentially physical) connec- tion from the socket specified by s to the foreign name (address) specified by...
Page 49
Sockets Programming Interfaces EINVAL Name arguments are invalid. ENOTCONN The socket is not connected. Description The getpeername() function returns the name (address) of the connected peer. The argument pName is a result parameter that is filled in with the address of the connecting entity as known to the communications layer.
Page 50
Sockets Programming Interfaces Socket option to get pbuf Pointer to memory buffer pbufsize Pointer to size of memory buffer Return Value If it succeeds, the function returns 0. Otherwise, a value of –1 is returned and the function fdError() can be called to determine the error: EBADF The file descriptor (socket) is invalid.
Page 51
Sockets Programming Interfaces SO_DONTROUTE Indicates that outgoing messages should bypass the standard routing facilities. Instead, messages are directed to the appropriate network interface according to the network portion of the destination address. SO_LINGER Controls the action taken when unsent messages are queued on socket and a close is performed.
Page 52
Sockets Programming Interfaces SO_RCVLOWAT Is an option to set the minimum count for input op- erations. In general, receive calls will block until any (non-zero) amount of data is received, then return with the smaller of the amount specified by SO_RCVLOWAT or the amount requested.
Page 53
Sockets Programming Interfaces Options that are not Berkeley standard: SO_IFDEVICE Specifies a uint index (1 to n) of the designated in- terface for sending and receiving IP broadcast pack- ets. When set, this interface is selected on a IP broadcast send operation if the socket’s local (bound) IP address is NULL (INADDR_ANY).
Page 54
Sockets Programming Interfaces Listen for Connection Requests on Socket listen Syntax int listen( int s, int maxcon ); Parameter(s) Socket maxcon Maximum number of connects to queue Return Value If it succeeds, the function returns 0. Otherwise, a value of –1 is returned and the function fdError() can be called to determine the error: EBADF The file descriptor (socket) is invalid.
Page 55
Sockets Programming Interfaces ENOTCONN The socket is connection oriented and not con- nected. EWOULDBLOCK The socket is specified as non-blocking, or the timeout has expired. Description The recv() function attempts to receive data from a socket. It is normally used on a connected socket (see connect()).
Page 56
Sockets Programming Interfaces Receive Data from a Socket with the Sender’s Name (address) recvfrom Syntax int recvfrom( int s, void *pbuf, int size, int flags, PSA pName, int *plen ); Parameter(s) Socket pbuf Data buffer to place received data size Size of desired data flags Option flags...
Page 57
Sockets Programming Interfaces as well as the socket-level options SO_RCVLOWAT and SO_RCVTIMEO de- scribed in getsockopt(). The select call (fdSelect()) may be used to determine when more data arrive. The flags argument to a recv() call is formed by combining one or more of the following flags: MSG_DONTWAIT requests that the operation not block when no data...
Page 58
Sockets Programming Interfaces ENOTCONN The socket is connection oriented and not con- nected. EWOULDBLOCK The socket is specified as non-blocking, or the timeout has expired. Description The recvnc() function attempts to receive a data buffer from a socket. It is nor- mally used on a connected socket (see connect()).
Page 59
Sockets Programming Interfaces Receive Data and Sender’s Name from Socket without Buffer Copy recvncfrom Syntax int recvncfrom( int s, void **ppbuf, int flags, HANDLE *phBuffer, PSA pName, int *plen ); Parameter(s) Socket ppbuf Pointer to receive data buffer pointer flags Option flags phBuffer Pointer to receive buffer handle...
Page 60
Sockets Programming Interfaces This function can not be used with sockets of type SOCK_STREAM. When used with sockets of type SOCK_STREAMNC, out of band data marks are cleared. The select call (fdSelect()) may be used to determine when more data arrives. The flags argument to a recv() call can be one of the following flags: MSG_DONTWAIT requests that the operation not block when no data...
Page 61
Sockets Programming Interfaces For a datagram type socket, the send operation always copies one packet’s worth of data. If the buffer is too long to hold the entire packet an error code of EMSGSIZE is returned. If there is not transmit buffer space available on a stream type socket, the func- tion waits for space to become available, unless the socket is non-blocking.
Page 62
Sockets Programming Interfaces EWOULDBLOCK The socket is specified as non-blocking, or the timeout has expired. EMSGSIZE The specified size exceeds the limit of the un- derlying protocol. ENOBUFS Memory allocation failure while attempting to send data. EHOSTUNREACH The remote host was unreachable. Description The sendto() function attempts to send data on a socket to a specified destina- tion.
Page 63
Sockets Programming Interfaces Get the Value of a Socket Option Parameter setsockopt Syntax int setsockopt( int s, int level, int op, void *pbuf, int bufsize ); Parameter(s) Socket level Option level (SOL_SOCKET, IPPROTO_IP, IPPROTO_TCP) Socket option to get pbuf Pointer to memory buffer bufsize Size of memory buffer pointed to by pbuf Return Value...
Page 64
Sockets Programming Interfaces Close One Half of a Connected Socket shutdown Syntax int shutdown( int s, int how ); Parameter(s) Socket Manner of shutdown Return Value If it succeeds, the function returns 0. Otherwise, a value of –1 is returned and the function fdError() can be called to determine the error: EBADF The file descriptor (socket) is invalid.
Page 65
Sockets Programming Interfaces be used. These families are defined in the include file INC\SOCKET.H. This will always be PF_INET (AF_INET) in this implementation. The socket type parameter specifies the semantics of communication. Cur- rently defined types are: SOCK_STREAM provides sequenced, reliable, two-way connection based byte streams.
Full Duplex Pipes Programming Interface 3.4 Full Duplex Pipes Programming Interface 3.4.1 Synopsis Although sockets can be used for inter-task communications, it is not the most efficient method. The stack provides a second data communications model called pipes, which allow for local connection oriented communications. A pipe is a full duplex connection oriented file descriptor.
Page 67
Full Duplex Pipes Programming Interface 3.4.2 Pipe API Functions Since pipes share file descriptor and IO functions with sockets, the only pipe oriented function is the creation of the connected pair. Create a Full Duplex Pipe pipe Syntax int pipe( int *fd1, int *fd2 ); Parameter(s) File descriptor to first end of pipe File descriptor to second end of pipe...
Chapter 4 Initialization and Configuration The first step in launching a network application is the initialization and configu- ration of the network stack. This section covers Configuration Manager API used to maintain system configurations, the Network Control module that uses the configuration to initialize the network, and the specification of the individual configuration components available.
Configuration Overview 4.1 Configuration Overview One of the more tedious aspects of using the stack system is the initialization process. Normally applications programmers need not worry about configura- tion since it is part of the underlying OS. The target platform for this software however is the embedded processor space where there is little or no configu- ration done for the programmer, and the programmer must usually develop custom boot code as well.
Configuration Manager 4.2 Configuration Manager 4.2.1 Synopsis The configuration manager is a collection of API functions that allow a user to create and manipulate a configuration. The manager API is independent of the configuration specification. The configuration is arranged as a database with a master key (called Tag) which defines the class of configuration item.
Page 71
Configuration Manager The PPP module in the stack library and several modules in the NETTOOLS library make use of a default configuration to store and search for data. The default configuration is accessed by passing in a NULL configuration handle to any function that takes the hCfg parameter (except CfgFree()).
Page 72
Configuration Manager 4.2.3 Configuration API Functions Add Configuration Entry to Configuration CfgAddEntry Syntax int CfgAddEntry( HANDLE hCfg, uint Tag, uint Item, uint Mode, uint Size, UINT8 *pData, HANDLE *phCfgEntry ); Parameter(s) hCfg Handle to configuration Tag value of new entry Item Item value of new entry Mode...
Page 73
Configuration Manager the function writes the referenced handle of the new configuration entry to the location specified by this parameter. It is then the caller’s responsibility to der- eference this handle when it is finished with it. When the parameter phCfgEntry is NULL, no entry handle is returned, but the function return value is still valid.
Page 74
Configuration Manager Set the Execution State (Active/Inactive) of the Configuration CfgExecute Syntax int CfgExecute( HANDLE hCfg, int fExecute ); Parameter(s) hCfg Handle to configuration fExecute Desired execute state (1=active) Return Value Returns 0 on success, or less than 0 on an operation error. The possible errors are: CFGERROR_BADHANDLE Invalid hCfg handle...
Page 75
Configuration Manager Get Default Configuration Handle CfgGetDefault Syntax HANDLE CfgGetDefault(); Parameter(s) none Return Value Returns a handle to the current default configuration, or NULL if none. Description This function returns the current default configuration handle. The default han- dle is used in any function that takes a hCfg parameter, when the specified pa- rameter is NULL.
Page 76
Configuration Manager sponsibility to dereference this handle when it is finished with it. When the pa- rameter phCfgEntry is NULL, no entry handle is returned, but the function re- turn value is still valid (“found” or “not found”). Configuration entry handles are dereferenced by the calling one of the follow- ing: CfgEntryDeRef() Stop using the entry...
Page 77
Configuration Manager Index Instance index to get (1 to n) Size Size of buffer to receive data pData Pointer to data buffer to receive data Return Value Number of bytes copied Description This function is a useful shortcut when searching the configuration for well known entries.
Page 78
Configuration Manager When the parameter phCfgEntryNext is NULL, no entry handle is returned, but the function always returns 1 if such an entry was found and 0 when not. When the phCfgEntryNext parameter is not NULL, the function writes a refer- enced handle to the configuration entry to the location specified by this param- eter.
Page 79
Configuration Manager Create a New Configuration CfgNew Syntax HANDLE CfgNew(); Parameter(s) none Return Value Returns handle to new configuration or NULL on memory allocation error. Description Creates a configuration handle that can be used with other configuration func- tions. The new handle defaults to the inactive state (see CfgExecute()). Remove Configuration Entry from Configuration by Handle CfgRemoveEntry Syntax...
Page 80
Configuration Manager Save a Configuration to a Linear Memory Block CfgSave Syntax int CfgSave( HANDLE hCfg, int *pSize, UINT8 *pData ); Parameter(s) hCfg Handle to configuration pSize Pointer to size of memory block pData Pointer to memory block to load Return Value Returns the number of bytes written, 0 on a “size error”...
Page 81
Configuration Manager Set Service Callback Function for Configuration Tag CfgSetService Syntax int CfgSetService( HANDLE hCfg, uint Tag, int (*pCb) (HANDLE, uint, uint, uint, HANDLE) ); Parameter(s) hCfg Handle to configuration Tag value to change Pointer to service callback function Return Value Returns 0 on success, or less than 0 on error.
Page 82
Configuration Manager pOpenOrder Pointer to array of tag values in initialization order pCloseOrder Pointer to array of tag values in shutdown order Return Value Returns zero on success, or less than 0 on an operation error. The possible errors are: CFGERROR_BADHANDLE Invalid hCfg handle CFGERROR_BADPARAM...
Page 83
Configuration Manager Get Configuration Entry Data CfgEntryGetData Syntax int CfgEntryGetData( HANDLE hCfgEntry, int *pSize, UINT8 *pData ); Parameter(s) hCfgEntry Handle to configuration entry pSize Pointer to size of data buffer pData Pointer to data buffer Return Value Returns the number of bytes written, 0 on a “size error” (value at pSize set to required size), or less than 0 on an operation error.
Page 84
Configuration Manager This function should be used with great care. Direct manipulation of the config- uration entry data should only be attempted on informational tags, and only when the caller holds a referenced handle to the configuration entry. This func- tion is used in configuration service callback functions, which are called only when the configuration is in a protected state.
Page 85
Configuration Manager The new entry data is pointed to by the pData parameter with a size indicated by Size. Note that the new data must be an exact replacement for the old. The size of the new buffer must exactly match the old size. This function should be used for configuration entries that are for information purposes only.
Network Control Initialization Procedure (NETCTRL) 4.3 Network Control Initialization Procedure (NETCTRL) 4.3.1 Synopsis As previously mentioned, the configuration and initialization of the stack is per- haps the most tedious part of its operation. For this reason, the stack library includes code to perform system initialization based on a configuration constructed by the programmer.
Page 87
Network Control Initialization Procedure (NETCTRL) 6) Under normal operation, the network does not shutdown until the NC_NetStop() function is called. At some point after a call to NC_NetStop(), the original NC_NetStart() thread calls the user supplied callback function for the “stop” operation. In this callback function, the application shuts down any operation it initiated in the “start”...
Page 88
Network Control Initialization Procedure (NETCTRL) NetIPCb Pointer to callback function called when an IP address is added or removed from the system Return Value Returns the integer value passed to NC_NetStop(). Description This function is called to boot up the network using the network configuration supplied in hCfg.
Page 89
Network Control Initialization Procedure (NETCTRL) The user has the option of immediately calling NC_NetStart() again upon re- turn. This makes for a good stack reboot function. Optionally, the configuration can also be reloaded. This allows the stack to be restarted after a major config- uration change.
Configuration Specification 4.4 Configuration Specification 4.4.1 Synopsis The specification of all the various configuration options for the stack would require a separate document. This section details that part of the configuration that is relied upon by the Network Control (NC) initialization functions, or the services contained in the NETTOOLS library.
Page 91
Configuration Specification Network services are identified by a configuration Tag parameter value of CFGTAG_SERVICE. Note that all these services are obtained directly from the NETTOOLS services API. The configuration system adds a level of abstraction so that a list of ser- vices can be added to a configuration, and then the service provider callback functions contained in the Net Control initialization routines can automatically load the services at runtime without the user calling the NETTOOLS API direct-...
Page 92
Configuration Specification HANDLE hService; This is the handle to the service as returned by the NETTOOLS function corresponding to the type of service requested. Its initial value should be NULL, and it is initialized by the service callback function when the service is started.
Page 93
Configuration Specification uint ReportCode; All the services available via the configuration can also be launched direct- ly via a NETTOOLS API. The NETTOOLS service API has a standard ser- vice reporting callback function that is mirrored by the configuration sys- tem via the Net Control service provider callback.
Page 94
Configuration Specification 4.4.3.3 Individual Configuration Entry Instance Structures The following is the definition of the instance structures used for each of the defined configuration entries using the configuration service tag. Note that all structures contain the previously mentioned CISARGS structure. Some ser- vices require more information and their configuration entry structure contains an additional parameter structure as defined in the service’s NETTOOLS API.
Page 95
Configuration Specification The IPNET entry instance structure is defined as follows: // IPNet Instance typedef struct _ci_ipnet { uint NetType; // Network address type flags IPAddr; // IP Address IPMask; // Subnet Mask HANDLE hBind; // Binding handle (initially NULL) char Domain[CFG_DOMAIN_MAX];...
Page 96
Configuration Specification 4.4.5 IP Gateway Route Specification (CFGTAG_ROUTE) The ROUTE entry specifies a route from one network to another via a specified IP gateway. When specifying a ROUTE entry to the configuration, the Tag pa- rameter is set to CFGTAG_ROUTE, and the Item parameter is not used (set to zero).
Page 97
Configuration Specification 4.4.6 Client Record Specification (CFGTAG_CLIENT) The CLIENT entry specifies a record of a client that appears on the indicated physical interface. When specifying a CLIENT entry to the configuration, the Tag parameter is set to CFGTAG_CLIENT, and the Item parameter is set to the index (1 to n) of the physical interface on which the client appears.
Page 98
Configuration Specification CFG_CLIENTSTATUS_STATIC – Reported via DHCP INFORM or non-DHCP application CFG_CLIENTSTATUS_INVALID – Invalidated by DHCP DECLINE IPN IPAddr; This is IP address of the client. char MacAddr[6]; This is physical Ethernet address of the client. char Hostname[CFG_HOSTNAME_MAX]; This is the hostname of the client. It is recorded by the DHCP server ser- vice, even if the record is STATIC.
Page 99
Configuration Specification uint Flags; The flags determine the access granted by channel or group. The chan- nels or groups that any given PPP server will allow is determined when the PPP server is invoked. A singe client account can be a member of one or more groups, thus one or more of the following flags can be set: CFG_ACCTFLG_CH1 –...
Page 100
Configuration Specification 4.4.9 OS / IP Stack Configuration Item Specification (CFGTAG_OS, CFGTAG_IP) The OS and IP tags specify entries that alter various configuration options that can be adjusted in the operating system and low-level stack operation. When specifying an entry to the configuration, the Tag parameter is set to CFGTAG_OS or CFGTAG_IP, and the Item parameter is set to the configura- tion item to set (these are listed below).
Page 101
Configuration Specification When Tag is CFGTAG_IP, the value of Item can be one of the following: CFGITEM_IP_ICMPDOREDIRECT Add route on ICMP redirect (1=Yes) CFGITEM_IP_ICMPTTL TTL for ICMP messages (RFC1700 says 64) CFGITEM_IP_ICMPTTLECHO TTL for ICMP echo (RFC1700 says 64) CFGITEM_IP_IPINDEXSTART IP Protocol Start Index CFGITEM_IP_IPFORWARDING IP Forwarding Enable...
Page 102
Configuration Specification CFGITEM_IP_PIPETIMEIO Max time for pipe send/rcv call CFGITEM_IP_PIPEBUFMAX Pipe internal buffer size CFGITEM_IP_PIPEMINTX Pipe min tx space for “able to write” CFGITEM_IP_PIPEMINRX Pipe min rx data for “able to read” CFGITEM_IP_STACKMAX Max CFGTAG_STACK item Initialization and Configuration 4-35...
Chapter 5 Network Tools Library Support Functions Included with the stack package is a library of network tools. It provides auxilia- ry functionality to the stack library and contains source written to the socket layer that would normally be considered application level code. The library file is called , and can be accessed by an application that includes NETTOOLS.LIB...
Generic Support Calls 5.1 Generic Support Calls 5.1.1 Synopsis This section contains a selection of functions that can be very useful when pro- gramming network applications. Some are standard Berkeley while others are custom to the stack – designed to save the programmer the time and trouble of programming directly to the stack API.
Page 105
Generic Support Calls This function actually calls inet_aton(), which is the better form of the function. Convert IP Address from String and Return in in_addr Structure inet_aton Syntax int inet_aton( char *strptr, struct in_addr *pa ); Parameter(s) strptr Pointer character string Pointer to address structure Return Value 1 on success or 0 on failure...
Page 106
Generic Support Calls Add Static Gateway Route to the Route Table NtAddStaticGateway Syntax HANDLE NtAddStaticGateway( IPN IPDestAddr, IPN IPDestMask, IPN IPGa- teAddr ); Parameter(s) IPDestAddr IP address of destination (in network format) IPDestMask IP subnet mask of destination (in network format) IPGateAddr IP address of next hop gateway (in network format) Return Value...
Page 107
Generic Support Calls Remove Static Gateway Route from the Route Table NtRemoveStaticGateway Syntax int NtRemoveStaticGateway( IPN IPTarget ); Parameter(s) IPTarget IP address of destination to remove (in network format) Return Value Returns 1 if the route was removed or 0 if it was not found. Description This function removes a static gateway route from the system route table.
Page 108
Generic Support Calls Convert 32-bit IP Address in Network Format to String NtIPN2Str Syntax void NtIPN2Str( IPN IPAddr, char *pStrBuffer ); Parameter(s) IPAddr IP address in network format pStrBuffer Pointer to receive IP address string Return Value nothing Description This function performs an sprintf() of the IP address supplied in IPAddr to the buffer supplied in pStrBuffer.
DNS Support Calls 5.2 DNS Support Calls 5.2.1 Synopsis The concepts and code behind the Unix gethostbyname() and gethostby- addr() functions is extensive. And there are public domain versions available, can be easily run on the IP stack library. Although the code to support the whole name, address and server database is quite large, the basic name resolution functions are quite useful.
Page 110
DNS Support Calls The structure differs slightly from the conventional definition. It is defined as follows: // Host Entry Structure struct _hostent { char *h_name; // Official name of host h_addrtype; // Address Type (AF_INET) h_length; // Address Length (4) h_addrcnt;...
Page 111
DNS Support Calls Resolve a Hostname from an IP Address DNSGetHostByAddr Syntax int DNSGetHostByAddr( IPN IPAddr, void *pScrapBuf, int size ); Parameter(s) IPAddr IP address to resolve, in network format pScrapBuf Pointer to a scrap buffer from which a HOSTENT structure will be allocated size Size of the supplied scrap buffer in bytes...
TFTP Support Calls 5.3 TFTP Support Calls 5.3.1 Synopsis TFTP is supported via the received function. More information on TFTP can be found in rfc783. 5.3.2 TFTP Support API Functions TFTP is accessed through this API. The network tools, include file NET- TOOLS.H, is required.
Page 113
TFTP Support Calls 0 – Not defined, see error message (if any). 1 – File not found. 2 – Access violation. 3 – Disk full or allocation exceeded. 4 – Illegal TFTP operation. 5 – Unknown transfer ID. 6 – File already exists. 7 –...
Chapter 6 Network Tools Library Services Included with the stack package is a library of network tools. It provides auxilia- ry functionality to the stack library and contains source written to the socket layer that would normally be considered application level code. The library file is called , and can be accessed by an application that includes NETTOOLS.LIB...
Service Calling Conventions 6.1 Service Calling Conventions 6.1.1 Specifying Network Services Using the Configuration Although each service has it own specific API, it is usually more convenient to add services by specifying the service in the system configuration as opposed to calling their individual Open and Close API functions.
Page 116
Service Calling Conventions typedef struct _ntargs { CallMode; // Determines desired calling mode #define NT_MODE_IFIDX // Call by specifying IfIdx #define NT_MODE_IPADDR // Call by specifying IPAddr IfIdx; // Physical interface index (0–n) IPAddr; // IP Address HANDLE hCallback; // Handle to pass to callback function void(*pCb)( HANDLE, uint );...
Page 117
Service Calling Conventions service will accept connections to any valid IP address on any device. Note that some services (like DHCP sever) do not support being launched by IP address. When this field is used, CallMode should be set to NT_MODE_IPADDR.
Telnet Server Service 6.2 Telnet Server Service 6.2.1 Synopsis The Telnet Server service provides a mechanism for exposing a stream IO connection to any remote telnet client console. A telnet connection is basically just a TCP connection to the “well-known” port designated for telnet.
Page 119
Telnet Server Service 6.2.3 Specifying Service Using the Configuration The service can be specified as public in that it can connect using any IP ad- dress, or an IP address of a specific interface. When accepting connections to any system IP address, the service is specified with the “CALLBYIP” flag and an IP address of INADDR_ANY.
Telnet Server Service Return Value Returns a handle to the new telnet server instance, or NULL if the service could not be created. This handle is used with TelnetClose() to shutdown the server when its no longer needed. Description When a telnet session is established, a telnet child task is spawned which will call the supplied callback function.
DHCP Server Service 6.3 DHCP Server Service 6.3.1 Synopsis When acting as a router, the TCP/IP stack may also need to maintain the net- work configuration on one of its network devices. A DHCP server allows the stack to maintain the IP address of multiple Ethernet client devices. When combined with Network Address Translation (NAT), the DHCP server can be used to establish client membership in a private virtual network.
DHCP Server Service PoolCount – The number of addresses in the address pool. This structure is used both when specifying the service to the configuration system or when bypassing the configuration and invoking the service API di- rectly. 6.3.4 Specifying Service Using the Configuration Since the DHCP server service executes on a specific interface, it is never executed based on an IP address.
Page 123
DHCP Server Service Open a DHCP Server DHCPSOpen Syntax HANDLE DHCPSOpen( NTARGS *pNTA, NTPARAM_DHCPS *pNTP ); Parameter(s) pNTA Pointer to common argument structure used by all services pNTP Pointer to DHCP server parameter structure Return Value Returns a HANDLE to a DHCPS instance structure which is used in calls to other DHCPS functions like DHCPSClose().
DHCP Client Support 6.4 DHCP Client Support 6.4.1 Synopsis At system startup the DHCP client will try and acquire an IP address from the DHCP servers available on the network. Note that the client will accept the first IP address offered and that the INIT-RE- BOOT State (which requests a previously assigned IP address) is not currently implemented.
Page 125
DHCP Client Support 6.4.3 DHCP Client Parameter Structure The following structure defines the unique parameters of the DHCP client ser- vice. It is located in the file: inc\nettools\inc\dhcpif.h. // DCHP Parameter Structure #define DHCP_MAX_OPTIONS // Max number allowed options typedef struct _ntparam_dhcp { UINT8 *pOptions;...
Page 126
DHCP Client Support 6.4.5 Invoking the Service via NETTOOLS API In addition to the configuration option, this service can also be created and de- stroyed directly through this NETTOOLS API. If an application wishes to by- pass the configuration system and launch the service directly, these calls can be used.
HTTP Server Support 6.5 HTTP Server Support 6.5.1 Synopsis An HTTP (Hypertext Transfer Protocol) server allows a remote browser to view content on the server file system. Files can be stored for viewing and forms can also be stored to allow remote interaction with the system. Form POST func- tions become calls to application defined C functions that allow the embedded system to be remotely controlled via a HTTP browser.
Page 128
HTTP Server Support http_example() CI_SERVICE_HTTP http; bzero( &http, sizeof(http) ); http.cisargs.IPAddr = INADDR_ANY; http.cisargs.pCbSrv = &ServiceReport; CfgAddEntry( hCfg, CFGTAG_SERVICE, CFGITEM_SERVICE_HTTP, 0, sizeof(http), (UINT8 *)&http, 0 ); The above code is all that is required when using the configuration system to invoke this service.
DNS Server Service 6.6 DNS Server Service 6.6.1 Synopsis The DNS server service allows clients on a home network to resolve host names and addresses for clients on both the home and public networks. 6.6.2 Operation The TCP/IP stack contains a small DNS resolver which can resolve host- names and addresses that are local to the system via the configuration, or those outside the system by using an external DNS server.
Page 130
DNS Server Service dns_server_example() CI_SERVICE_DNSSERVER dnss; bzero( &dnss, sizeof(dnss) ); dnss.cisargs.IPAddr = INADDR_ANY; dnss.cisargs.pCbSrv = &ServiceReport; CfgAddEntry( hCfg, CFGTAG_SERVICE, CFGITEM_SERVICE_DNSSERVER, 0, sizeof(dnss), (UINT8 *)&dnss, 0 ); The above code is all that is required when using the configuration system to invoke this service.
Network Address Translation (NAT) Service 6.7 Network Address Translation (NAT) Service 6.7.1 Synopsis The NAT service allows for the establishment of a home virtual network that is isolated from and protected from the external public network. It provides a port based address translation function that allows all the clients on the home network to share a single public IP address.
Page 132
Network Address Translation (NAT) Service (192.168.0.x/255.255.255.0) on “If–2” and (192.168.1 .x/255.255.255.0) on “If–3”. In order to run NAT on both home networks, the NAT interface would be “If–1” (the public interface), and the NAT group (virtual) network would be 192.168.0.0/255.255.254.0, which covers both home networks. For more information on NAT operation, including how to program proxy filters, see the Network Address Translation appendix at the end of this document.
Page 133
Network Address Translation (NAT) Service nat_service_example() CI_SERVICE_NAT nat; bzero( &nat, sizeof(nat) ); // Don’t start NAT until we resolve an IP address on its IF nat.cisargs.Mode = CIS_FLG_IFIDXVALID | CIS_FLG_RESOLVEIP | CIS_FLG_RESTARTIPTERM; nat.cisargs.IfIdx = natIdx; nat.cisargs.pCbSrv = &ServiceReport; // Include all 192.168.x.x addresses in NAT group nat.param.IPVirt = htonl(0xc0a80000);...
Page 134
Network Address Translation (NAT) Service Disable the NAT Service NATClose Syntax void NATClose( HANDLE hNAT ); Parameter(s) hNAT Handle to NAT service obtained from NATOpen() Return Value nothing Description Disables the NAT service. Network Tools Library Services 6-21...
Page 135
Appendix A Appendix A Internal Stack Functions In the source code to the network control functions there are several calls to internal stack functions. This is similar to calling the kernel in other operating environments. This section contains a partial list of internal stack functions provided to aid in the comprehension of kernel oriented calls.
Page 136
Overview A.1 Overview The control API is the collection of functions supplied in the stack library. The entire API is exposed, although the vast majority of functions and objects will only be used internally to the stack. A.1.1 Interrupts and Preemption It should be noted that no part of the stack is interrupt driven.
Overview With a little care, use these functions should be of no concern. The following are good general guidelines: Always call llEnter() before calling a stack function, and llExit() when done calling stack functions. Try and keep all code that requires llEnter() and llExit() in a single module. They are only required for system maintenance.
Page 138
Overview Referenced Objects – A referenced object is one that may be used by oth- er tasks long after the original creator is through with it. This type of handle is useful when an object is needed for a task of indeterminate length, where the creator of the handle does not wish to track it –...
Stack Executive (Exec) A.2 Stack Executive (Exec) A.2.1 Synopsis At the heart of the stack is the Executive API (Exec). The Executive acts as a message dispatcher for the internal stack components. This action is mostly hidden from the application, but there are some public functions. A.2.2 API Functions Prepare the System for Execution ExecOpen...
Packet (Pkt) Object A.3 Packet (Pkt) Object A.3.1 Synopsis In order to fit nicely into an object oriented environment, network packets are abstracted into two data objects, packets and packet fragments. The packet object (PKT) is comprised of information about the packet charac- teristics, like the ingress and egress device, the route associated with the packet, the size and state of various protocol headers, etc.
Page 141
Packet (Pkt) Object the section on the FRAG object). The size of the individual layers can be ob- tained from the size properties SizeLLCHdr, SizeNetHdr, and SizeTPHdr. When a packet is created with the generic interface (IF) API (discussed later), these properties are initialized with the standard header sizes for their respec- tive types.
Page 142
Packet (Pkt) Object PktSetFrag() Attach a Packet Fragment Handle to a Packet PktSetIFRx() Set Receive (Ingress) Interface Handle PktSetIFTx() Set Transmit (Egress) Interface Handle PktSetLLADst() Set Destination Link Level Address Handle PktSetRoute() Set Packet Route PktSetSizeLLC() Set the Packet Link Layer Control Header Size PktSetSizeNet() Set the Packet Network Header Size PktSetSizeTP()
Page 143
Packet (Pkt) Object Get Packet Flags PktGetFlags Syntax uint PktGetFlags( HANDLE hPkt ); Return Value Packet flags Description This function is called to get the status flags in the packet object. Flags are used to mark whether certain network headers are either included or not in- cluded in the valid data of the packet.
Page 144
Packet (Pkt) Object Get Destination Link Level Address Handle PktGetLLADst Syntax HANDLE PktGetLLADst( HANDLE hPkt ); Return Value Handle to destination LLA (link-level address) or NULL. Description This function is called to get a handle to the link-level destination address for the packet.
Page 145
Packet (Pkt) Object Get the Packet Transport Header Size PktGetSizeTP Syntax uint PktGetSizeTP( HANDLE hPkt ); Return Value Transport header length or NULL if unknown. Description This function is called to get the length of the transport header. For a TCP pack- et, this value is usually 20, but can be larger if options are present.
Page 146
Packet (Pkt) Object Attach a Packet Fragment Handle to a Packet PktSetFrag Syntax void PktSetFrag( HANDLE hPkt, HANDLE hFrag ); Return Value nothing Description This function is called to attach a packet fragment (FRAG) handle to a packet. The FRAG is the object which abstracts the physical memory buffer containing the packet data.
Page 147
Packet (Pkt) Object Set Packet Route PktSetRoute Syntax void PktSetRoute( HANDLE hPkt, HANDLE hRoute ); Return Value nothing Description This function is called to set a destination route for the packet. The route can be used by the LLI (link-level info) module to resolve both a transmission inter- face and destination link-level address (LLA).
Packet Fragment (Frag) Object A.4 Packet Fragment (Frag) Object A.4.1 Synopsis A Fragment object is a container for packet data. The concept behind the frag is that a packet data buffer can be represented by the following properties: A pool from which the packet buffer was allocated A pointer to the packet data buffer The size (total byte capacity) of the buffer The size (in bytes) of the data which is currently valid in the buffer...
Packet Fragment (Frag) Object Figure A–2. FRAG Object Properties Buffer Pool Buffer Pointer Unused Buffer Offset Space Length Free Valid Valid Buffers Data Size Unused Space A.4.2 Object Type Static – Packet fragment (FRAG) objects are owned and destroyed by a single entity.
Page 150
Packet Fragment (Frag) Object A.4.4 API Function Description Create Frag by Allocating a New Buffer FragNewAlloc Syntax HANDLE FragNewAlloc( uint PoolID, uint BufferLen, uint PadLen, uint ValidLen, uint DataOffset ); Return Value Handle to new FRAG, or NULL on memory allocation error. Description This function is called to create a Frag object and allocate a Frag memory buff- er.
Page 151
Packet Fragment (Frag) Object Create Frag by Copying an Existing Frag FragCopy Syntax HANDLE FragCopy( HANDLE hFrag ); Return Value Handle to new FRAG, or NULL on memory allocation error. Description This function is called to create a Frag object by copying an existing Frag ob- ject.
Page 152
Packet Fragment (Frag) Object Get the Buffer Status Parameters FragGetBufParams Syntax UINT8 *FragGetBufParams( HANDLE hFrag, uint *pBufferLen, uint *pValidLen, uint *pDataOffset ); Return Value Pointer to memory buffer. Description Called to get information about the buffer associated with the Frag. The func- tion always returns a pointer to the buffer.
Page 153
Packet Fragment (Frag) Object Set Frag Auxiliary Data Value 2 FragSetAux2 Syntax void FragSetAux2( HANDLE hFrag, UINT32 Data ); Return Value nothing Description Called to set auxiliary data associated with the Frag. This is used by TCP and UDP to track buffer data and should not be used for other purposes. Set Frag Buffer Status Parameters FragSetBufParams Syntax...
Link Layer Address (LLA) Object A.5 Link Layer Address (LLA) Object A.5.1 Synopsis In order to make full use of the stack objects described in this section, it is nec- essary to understand some of the stack’s basic building block components. One such component is the Link Layer Address Object, or LLA for short.
Page 155
Link Layer Address (LLA) Object Set LLA Object Properties LLASet Syntax void LLASet( HANDLE hLLA, uint Type, uint Size, UINT8 *pData ); Description This function is called to set the properties of an LLA object. The object type is the type of address the data represents. Valid values for the Type argument are: TYPE_LLA_UNICAST Object is a unicast MAC address...
Link Layer Information (LLI) Object A.6 Link Layer Information (LLI) Object A.6.1 Synopsis In order to make full use of the stack objects described in this section, it is nec- essary to understand some of the stack’s basic building block components. One such component is the Link Layer Information Object, or LLI for short.
Page 157
Link Layer Information (LLI) Object This function also updates the route in the LLI (ARP) expiration list. It allows an application to change the state of the ARP entry even if the stack has al- ready created the route. It should be used when it is unclear if the route (really ARP table entry) already exists or not.
Interface (IF) Object A.7 Interface (IF) Object A.7.1 Synopsis The Interface (or IF) object is an abstraction of any physical interface in the system capable of transmitting and receiving packet (PKT) objects. In the cur- rent software, an interface object can represent either a PPP based device or and Ethernet (Ether) based device.
Page 159
Interface (IF) Object A.7.4 API Function Description Initialize Handle to Index Mapping Tables IFInit Syntax void IFInit(); Return Value nothing Description This function is called from ExecOpen(), before any physical devices are ini- tialized. It will prepare the IF system to correctly process IFIndexNew() com- mands which are called when Ether and PPP devices are created.
Page 160
Interface (IF) Object Get the Device Handle Corresponding to a Physical Index IFIndexGetHandle Syntax HANDLE IFIndexGetHandle( uint Index ); Return Value Handle to device corresponding to supplied index, or NULL on error. Description This function is called to convert a physical device index to a device handle. Get the Physical Index Corresponding to a Device Handle IFGetIndex Syntax...
Page 161
Interface (IF) Object Create a Packet Object for Transmission IFCreatePacket Syntax HANDLE IFCreatePacket( uint SizePayload, uint SizeNet, uint SizeTP ); Return Value Handle to new packet or NULL on allocation error. Description This function is probably the most useful of the IF functions. It is called to create a packet object to send packets out of the stack.
Ether Object A.8 Ether Object A.8.1 Synopsis The Ether object is really just the “generic” portion of the packet driver. It knows how to process an Ethernet MAC header, and handles incoming and outgoing packets. It interfaces directly to the HAL packet driver. For each Ethernet based packet device in the system, an Ether object is created to represent this device to the stack.
Page 163
Ether Object Create New Ether Object EtherNew Syntax HANDLE EtherNew( uint PhysIndex ); Return Value Returns a handle to the Ether object, or NULL on a memory allocation error. Description Installs a new Ether object in the system. This call should be made for every ethernet device installed.
Page 164
Ether Object Get the directed Link Level Address of the Ether Object EtherGetLLADirect Syntax HANDLE EtherGetLLADirect( HANDLE hEther ); Return Value Handle to LLA or NULL on error. Description Returns an LLA object handle containing the Ethernet MAC address of the physical device represented by the indicated Ether object.
Page 165
Ether Object Clear All Multicast Ethernet Addresses EtherClearMCast Syntax void EtherClearMCast( HANDLE hEther ); Description Called to remove all Ethernet multicast addresses from the list of multicast ad- dresses previously added via a call to EtherAddMCast(). After calling this function, the Ethernet adapter will not receive any multicast addresses when the Rx filter is set to ETH_PKTFLT_MULTICAST or below.
Binding Object A.9 Binding Object A.9.1 Synopsis In order for a device object to live on the network, it must have an IP address and knowledge of its IP subnet. The process of assigning an IP address and subnet to a device is to create a binding to the device with the desired IP ad- dressing.
Page 167
Binding Object Start Enumeration of Binding Objects BindGetFirst Syntax HANDLE BindGetFirst(); Description Returns a handle to the first binding installed in the system (or NULL if not bind- ings exist). Continue Enumeration of Binding Objects BindGetNext Syntax HANDLE BindGetNext( HANDLE hBind ); Description Returns a handle to the binding in the installed binding list that follows the indi- cated binding (or NULL if no more bindings exist).
Timer Object A.10 Timer Object A.10.1 Synopsis The timer object is used to time events in kernel layer by installing a kernel call- back function which is called at set intervals. The resolution of the timer is 0.5 seconds, and the callback is not deterministic. The most common use of the timer callback is to implement timeout conditions that are usually measured in seconds.
Page 169
Timer Object Indicate Half Second Tick Event TimerHSTick Syntax void TimerHSTick (); Description Called by the stack scheduler to notify the stack that a half second has elapsed since the last call. Internal Stack Functions A-35...
Route Object A.11 Route Object A.11.1 Synopsis The route manager maintains IP routing information. It is called by various rou- tines to get and set route information. A route object is a “destination” on the network. Locally, it consists of an egress interface and a next hop IP address. This section describes a subset of the route object.
Page 171
Route Object FLG_RTE_REJECT – Entry is rejecting When set, indicates that the route is to an invalid address. All packets des- tined for this address are discarded with an error indication. FLG_RTE_MODIFIED – Route has been auto modified When set, indicates that the route has been modified as a result of an ICMP redirect message.
Page 172
Route Object so that Ethernet peers can communicate via ARP. An alternative would be to assign an alternate subnet to PPP clients. FLG_RTE_CLONING – “Cloning” route to a local IP subnet When set, indicates that the network route is a cloning route. Cloning routes clone (spawn to) host routes when a route search is performed on a host address that is a member of the cloning route’s network (via address and subnet mask).
Page 173
Route Object A.11.4 Route Entry Flags Guidelines Without writing another chapter on the theory of routing, here are some gener- al guidelines to use when creating new routes. Use the definitions listed above with the following legal flag combinations: Setting FLG_RTE_BLACKHOLE FLG_RTE_REJECT –...
Page 174
Route Object A.11.5 API Functions The Route API is no doubt the most extensive API that a system task will make use of outside of the stack routines themselves. As with the other stack APIs however, it is not the goal of this guide to document the entire API. Calls that accept a CallFlags argument can be supplied with the FLG_RTF_REPORT flag to indicate that the call should result in a route report to the route control object.
Page 175
Route Object Call Flags FLG_RTF_REPORT Reports new route (NEW) Return Value Referenced handle to newly created route. Description Called to create a new host or network route and add it to the route table. Exist- ing routes can not be modified via this call. Some flag combinations make no sense, and the following are strictly en- forced: FLG_RTE_UP flag is always SET.
Page 176
Route Object When there is more than one route with the same subnet mask, the following matching guidelines are used (listed from BEST to WORST): Route has a local destination (occurs with host addresses only). Route has a gateway destination. Route has a subnet destination on a connected interface Sometimes a search is desired where particular matches are desired.
Page 177
Route Object RTC_HOSTUNREACH Host unreachable RTC_NETUNREACH Network unreachable Remove Route from System Route Table RtRemove Syntax void RtRemove( HANLE hRt, uint CallFlags, uint FailCode ); Call Flags FLG_RTF_REPORT Reports the removal of the route (REMOVED) Description This call allows an application to remove a route from the system route table independently of any held references to the route.
Page 178
Route Object Get the Route IP Address RtGetIPAddr Syntax IPN RtGetIPAddr( HANLE hRt ); Return Value IP host/network address. Description This function returns the specified route’s IP address in network format. Get the Route IP Subnet Mask RtGetIPMask Syntax IPN RtGetIPMask( HANLE hRt ); Return Value IP subnet mask Description...
Page 179
Route Object Start Walking the Route Table RtWalkBegin Syntax HANDLE RtWalkBegin(); Return Value HANDLE to first route in system route table or NULL if no routes. Description This function initiates a walk of the route table. It returns the first route in the table.
Route Control Object A.12 Route Control Object A.12.1 Synopsis The route control object isn’t so much of an object as it is a function. Its purpose is to serve as a collection point for route related information in the system. A routing daemon may wish to make use of this information, or it could simply be logged as debugging information.
Page 181
Route Control Object Route Find “Missed” on Route MSG_RTC_MISS Parameter(s) Param1 = Route IP Param2 = Route IP Mask (all ones for host route) Description Called when the route table was searched for a route and no matching route was found. This message will never be sent when there is a default route in the table since all searches will have a match (unless a special restricted search is performed).
Page 182
Route Control Object Route has been Redirected MSG_RTC_REDIRECT Parameter(s) Param1 = Route IP Param2 = New Destination Gateway IP Description Called when an ICMP redirect message is received for a given IP host ad- dress. Since the invention of classless subnets, all redirects are treated as HOST redirects.
Page 183
Route Control Object Unhook RTC Messages RTCRemoveHook Syntax void RTCRemoveHook ( void (*pfn)( uint, UINT32, UINT32 ) ); Return Value none Description Called to remove a previously “hooked” callback function. Internal Stack Functions A-49...
Configuring the Stack A.13 Configuring the Stack A.13.1 Synopsis The stack has multiple configuration options that can be changed by the sys- tem programmer. This is possible by altering the default values in a stack con- figuration structure before the stack is initialized. A.13.2 Configuration Structure The stack internal configuration structure is _ipcfg.
Page 185
Configuring the Stack The structure entries as defined as follows: Update Route Table on ICMP Redirect _ipcfg.IcmpDoRedirect Default Value 1 (Yes) Description When set, causes ICMP to automatically create a route to perform redirects on an IP host to the gateway supplied in the redirect message. If set to false (0), the system programmer can take whatever action they feel necessary as the ICMP redirect will also generate a route control message.
Page 186
Configuring the Stack IP Network Address Translation Enable _ipcfg.IpNatEnable Default Value 0 (No) Description When set to true (1), this allows the stack to make use of the network address translation (NAT) module. Note that in addition to setting this structure ele- ment, NAT must also be configured.
Page 187
Configuring the Stack Lifetime of Route in RtAdv _ipcfg.RtcAdvLife Default Value Description If sending router advertisements (see above), this is the route lifetime that will be sent in the ICMP message. Preference Level of Route in RtAdv _ipcfg.RtcAdvPref Default Value Description If sending router advertisements (see above), this is the route preference level that will be sent in the ICMP message.
Page 188
Configuring the Stack Default MTU for Local Routes _ipcfg.RtDefaultMTU Default Value 1500 Description When a route is created, it gets its MTU from the egress device. However, if the route is local to the system, there is no egress device. In this case, a default MTU is used.
Page 189
Configuring the Stack Maximum Time in Seconds to Wait on Socket Read/Write _ipcfg.SockTimeIo Default Value Description This is max amount to time the sockets layer will wait on a read or write opera- tion without any progress. For example, if the user calls send() with a very large buffer, the function will not timeout so long as some fraction of the data is sent during the timeout period.
Page 190
Configuring the Stack Size in Bytes of Each End of a Pipe Buffer _ipcfg.PipeBufSize Default Value 1024 Description This is the size of a Pipe send and receive buffer. This value is only examined when pipes are created, so changing this value will not affect the buffering of existing pipes.
Network Address Translation A.14 Network Address Translation A.14.1 Synopsis The stack includes a small network address translation (NAT) function which can be used to setup virtual networks when the stack it acting as a router. When enabled, NAT will translate routed packets sent from or to a targeted virtual network.
Page 192
Network Address Translation A.14.3 NAT Configuration In order to make use of NAT, it must be configured via the function described here. Also, by default the NAT code is not called by the stack. This is to in- crease stack efficiency when NAT is not in use. In order to enable the NAT module, the IpNatEnable element of the stack configuration structure must be set.
Obtaining Stack Statistics A.15 Obtaining Stack Statistics Stack statistics are available from global structures or global arrays exported by the stack library. The declaration of these global identifiers appears in the interface specification for the individual protocols. The following protocols con- tain statistics information: Protocol Statistics Definition...
Page 194
Appendix B Appendix A Network Address Translation This section is required only for system programmers who need low level ac- cess to the Network Address Translation (NAT) Layer. This API does not ap- ply to sockets application programming. This section describes functions that are callable from the kernel layer. Users should familiarize themselves with the operation of the operation of llEnt- er()/llExit() functions before attempting to use the APIs described in this sec- tion.
NAT Operation B.1 NAT Operation NAT is basically what the acronym implies – a translation of packet IP address. It is used by the stack when routing, to translate the IP address of a packet to/ from a private LAN from/to a public WAN. NAT is required when the IP address paradigms on either side of the router are incompatible, for example, virtual addresses vs.
Page 196
NAT Operation B.1.2 Basic NAT When sharing a single WAN IP address, the IP address obtained from the ISP is assigned to the router (the TCP/IP stack in routing mode). Client machines that are to share the IP address are placed on the home LAN. The router routes traffic between the LAN and the WAN (internet via the ISP).
Page 197
NAT Operation When the router HR receives this packet, it searches for a NAT entry that matches the From address of the packet. Since this is the first packet, assume the table is empty. When no entry is found, (skipping proxies for now) the router will create a new entry.
Page 198
NAT Operation When HR receives the packet, it checks the NAT entry table for an entry with a Mapped Port value equal to the destination port of the packet (in this case 50001). The value of Protocol and the source IP address/port values must also match the Protocol, Foreign IP, and Foreign Port fields of the NAT entry.
NAT Operation B.1.3 NAT Port Mapping So far we’ve only examined communications that has been initiated by hosts on the home LAN. Note that any unsolicited packets sent to HR from the WAN will not match any entry in the NAT table. These packets will be forwarded to the internal protocol stacks on HR, where they may or may not be used.
NAT Operation The resulting NAT entry table would be: NAT Entry Table Foreign Local Mapped Port Port Port Foreign IP Local IP IP Protocol TCP State Timeout 64.1.1.100 2006 192.168.0.32 SYNSENT 00:01:00 wild wild 192.168.0.32 – STATIC The packet sent to the LAN by HR would be: Packet 4 (modified) From Protocol...
Page 201
NAT Operation In order to make the servers on H1 and H2 public, the following NAT port map- ping entries are installed on HR: NAT Entry Table Foreign Local Mapped Port Port Port Foreign IP Local IP IP Protocol TCP State Timeout wild wild...
Page 202
NAT Operation B.1.4.2 Problem Example – FTP Clients on the LAN As a straightforward example of a situation that requires a proxy filter, consider FTP (file transfer protocol). FTP actually uses two ports to transmit a file. The first port is used to establish the control connection. Then, new ports are used to establish the data connection to actually send the file.
Page 203
NAT Operation Since there is no NAT entry record that will match the address values in this packet (specifically port 20 in the From field), this packet will not be forwarded to the FTP client. In order for this to work, there must be a port mapping installed for 64.1.1.100 that has a wildcard port value (we can’t be sure that the connection request will arrive on port 20).
Page 204
NAT Operation As a reminder, the FTP server would normally see the packet as: Packet 3 (modified incorrectly) From Protocol Packet Payload 64.1.1.100 : 21 128.1.2.12 : 50003 “PORT 192.168.0.32, 1142” This packet creates a couple problems. First, the IP address in the PORT com- mand does not match the IP address of the FTP server’s connected peer.
Page 205
NAT Operation B.1.4.3 Stack Support for Proxy Filters The bad news for the modification procedure discussed above is multifaceted: 1) The creation of the first data connection wildcard entry depends on the knowledge by some entity that an FTP control connection has occurred, and what IP/PORT the connection occurred on.
Page 206
NAT Operation In the case of the FTP client, there would be no “Rx” callback since only pack- ets from the client need be examined. The “Tx” callback would look for PORT commands from the client, and when one was detected, it would install the sec- ond wildcard port mapping as discussed in the previous section, and then modify the packet payload so that the PORT command reflected the WAN IP of HR, and the Mapped Port of the NAT entry.
Page 207
NAT Operation NatFree( pNI–>pUserData ); return(1); // FTPCProxyTx – Proxy for FTP Clients behind firewall // NOTE: Proxy callback function operate at the kernel level. They may not make calls to user–level functions. int FTPCProxyTx( NATINFO *pNI, IPHDR *pIpHdr ) UINT16 Length, Offset;...
Page 209
NAT Port Mapping B.2 NAT Port Mapping B.2.1 Synopsis NAT port mapping allows a client machine on the LAN (or home network) to appear on a specific port of the router’s public WAN IP address. This API (and NAT in general) is only used when the TCP/IP stack is acting as an IP router, and when one the IP network on one side of the router is using virtual IP ad- dresses.
Page 210
NAT Port Mapping NI_TCP_CLOSED The connection is closed NI_TCP_SYNSENT The peers are in the process of connecting NI_TCP_ESTAB A connection has been established IPN IPLocal; This is the IP address (in network format) of the peer host on the local net- work (LAN).
Page 211
NAT Port Mapping void * pUserData; This field is reserved for use by proxy filter callback functions. It is not used by the system software. The NAT information structure of little importance when only port mapping is required. Its real function is for use in NAT proxy filters. B.2.4 NAT API Functions Create a NAT Entry (for Port Mapping) NatNew...
Page 212
NAT Port Mapping Destroy a NAT Entry NatFree Syntax void NatFree( HANDLE hNat ); Parameter(s) hNat Handle to NAT entry created with NatNew() Return Value nothing Description This function frees the supplied NAT entry. It is called to remove a STATIC NAT entry that is no longer required.
NAT Proxy Filters B.3 NAT Proxy Filters B.3.1 Synopsis NAT proxy filters are used to allow NAT to operate correctly with network proto- cols that have addressing specific data in their packet payload data. This API (and NAT in general) is only used when the TCP/IP stack is acting as an IP router, and when one the IP network on one side of the router is using virtual IP addresses.
Page 214
NAT Proxy Filters Proxy Tx/Rx Callback Functions ProxyTx/RxCallback Syntax int SampleProxyTxCallback( NATINFO *pNI, IPHDR *pIpHdr ); int SampleProxyRxCallback( NATINFO *pNI, IPHDR *pIpHdr ); Parameter(s) Pointer to NATINFO structure of Nat entry in use pIpHdr Pointer to the IP header of the packet being translated Return Value 1 to allow normal operation, or NULL to abort the supplied packet.
Page 215
NAT Proxy Filters pfnTxCb Pointer to proxy “Tx” callback function (NULL if none) pfnRxCb Pointer to proxy “Rx” callback function (NULL if none) Return Value Handle to new proxy, or NULL on error. Description This function creates a “hook” that is examined whenever a new NAT entry is created.
Page 216
NAT Proxy Filters Modify the Contents of a Packet ProxyPacketMod Syntax IPHDR *ProxyPacketMod(uint Offset, uint OldSize, uint NewSize, UINT8 *pNewData ); Parameter(s) Offset Offset in bytes from start of IP header to first modified byte OldSize Size of old data at Offset NewSize Size of new data to replace old data at Offset pNewData...
Appendix C Appendix A Point to Point Protocol Point to point protocol (PPP) was originally designed as a replacement for SLIP (serial line IP) in sending IP packets a serial line. In addition to its massive popularity in performing this function, PPP has also been increasingly used for the transmission of packets over other media.
Low-Level PPP Support C.1 Low-Level PPP Support This section describes the operation of the PPP support API included in the TCP/IP stack. C.1.1 Please Note Unlike the HDLC and PPPoE APIs which are application callable, the low level PPP support API is designed to be called from the kernel layer only. Users should be thoroughly familiar with the operation of the operation of the kernel and the llEnter()/llExit() functions before attempting to use the APIs described in this section.
Low-Level PPP Support Figure C–3. Serial Interface (SI) Abstraction Application Software Î Î Î PPP Connect Î Î Î Session API Î Î Î Timer Î Î Î Hardware TCP/IP Packet Decoding Î Î Î Stack Î Î Î Packet Encoding Î...
Page 220
Low-Level PPP Support C.1.4 Supported Protocols In keeping with trying to maintain a small footprint, the PPP software supports a subset of the general PPP protocols. The following are supported: Link Control Protocol (LCP) Internet Protocol Control Protocol (IPCP) Password Authentication Protocol (PAP) Challenge Handshake Authentication Protocol (CHAP) using MD5 Internet Protocol (IP) C.1.5 SI Module Callback Function...
Page 221
Low-Level PPP Support SI_MSG_CALLSTATUS PPP connection status has changed SI_MSG_SENDPACKET PPP is requesting a packet be encoded and transmitted SI_MSG_PEERCMAP LCP has received the peer’s 32 bit asynch character map C.1.5.2 SI_MSG_CALLSTATUS Message When this message value is set, the callback function was called by PPP to update the status of the connection instance.
Page 222
Low-Level PPP Support and which do not. The default value of the peer CMAP should be 0xffffffff, and updated only when this message is received. Whether or not PPP will attempt to exchange CMAP information with its peer, is determined by passing flags to pppNew() when the connection instance is created.
Page 223
Low-Level PPP Support break; case SI_MSG_SENDPACKET: // Make sure packet is valid if( !hPkt || !(hFrag = PktGetFrag( hPkt )) DbgPrintf(DBG_ERROR,”pppoeSI: Bad packet”); goto TxDone; // Silently discard packet if we’re not connected if( !ppi–>SessionId ) goto TxDone; // Get the buffer parameters pb = FragGetBufParams( hFrag, 0, &ValidSize, &Offset );...
Page 224
Low-Level PPP Support C.1.6 Tips for Implementing a PPP Serial Interface (SI) Module Instance C.1.6.1 Multiple Instances PPP supports multiple instances, but it is up to the SI module implementation to track multiple instances of itself. In general, a module that supports multiple instances will have a locally global head pointer to its first instance, and then an array or linked list for additional instances.
Page 225
Low-Level PPP Support C.1.6.4 Creating a Packet Along with decoding any packet that is received on the physical hardware and stripping off all but the protocol and payload fields, the SI module must supply the received data as a packet (PKT) object to the pppInput() function. The fol- lowing example code illustrates the creation of a packet object for holding new packet data.
Page 226
Low-Level PPP Support FragSetBufParams( hFrag, PACKETSIZE, Offset ); // This handle is what we give to PPP return( hPkt ); C.1.7 PPP API Functions The following is the full description of the PPP functions described in this sec- tion. Create a New PPP Connection Instance pppNew Syntax HANDLE pppNew( HANDLE hSI, uint pppFlags, uint mru, IPN IPServer, IPN...
Page 227
Low-Level PPP Support When operating in SERVER mode, any of the following flags can also be set: PPPFLG_OPT_AUTH_PAP Require PAP authentication PPPFLG_OPT_AUTH_CHAP Require CHAP authentication PPPFLG_OPT_USE_MSE Use MS extensions as server PPPFLG_OPT_LOCALDNS Claim Local IP as DNS server PPPFLG_SIOPT_SENDCMAP Send an async character map PPPFLG_SIOPT_RECVCMAP Accept an async character map PPPFLG_CH1...
Page 228
Low-Level PPP Support Password – When creating the PPP instance in CLIENT mode, this is a pointer to a NULL terminated string containing the password to use in PAP or CHAP authentication. The maximum string length is defined by PPPNAMELEN. When operating in SERVER mode, this value is NULL. cmap –...
Page 229
Low-Level PPP Support Notify PPP of One Second Tick pppTimer Syntax void pppTimer( HANDLE hPPP ); Parameter(s) hPPP Handle to PPP instance created with pppNew() Return Value nothing Description This function is called on an active PPP instance to notify PPP that one second has elapsed.
Serial HDLC Client and Server Support C.2 Serial HDLC Client and Server Support C.2.1 Please Note The HDLC API is user callable. Unlike the low level PPP support API, users should not use the llEnter()/llExit() functions when calling the functions de- scribed in this section.
Page 231
Serial HDLC Client and Server Support Username Pointer to client account username Password Pointer to client account password Return Value If it succeeds, the function returns a handle to a PPPoE client instance. Else, it returns NULL. Description This function is called to create a new serial HDLC client instance on the physi- cal serial interface specified by the index Dev.
Page 232
Serial HDLC Client and Server Support Destroy a Serial HDLC Client Session hdlcFree Syntax void hdlcFree( HANDLE hHDLC ); Parameter(s) hHDLC Handle to HDLC Client Session Return Value nothing Description This function is called to close and destroy a serial HDLC client session that was created with hdlcNew().
Page 233
Serial HDLC Client and Server Support Create a Serial HDLC Server Session hdlcsNew Syntax HANDLE hdlcsNew( uint Dev, uint pppFlags, UINT32 cmap, IPN IPServer, IPN IPMask, IPN IPClient ); Parameter(s) Physical index of serial port to use pppFlags Connection option flags cmap Async control character map IPServer...
Page 234
Serial HDLC Client and Server Support character (0 to 31) that must be escaped when sent by the peer. If the PPPFLG_SIOPT_SENDCMAP option is not set, it is assumed that all 32 characters must be sent via the escape sequence. IPServer –...
Page 235
Serial HDLC Client and Server Support SI_CSTATUS_CONFIGURE Connection in IP configuration stage SI_CSTATUS_CONNECTED Connection is fully connected and operational SI_CSTATUS_DISCONNECT Connection dropped SI_CSTATUS_DISCONNECT_LCP Connection dropped in LCP stage SI_CSTATUS_DISCONNECT_AUTH Connection dropped in authorization stage SI_CSTATUS_DISCONNECT_IPCP Connection dropped in IP configuration stage Description This function is called to get the connection status of a serial HDLC server ses- sion using the HDLC instance handle returned from hdlcsNew().
PPPoE Client and Server Support C.3 PPPoE Client and Server Support C.3.1 Please Note The PPPoE API is user callable. Unlike the low level PPP support API, users should not use the llEnter()/llExit() functions when calling the functions de- scribed in this section. C.3.2 Synopsis The PPPoE (PPP over Ethernet) specification allows for PPP packets to be transmitted in a peer to peer method over an Ethernet tunnel.
Page 237
PPPoE Client and Server Support Username Pointer to client account username Password Pointer to client account password Return Value If it succeeds, the function returns a handle to a PPPoE client instance. Else, it returns NULL. Description This function is called to create a new PPPoE client instance on the Ether type interface specified by the handle hEther.
Page 238
PPPoE Client and Server Support Get the Status of a PPPoE Client Session pppoeGetStatus Syntax uint pppoeGetStatus( HANDLE hPPPOE ); Parameter(s) hPPPOE Handle to PPPoE Client Session Return Value This function returns a uint that will be set to one of the following values: SI_CSTATUS_WAITING Connection is idle (PPPoE session opening)
Page 239
PPPoE Client and Server Support ServerName Server name reported via PPPoE protocol ServiceName Service name reported via PPPoE protocol Return Value If it succeeds, the function returns a handle to a PPPoE server instance. Else, it returns NULL. Description This function is called to create a new PPPoE sever instance on the Ether type interface specified by the handle hEther.
Page 240
PPPoE Client and Server Support length of this name including the NULL terminator is defined by PPPOE_NAMESIZE. If a longer name is supplied, this function will fail. ServiceName – This is a required pointer to a NULL terminated string con- taining the service name that is reported to PPPoE clients.
Creating PPP Sever User Accounts C.4 Creating PPP Sever User Accounts C.4.1 Synopsis In order to use the PPP or PPPoE protocol in server mode, it advisable to pro- tect access to the system through the use of a PPP authentication protocol. The PPP supplied in the stack library allows for the use of either PAP or CHAP in user authentication.
Page 242
Creating PPP Sever User Accounts // We must de–reference the account we found CfgEntryDeRef( hAcct ); return; // Fill in the CA record strcpy( CA.Username, name ); strcpy( CA.Password, password ); // Give user access to all channels CA.Flags = CFG_ACCTFLG_CH1|CFG_ACCTFLG_CH2|CFG_ACCTFLG_CH3|CFG_ACCTFLG_CH4; // Add it to the configuration rc = CfgAddEntry( 0, CFGTAG_ACCT, CFGITEM_ACCT_PPP, CFG_ADDMODE_NOSAVE, sizeof(CI_ACCT),...
Page 243
Creating PPP Sever User Accounts CfgEntryDeRef( hAcct ); return(0); // See if the username matches the search name. If so, return // the referenced handle if( !strcmp( name, CA.Username ) ) return( hAcct ); // Since we didn’t match, get the next entry. If there is no // next entry, we’re done searching.
Appendix D Appendix A Hardware Abstraction Layer (HAL) As discussed in the introduction, hardware devices are supported though a Hardware Abstraction Layer. This section describes the HAL API. This section is required only for system programmers who need low level ac- cess to the hardware for configuration and monitoring.
Overview D.1 Overview The function of the HAL is to provide resources to the stack library functions and allow them to operate independently of the current run–time environment. The HAL contains the functionality required by the stack that depends directly on the hardware in a particular environment.
Low-Level Timer Driver (llTimer) D.2 Low-Level Timer Driver (llTimer) D.2.1 Synopsis The stack code requires a very basic simple time function. It consists of two parts: a function API, which can be called from the stack to get the current time, and a “scheduler”...
Page 247
Low-Level Timer Driver (llTimer) Check for Timer Activity _llTimerServiceCheck Syntax UINT32 _llTimerServiceCheck(); Return Value No timer event At least one half second has elapsed since the last time the function returned 1 Description This function is called by the network scheduler to determine if there has been timer activity since the last call.
Low-Level Packet Driver (llPacket) D.3 Low-Level Packet Driver (llPacket) D.3.1 Synopsis The stack code requires a very basic packet function library. Note that although the high level packet API is documented here, the HAL contains a generic packet driver that implements this API. It is more efficient to use the standard llPacket driver and provide a hardware specific mini-driver than to implement the llPacket API from scratch.
Page 249
Low-Level Packet Driver (llPacket) Shutdown Driver Environment _llPacketShutdown Syntax void _llPacketShutdown(); Return Value nothing Description This function is called by NETCTRL to indicate a final shutdown of the packet driver environment. When called, there should be no currently open packet drivers, and _llPacketInit() will be called again before any call to llPacketO- pen().
Page 250
Low-Level Packet Driver (llPacket) Set Packet Receive Filter llPacketSetRxFilter Syntax void llPacketSetRxFilter( uint dev, uint filter ); Return Value nothing Description Called to set the types of packets which should be received via the receive indi- cation function. Each level of filter is inclusive of the previous level. They are: ETH_PKTFLT_NOTHING No Packets ETH_PKTFLT_DIRECT...
Page 251
Low-Level Packet Driver (llPacket) Set Multicast Address List llPacketSetMCast Syntax void llPacketSetMCast( uint dev, uint addrcnt, UINT8 *pbAddr ); Return Value nothing Description Called to install a list of multicast addresses on the physical device. The size of the list (supplied as an address count) is in addrcnt. The list is a contiguous stream of 6 byte addresses pointed to by pbAddr.
Page 252
Low-Level Packet Driver (llPacket) Return an Rx Buffer to the System llPacketReturnBuffer Syntax void llPacketReturnBuffer( UINT8 *bAddr ); Description Called to return a packet buffer to the system, which was previously obtained from a call to llPacketGetBuffer(). This is done so packet drivers that use their own buffer pools can support passing buffer ownership without copying buffer data.
Low-Level Serial Port Driver (llSerial) D.4 Low-Level Serial Port Driver (llSerial) D.4.1 Synopsis In the current directory structure, the serial port driver (llSerial) may or may not be part of the HAL directory (as it is an optional component). However, it is part of the HAL architecture, and should be programmed using the same guide- lines used for the llTimer and llPacket drivers.
Page 254
Low-Level Serial Port Driver (llSerial) Shutdown Driver Environment _llSerialShutdown Syntax void _llSerialShutdown(); Return Value nothing Description This function is called by NETCTRL to indicate a final shutdown of the serial driver environment. When called, there should be no currently open serial driv- ers, and _llSerialInit() will be called again before any call to llSerialOpenChar- mode() or llSerialOpenHDLC().
Page 255
Low-Level Serial Port Driver (llSerial) When opening the device, the driver should save the callback function pointer pCharmodeRxCb. This function should be called for each character received while in character mode. When the driver is opened in HDLC mode, no charac- ter mode input is received.
Page 256
Low-Level Serial Port Driver (llSerial) Configure Serial Port llSerialConfig Syntax void llSerialConfig( uint dev, uint baud, uint mode, uint flowctrl ); Return Value nothing Description This function is called by NETCTRL to configure the serial port attributes for the indicated device. The value of baud is the baud rate, and must be an even denominator of 230400, up to a max baud rate of 230400.
Page 257
Low-Level Serial Port Driver (llSerial) Get a Serial Buffer from the System llSerialGetBuffer Syntax UINT8 *llSerialGetBuffer(); Return Value nothing Description Called to get a serial buffer from the system, which will eventually be sent via llSerialSend(), or returned to the driver via llSerialReturnBuffer(). Buffering is done in this fashion so drivers that use their own buffer pools can support pass- ing buffer ownership without copying data.
Appendix E Appendix A Web Programming with the HTTP Server The easiest way for a user to get information from an embedded network de- vice is through the web server. The HTTP server pulls files from the embedded file system (EFS) that is included in the NDK software package’s OS adapta- tion layer.
Adding WEB Content E.1 Adding WEB Content E.1.1 Operation As previously mentioned, the HTTP server allows access to files using the em- bedded file system (EFS) API. The default instantiation of this API is a RAM based file system that resides in the OS adaptation layer. This OS adaptation layer allows the HTTP server to work on any file storage device contained in the system.
Page 260
Adding WEB Content An example implementation of AddWebFiles() is shown below. Note the addi- tion of two more file creation calls. The first call to efs_createfile() creates the file we declared in default.c as converted from the file default.htm. The second call shows an alternate method of creating files.
Writing CGI Functions E.2 Writing CGI Functions E.2.1 Adding Functions to the EFS CGI programs must be in the EFS for the HTTP server to see them. An exam- ple of this was shown in the previous section by adding an entry for the file that translated into the C function cgiSample().
Page 262
Writing CGI Functions After reading in the data from the socket, each form entry can be parsed from the from by using the supplied example function: cgiParseVars(). The formal definition of the function is shown below. Note that this function replaces parsePostVars(), a similar function that was included in earlier versions of the Network Developer’s Kit.
Page 263
Writing CGI Functions httpSendFullResponse() Send full HTTP response, including a sta- tus code and an HTML file httpSendStatusLine() Send HTTP status response, including a status code and content type httpSendClientStr() Used after httpSendStatusLine() to send content data As an example of using these function, consider the two response MACROS included in hpptif.h // Common error responses...
CGI Function Example E.3 CGI Function Example As an example of using all the concepts described so far, consider a simple example. Assume an applications programmer wishes to create a WEB form that inputs and processes user data. E.3.1 Create the HTML Page The HTML page can be created with an HTML editor, or by hand.
Page 265
CGI Function Example E.3.2 Create the Base WEBPAGE Source File Once the HTML pages are ready in source form, the main WEBPAGE.C source file is created. This file will perform all the necessary WEB processing in the example. The basic source code declares the HTML pages as ”files” to the EFS file system.
Page 266
CGI Function Example 5) Send appropriate headers. 6) Send the response data. This could be a file or data generated by the CGI program. In addition to the commonly used strings defined in section E.4.1, in the exam- ple function we define some additional strings that are used more than once. There is also a MACRO to help disguise calls to httpSendClientStr(), and make the source code a little more readable.
Page 267
CGI Function Example // 3. Process request in some meaningful way . . . // (OK, we really don’t do this here.) // 4. Send a response. Keep in mind the first line of the response should indicate whether the request was successful or not.
HTTP Sever Exported Functions E.4 HTTP Sever Exported Functions The HTTP server module exports several functions and strings to aid in the creation of a CGI function. This section contains the formal specification for these functions. The first part of this appendix describes how to use these func- tions in creating a HTTP CGI function in C.
Page 269
HTTP Sever Exported Functions E.4.3 HTTP Server Exported API Functions Send the Status of this Request to the Client httpSendStatusLine Syntax void httpSendStatusLine( int Sock, int StatusCode, char *ContentType ); Parameter(s) Sock Socket on which to send StatusCode HTTP status code of the request ContentType HTTP type string of the response Return Value...
Need help?
Do you have a question about the TMS320C6000 and is the answer not in the manual?
Questions and answers