[ Previous ] [ Contents ] [ Index ] [ Next ]

C API Function Categories

The C API functions fall into these categories, which are described in the sections that follow:

Memory Allocation Functions

A set of wrapper functions for the malloc family of memory allocation functions that attempt to recover automatically from a low-memory situation.

Data Structures and Related Functions

Data structures and related functions for manipulating data common in HTTP connection requests and working with active HTTP connections.

Core Functions

An extensive set of functions for interacting with AOLserver.

Database Functions

A set of functions for accessing the database and obtaining information about the database.

Memory Allocation Functions

The AOLserver uses dynamically allocated memory extensively. To ease the burden of checking for memory-allocation failures, the AOLserver provides wrapper functions for the malloc family of memory allocation functions.

The AOLserver functions differ from their system counterparts: instead of returning NULL on memory-allocation failure, they instead attempt to recover automatically from a low-memory situation. The AOLserver attempts to recover by first freeing any memory from internal caches that can safely be flushed. If flushing caches fails to free enough memory, the AOLserver will wait 1 second and then, if necessary, another 10 seconds, in the hope that the memory shortage is temporary, perhaps caused by another program that will shortly stop executing. If the AOLserver cannot recover from a low-memory situation, it logs the failure and shuts down the server.

Using the AOLserver memory allocation functions is a matter replacing the corresponding malloc family system function with a function of the same name preceded by ns_. You can currently mix calls to the ns_ functions and their system counterparts. However, this is not recommended because the interface may change in future releases of AOLserver.

The memory allocation functions are listed below.

Function

Description

Ns_Calloc

Allocate a zero-filled block of memory

Ns_Free

Free a block of allocated memory

Ns_Malloc

Allocate a block of memory

Ns_Realloc

Resize a previously allocated block of memory

Ns_StrCopy

Copy a string or NULL value using Ns_Malloc

Ns_StrDup

Copy a string using Ns_Malloc

Data Structures and Related Functions

The AOLserver C API provides the following data structures for manipulating data common in HTTP connection requests and working with active HTTP connections.

Ns_Set Structure

A string key-value pair structure, such as for database rows, HTTP header information, and HTTP form data.

Ns_DString Structure

A structure used to implement dynamic memory blocks, typically strings.

Ns_Conn Structure

A structure that includes all state information of an active HTTP connection.

Ns_Request Structure

A structure that contains the various parts of the HTTP request of an active connection.

Ns_Set Structure

An AOLserver C API function must often access data as sets of key-value pairs, for example:

The Ns_Set structure provides a convenient mechanism for manipulating key-value pairs of string data. The key-value pairs in an Ns_Set are Ns_SetFields (called "fields" for short). The Ns_SetField structure has the following definition:

    
    typedef struct {
    	char *name;		  /* Key name of field. */
    	char *value;		 /* Value of field (can be NULL) */
    } Ns_SetField;
    

The Ns_Set structure has the following definition:

    
    typedef struct {
    	char 	*name;    	/* Name of set (can be NULL) */
    	int   size;    		/* Current number of fields */
    	int   maxSize;			 /* (used internally) */
    	Ns_SetField *fields; 	/* Array of Ns_SetField's */
    } Ns_Set;
    

Within the Ns_Set, the fields are stored as an array, in the order in which the fields were added to the set. The array of fields grows dynamically as fields are entered.

To access the fields of a set, either use the lookup functions described below or loop through the fields directly as in the following code fragment:

    
    	for (n = 0; n < Ns_SetSize(set); ++n) {
    		printf("field %d name: %s value: %s\n",
    			n, Ns_SetKey(set, n), Ns_SetValue(set, n));
    	}

The functions that use the Ns_Set data structure are listed in the following table.

Function

Description

Ns_SetCopy

Create a new copy of a set

Ns_SetCreate

Create a new Ns_Set

Ns_SetDelete

Remove a field from a set by field index

Ns_SetDeleteKey

Remove a field from a set by key name

Ns_SetFind

Locate the index of a field within an Ns_Set

Ns_SetFree

Free memory used by an Ns_Set

Ns_SetGet

Return the value for a field

Ns_SetIDeleteKey

Remove a field from a set by key name case-insentively

Ns_SetIFind

Locate the index of a field case-insensitively

Ns_SetIGet

Return the value for a field case-insensitively

Ns_SetIUnique

Check if a key in an Ns_Set is unique (case insensitive)

Ns_SetKey

Return the key name of a field

Ns_SetLast

Return the index of the last element of a set

Ns_SetListFind

Locate a set by name in a set list

Ns_SetListFree

Free a list of sets

Ns_SetMerge

Merge two sets

Ns_SetMove

Move fields from one set to the end of another

Ns_SetName

Return the name of a set

Ns_SetPrint

Print the contents of a set to the AOLserver error log

Ns_SetPut

Add a field to an Ns_Set

Ns_SetPutValue

Set the value of a field

Ns_SetSize

Return the current size of a set

Ns_SetSplit

Split a set into an array of new sets

Ns_SetTrunc

Truncate an Ns_Set

Ns_SetUnique

Check if a key in an Ns_Set is unique (case sensitive)

Ns_SetUpdate

Update an Ns_Set value

Ns_SetValue

Return the value of a field

Ns_TclEnterSet

Make an Ns_Set accessible through Tcl

Ns_TclFreeSet

Free an Ns_Set

Ns_TclGetSet

Return the Ns_Set for the specified set ID

Ns_TclGetSet2

Return the Ns_Set for the specified set ID in a pointer

Ns_DString Structure

An AOLserver C API function often uses dynamically allocated strings. The Ns_DString structure is used for this purpose. (The AOLserver Ns_DString is based on the Tcl_DString found in the Tcl C API.) Ns_DStrings contains a small amount of static space but will overflow to allocated memory if needed. Within the AOLserver, pointers to Ns_DStrings are often used where other APIs would require a pointer to a buffer and a specific size.

The Ns_DString structure has the following definition:

    typedef struct {
      char *string;    /* Points to either static space or dynamically
                          allocated memory */
      int length;      /* Number of bytes in string */
      int spaceAvl;    /* Number of bytes unused but allocated for
                          string */
      char staticspace [NS_DSTRING_STATIC_SIZE]; 
                       /* Initial static space. */
    } Ns_DString;

NS_DSTRING_STATIC_SIZE is by default set to 512 bytes.

The functions that use the Ns_DString data structure are listed in the following table.

Ns_DStringAppend

Append a string to an Ns_DString

Ns_DStringAppendArg

Append argument to an Ns_DString

Ns_DStringExport

Export the string of an Ns_DString

Ns_DStringFree

Free any allocated memory used by an Ns_DString

Ns_DStringInit

Initialize an Ns_DString

Ns_DStringLength

Return the current length of an Ns_DString

Ns_DStringNAppend

Append n-characters of a string to an Ns_DString

Ns_DStringPrintf

Append a formatted string to an Ns_DString

Ns_DStringTrunc

Truncate an Ns_DString

Ns_DStringValue

Return the current value of an Ns_DString

Ns_DStringVarAppend

Append a variable number of strings to an Ns_DString

Ns_Conn Structure

All functions that handle connection requests, which we refer to as AOLserver operations, take as an argument a pointer to an Ns_Conn structure. This structure contains all information and state about the active connection. The public members that you may find useful include:

    typedef struct Ns_Conn {
    Ns_Request *request;

Pointer to an Ns_Request structure that holds information about the HTTP request associated with the connection. The Ns_Request structure is described below.

    Ns_Set *headers;

Pointer to an Ns_Set whose fields are the HTTP request headers sent by the HTTP client.

    Ns_Set *outputheaders;

Pointer to an Ns_Set whose fields are the headers to be sent to the client.

    char *authUser;

Decoded user name from the header information. Because the AOLserver does not authenticate the user when world permission is allowed to a URL, this user may not be a valid AOLserver user.

    char *authPasswd;

Decoded user password from the header information. Because the AOLserver does not authenticate the user when world permission is allowed to a URL, this password may not be the user's actual password.

    int contentLength;

Number of bytes in the content sent by the HTTP client.

    } Ns_Conn;

Ns_Request Structure

The Ns_Request structure breaks a complete HTTP request line into its many parts.

    typedef struct Ns_Request {
    char *line;

A copy of the actual request line sent by the HTTP client.

    char *method;

HTTP method; for example GET or POST.

    char *protocol;

Protocol of the HTTP request, e.g., http or ftp. Normally, this element is NULL because the AOLserver does not currently proxy requests, so fully-qualified URLs in HTTP requests are rejected.

    char *host;

Host part of the URL in the HTTP request. Normally this element is NULL because the AOLserver does not currently proxy HTTP requests.

    unsigned short port;

Port explicitly specified in the URL of the HTTP request. This element is 0 when no port is explicitly specified.

    char *url;

URL after having been normalized with Ns_NormalizePath() function and after removing any query data that may have been appended.

    char *query;

Any query data appended to the URL. (Query data are any data that follow a question mark at the end of a URL. They can be used to pass arguments to an operation.)

    int urlc;

Number of path elements in the normalized URL. This is similar to the argc parameter to the main() function in a C program. For example, if the URL were /some/url, urlc would be 2.

    char **urlv;

NULL-terminated array of pointers to strings for each path element of the normalized URL. This is similar to the argv parameter to the main() function in a C program. For example, if the URL was /some/url, urlv[0] would be "some", urlv[1] would be "url", and urlv[2] would be NULL.

    double version;

Version of the HTTP request, usually 0.9 or 1.0.

    } Ns_Request;

The AOLserver provides several convenient functions for working with the elements of the Ns_Request structure. The functions that use the Ns_Request data structure are listed in the following table.

Ns_FreeRequest

Free memory used by an Ns_Request

Ns_ParseRequest

Parse an HTTP request line into an Ns_Request

Ns_SetRequestUrl

Fill in request structure

Ns_SkipUrl

Skip past path elements in the URL of a request

Core Functions

The groups of core functions listed below are described in the following subsections.

Registration Functions

Functions used to register other functions to handle HTTP requests or implement traces, chores, or shutdown procedures.

Access Control Functions

Functions used to check authorization on a method/URL combination or implement an alternative authorization procedure.

Caching Functions

Functions used to manage caching.

Configuration File Functions

Functions used to access the in-memory representation of the configuration file data.

URL and File Functions

Functions used to convert URLs to files within the pages directory and test the files for various properties

HTTP Header-Related Functions

Functions used to generate and send HTTP headers to a browser

HTTP Complete Response Functions

Functions used to generate complete responses to HTTP requests

HTTP Simple Response Functions

Functions used to call Ns_ConnReturnStatus or Ns_ConnReturnNotice with the appropriate status code, reason, and notice message when the only response required by the AOLserver is the HTTP status line.

HTTP Low-Level Connection Functions

Functions used to send data directly to the client without formatting or immediate buffering of the data.

Logging Functions

Functions used to write information to the AOLserver log file.

Memory Pool Functions

Functions used to manipulate the memory pools used by AOLserver.

Mime-Related Functions

Functions used to access and manipulate Mime type information.

Module Logging Realms Functions

Functions used to control realms for module logging.

Scheduled Procedures Functions

Functions used to schedule procedures to be run daily, weekly, or at specified intervals.

Sockets Interface Functions

Functions for managing sockets.

Socket Driver Interface Functions

Functions for socket drivers.

Storage and Retrieval Functions

Functions used to store and retrieve information specific to URLs or servers.

Synchronization Functions

Functions used to manage condition variables, semaphores, mutexes, events, critical sections, and read/write locks.

Thread Interface Functions

Functions used to interact with the threads interface of AOLserver.

Tcl Interpreter Functions

Functions used to allocate and return Tcl interpreters.

Miscellaneous Functions

Functions used to perform miscellaneous tasks and get information about the server.

Registration Functions

At startup time, the server loads your C module and runs your initialization function. Your initialization function can connect to any external data sources or initialize any data structures it requires. The initialization function then typically calls one or more of the following functions to register other functions within the module as capable of handling URL requests or implementing traces, chores, or shutdown procedures.

The functions in this category are listed in the following table.

Ns_AdpRegisterParser

Register a parser for ADPs

Ns_GetRequest

Return the parameters of a request

Ns_RegisterAtExit

Register an exit procedure.

Ns_RegisterAtPreStartup

Register a procedure for pre-server startup

Ns_RegisterAtSignal

Register a procedure at HUP signal

Ns_RegisterAtStartup

Register a procedure for server startup

Ns_RegisterCleanup

Register a procedure for connection cleanup trace

Ns_RegisterFilter

Register a filter function to handle a method/URL combination

Ns_RegisterProxyRequest

Register a function to proxy requests for a method/protocol combination

Ns_RegisterRequest

Register a function to handle HTTP requests for a method/URL combination

Ns_RegisterReturn

Register a return status for a URL

Ns_RegisterServerShutdown

Register a shutdown procedure for a server.

Ns_RegisterServerTrace

Register a trace procedure for a server.

Ns_RegisterShutdown

Register a shutdown procedure.

Ns_UnRegisterProxyRequest

Unregister a proxy request function

Ns_UnRegisterRequest

Unregister a function

Access Control Functions

The hierarchical access checking authorization system is accessed through the following functions.

Ns_AuthorizeRequest

Check access of a method and URL

Ns_AuthorizeUser

Check username and password

Ns_PermPasswordCheck

Check user's encrypted password

Ns_SetRequestAuthorizeProc

Set function used by Ns_AuthorizeRequest

Ns_SetUserAuthorizeProc

Set function used by Ns_AuthorizeUser

Caching Functions

Caching is managed with the following functions:

Ns_CacheBroadcast

Broadcast to condition variable

Ns_CacheCreate

Create a new cache

Ns_CacheCreateEntry

Create a cache entry

Ns_CacheCreateSz

Create a size-based cache

Ns_CacheDeleteEntry

Delete a cache entry

Ns_CacheFind

Find a cache

Ns_CacheFindEntry

Find a cache entry

Ns_CacheFirstEntry

Get first cache entry

Ns_CacheFlush

Flush all cache entries

Ns_CacheFlushEntry

Delete a cache entry

Ns_CacheFree

Free allocated memory

Ns_CacheGetValue

Get value of cache entry

Ns_CacheKey

Get key of cache entry

Ns_CacheLock

Lock a cache

Ns_CacheMalloc

Allocate memory

Ns_CacheName

Get name of cache

Ns_CacheNextEntry

Get next cache entry

Ns_CacheSetValue

Set value of cache entry

Ns_CacheSetValueSz

Set value of cache entry and adjust cache size

Ns_CacheSignal

Signal cache's condition variable

Ns_CacheTimedGetValue

Wait for cache entry to be set

Ns_CacheTimedWait

Wait for condition variable to be set

Ns_CacheUnlock

Unlock cache

Ns_CacheUnsetValue

Reset cache entry to null

Ns_CacheWait

Wait indefinitely for condition variable to be set

Configuration File Functions

When the server is started, it reads the AOLserver configuration file into memory. You can use the following functions to access the in-memory representation of those data. See Chapter 4 in the AOLserver Administrator's Guide for more information on the AOLserver configuration file.

Ns_ConfigGetBool

Get a boolean configuration file variable

Ns_ConfigGetInt

Get a configuration file integer variable

Ns_ConfigGetInt64

Get a configuration file 64-bit integer variable

Ns_ConfigGetPath

Return configuration file section name

Ns_ConfigGetSection

Get the Ns_Set for a configuration file section

Ns_ConfigGetSections

Return Ns_Sets with configuration file data

Ns_ConfigGetValue

Get a configuration file variable

Ns_ConfigGetValueExact

Get configuration variable case-sensitively

URL and File Functions

AOLserver operations often work with files within the pages directory. These files normally are related to URLs that are requested by clients. The AOLserver provides the following functions for converting URLs to files within the pages directory and testing the files for various properties.

Ns_AbsoluteUrl

Construct a URL from a URL and location

Ns_DecodeUrl

Decode URL query data

Ns_EncodeUrl

Encode URL query data

Ns_HomePath

Construct a path name relative to the AOLserver home directory

Ns_MakePath

Construct a path name from a list of path elements

Ns_ModulePath

Construct a path from base path

Ns_NormalizePath

Normalize a path name

Ns_PathIsAbsolute

Check for an absolute path name

Ns_QueryToSet

Parse query data into Ns_Set

Ns_RelativeUrl

Get relative filename portion of URL

Ns_SetUrlToFileProc

Customize relative file mapping

Ns_UrlIsDir

Check if a directory that corresponds to a URL exists

Ns_UrlIsFile

Check if a file that corresponds to a URL exists

Ns_UrlToFile

Construct the filename that corresponds to a URL

HTTP Header-Related Functions

The C API includes the following functions to generate and send HTTP headers to a browser. If the original request was not HTTP version 1.0 or higher, these functions do not send the headers to the client. This allows you to write header generating code without regard to HTTP version.

Ns_ConnCondSetHeaders

Set the value for a header field conditionally

Ns_ConnConstructHeaders

Put HTTP header into DString

Ns_ConnFlushHeaders

Mark the end of the headers

Ns_ConnOutputHeaders

Get Ns_Set of headers to send to client

Ns_ConnPrintfHeader

Return a formatted header

Ns_ConnReplaceHeaders

Replace output headers for connection

Ns_ConnSetExpiresHeader

Return an "expires" header for the given time

Ns_ConnSetHeaders

Set the value for a header field

Ns_ConnSetLastModifiedHeader

Return a last modified header using the given time

Ns_ConnSetLengthHeader

Return a Content-Length header

Ns_ConnSetRequiredHeaders

Return the required HTTP headers

Ns_ConnSetTypeHeader

Return a Content-Type header

HTTP Complete Response Functions

The following functions can be used to generate complete responses to HTTP requests.

Ns_ConnReturnAdminNotice

Return a short notice to a client to contact system administrator

Ns_ConnReturnData

Return an HTML string to a client

Ns_ConnReturnFile

Return a file to a client

Ns_ConnReturnHtml

Return an HTML string to a client

Ns_ConnReturnNotice

Return a short notice to a client

Ns_ConnReturnOpenFd

Return a file to a client

Ns_ConnReturnOpenFile

Return a file to a client

Ns_ConnReturnRedirect

Return an HTTP redirect response to a client

Ns_ConnReturnStatus

Return a status message to a client

HTTP Simple Response Functions

Often the only response required by the AOLserver is the HTTP status line. For example, after a successful PUT of a new file, the only required response is the status line to indicate if the file was successfully saved on the server. The following functions call Ns_ConnReturnStatus or Ns_ConnReturnNotice with the appropriate status code, reason, and/or notice message:

Ns_ConnReturnBadRequest

The request was invalid. Status = 400

Ns_ConnReturnForbidden

The request is forbidden. There is no Authorization header that will authorize access from this IP address. Status = 403

Ns_ConnReturnInternalError

A server internal error occurred. Status = 500

Ns_ConnReturnNoResponse

The request requires no response. Status = 204

Ns_ConnReturnNotFound

The requested URL was not found on the server. Status = 404

Ns_ConnReturnNotImplemented

The request has not been implemented by the server. Status = 500

Ns_ConnReturnNotModified

The requested data have not been modified since the time specified by the If-Modified-Since header sent by the client. Status = 304

Ns_ConnReturnOk

The request was successful. Status = 200

Ns_ConnReturnUnauthorized

The request did not include a valid Authorization header or the header did not specify an authorized user. Status = 401

Ns_ConnRunRequest

Execute procedure for method and URL pattern

HTTP Low-Level Connection Functions

The following functions can be used to send data directly to the client. No formatting or immediate buffering is done to the data.

Ns_ConnAuthPasswd

Return password

Ns_ConnAuthUser

Return user name

Ns_ConnClose

Close a connection

Ns_ConnContentLength

Return content length

Ns_ConnContentSent

Check if browser sent content

Ns_ConnCopyToChannel

Copy content to Tcl channel

Ns_ConnCopyToDString

Copy data from connection to dynamic string

Ns_ConnCopyToFd

Copy content to file descriptor

Ns_ConnCopyToFile

Copy data from connection to a file

Ns_ConnDriverContext

Return driver context

Ns_ConnDriverName

Return driver name

Ns_ConnFlushContent

Flush remaining content

Ns_ConnGetQuery

Construct Ns_Set representing query data

Ns_ConnGets

Read content into a buffer

Ns_ConnHeaders

Return headers

Ns_ConnHost

Return host

Ns_ConnInit

Run socket init procedure

Ns_ConnLocation

Return location

Ns_ConnModifiedSince

Determine if content modified since a specified date

Ns_ConnPeer

Return name of peer

Ns_ConnPeerPort

Return peer port

Ns_ConnPort

Return port

Ns_ConnPuts

Send a string to a client

Ns_ConnRead

Read content into buffer

Ns_ConnReadHeaders

Read headers into Ns_Set

Ns_ConnReadLine

Read a line from a connection

Ns_ConnRedirect

Perform internal redirect

Ns_ConnResponseLength

Return response length

Ns_ConnResponseStatus

Return response status

Ns_ConnReturnOpenChannel

Write Tcl channel content to conn

Ns_ConnSendChannel

Send Tcl channel content to conn

Ns_ConnSendDString

Write a DString to the conn

Ns_ConnSendFd

Write file to connection content

Ns_ConnSendFp

Write file to connection content

Ns_ConnServer

Return name of server

Ns_ConnWrite

Send data to a client

Ns_DriverEnableKeepalive

Enable HTTP Keepalive on driver

Ns_WriteConn

Send a specified length of data to the client

Logging Functions

The functions in this category are listed in the following table.

Ns_Fatal

Log a fatal error and shutdown

Ns_Log

Log formatted message

Ns_LogRoll

Roll server log

Ns_LogTime

Construct local date and time for log file

Ns_RollFile

Rename a file and increment its backup number

Memory Pool Functions

The functions in this category are listed in the following table:

Ns_PoolAlloc

Allocate memory within a pool

Ns_PoolCreate

Create a new memory pool

Ns_PoolDestroy

Destroy a memory pool

Ns_PoolDump

Debug a memory pool

Ns_PoolFree

Free pool memory

Ns_PoolRealloc

Reallocate pool memory

Ns_PoolTrace

Trace a memory pool

Ns_ThreadFree

Free thread pool memory

Ns_ThreadMalloc

Allocate thread pool memory

Ns_ThreadPool

Get thread pool memory

Ns_ThreadRealloc

Realloc thread pool memory

Mime-Related Functions

The functions in this category are listed in the following table.

Ns_GetMimeType

Get Mime type

Module Logging Realms Functions

The functions in this category are listed in the following table.

Ns_ModLog

Log a message with a realm

Ns_ModLogGetThreshold

Get the severity of the logging threshold of a handle

Ns_ModLogLookupHandle

Obtain the handle of a given realm

Ns_ModLogLookupRealm

Obtain the realm from the handle

Ns_ModLogRedirect

Redirect logging of a realm to a file

Ns_ModLogRegister

Register a new realm

Ns_ModLogSetThreshold

Set the logging severity of a handle

Scheduled Procedures Functions

These functions allow you to specify a procedure to be run daily, weekly, or at specified intervals

Function

Description

Ns_ScheduleDaily

Schedule a procedure to run once a day

Ns_ScheduleProc

Schedule a procedure to run at specified intervals (simplified options)

Ns_ScheduleProcEx

Schedule a procedure to run at specified intervals (expanded options)

Ns_ScheduleWeekly

Schedule a procedure to run once a week

Ns_UnscheduleProc

Stop a scheduled procedure

Sockets Interface Functions

The following functions are available for managing sockets. Developers should consult a book on socket programming when using these functions, for example "Unix Network Programming" by W. Richard Stevens.

Function

Description

Ns_BindSock

Bind a socket as root

Ns_GetSockAddr

Get socket driver address

Ns_SockAsyncConnect

Create a remote socket and return immediately

Ns_SockCallback

Register a socket callback function

Ns_SockCancelCallback

Remove a socket callback

Ns_SockConnect

Create a socket to remote host and port

Ns_SockListen

Create a socket on a specified address and port

Ns_SockListenCallback

Register a socket callback function and create socket

Ns_SockPipe

Return a pair of connected sockets

Ns_SockPortBound

Determine if port is bound

Ns_SockSetBlocking

Set a socket in blocking mode

Ns_SockSetNonBlocking

Set a socket in nonblocking mode

Ns_SockTimedConnect

Create a remote socket within a specified time

Socket Driver Interface Functions

The functions in this category are listed in the following table:

Ns_GetDriver

Get socket driver

Ns_GetDriverContext

Get socket driver context

Ns_GetDriverLabel

Get socket driver label

Ns_GetDriverName

Get socket driver name

Ns_GetDriverProc

Get a communications driver procedure

Ns_GetFirstDriver

Get pointer to first socket driver

Ns_GetNextDriver

Get pointer to next socket driver

Ns_QueueConn

Make a queue a new conn

Ns_RegisterDriver

Register a socket driver

Ns_RegisterLocation

Register location for socket driver

Ns_SetDriverProc

Set socket driver callback

Storage and Retrieval Functions

The functions in this category are listed in the following table. In rows where more than one function is listed, the preferred function is listed first.

Ns_ServerSpecificAlloc

Return unique integer to use in other functions

Ns_ServerSpecificDestroy

Delete server-specific data

Ns_ServerSpecificGet

Retrieve server-specific data

Ns_ServerSpecificSet

Store server-specific data for subsequent retrieval

Ns_TlsAlloc, Ns_AllocThreadLocalStorage

Allocate thread local storage

Ns_TlsGet, Ns_GetThreadLocalStorage

Get thread local storage

Ns_TlsSet, Ns_SetThreadLocalStorage

Set thread local storage

Ns_UrlSpecificAlloc

Return unique integer to use in other functions

Ns_UrlSpecificDestroy

Delete URL-specific data

Ns_UrlSpecificGet

Retrieve URL-specific data

Ns_UrlSpecificGetExact

Retrieve URL-specific data without inheritance

Ns_UrlSpecificSet

Store URL-specific data for subsequent retrieval

Synchronization Functions

Condition Variables

Condition variables are managed with the following functions

Ns_CondBroadcast

Wake up all threads waiting on a cond

Ns_CondDestroy

Free a cond's memory

Ns_CondInit

Initialize a cond

Ns_CondSignal

Wake up a single thread

Ns_CondTimedWait

Block on a cond

Ns_CondWait

Wait indefinitely on a cond

Semaphores

Semaphores are managed with the following functions. The preferred function is listed first in each row.

Ns_SemaDestroy, Ns_DestroySemaphore

Destroy a semaphore object

Ns_SemaInit, Ns_InitializeSemaphore

Initialize a semaphore object

Ns_SemaPost, Ns_ReleaseSemaphore

Increment a semaphore object

Ns_SemaWait, Ns_WaitForSemaphore

Wait for a semaphore object to be incremented above 0.

Mutexes

Mutexes are managed with the following functions. The preferred function is listed first in each row.

Ns_MutexDestroy, Ns_DestroyMutex

Destroy a mutex object

Ns_MutexInit, Ns_InitializeMutex

Initialize a mutex object

Ns_MutexLock, Ns_LockMutex

Lock a mutext object

Ns_MutexUnlock, Ns_UnlockMutex

Unlock a mutext object

Events

Events are managed with the following functions:

Ns_AbsTimedWaitForEvent

Wait for an event to be broadcast

Ns_BroadcastEvent

Wake all threads blocked in Ns_WaitForEvent.

Ns_DestroyEvent

Destory an event object.

Ns_InitializeEvent

Initialize an event object.

Ns_SetEvent

Wait no more than one thread blocked in Ns_WaitForEvent

Ns_TimedWaitForEvent

Wait for an event to be raised or a timeout.

Ns_UTimedWaitForEvent

Wait for an event for a specified time, in microseconds

Ns_WaitForEvent

Wait for an event to be raised.

Critical Sections

Critical sections are managed with the following functions. The preferred function is listed first in each row.

Ns_CsDestroy, Ns_DestroyCriticalSection

Destroy a critical section object

Ns_CsEnter, Ns_EnterCriticalSection

Enter a critical section of code

Ns_CsInit, Ns_InitializeCriticalSection

Initialize a critical section object

Ns_CsLeave, Ns_LeaveCriticalSection

Leave a critical section of code

Read/write Locks

Read/write locks are managed with the following functions. The preferred function is listed first in each row.

Ns_RWLockDestroy, Ns_DestroyRWLock

Destroy a read/write lock

Ns_RWLockInit, Ns_InitializeRWLock

Initialize a read/write lock

Ns_RWLockRdLock, Ns_ReadLockRWLock

Acquire a read lock

Ns_RWLockUnlock, Ns_ReadUnlockRWLock, Ns_WriteUnlockRWLock

Release a read/write lock

Ns_RWLockWrLock, Ns_WriteLockRWLock

Acquire a write lock

Thread Interface Functions

The following functions are used to support platform independent multithreaded programming. A table following this list of functions points you to further information for each function.

Ns_CheckStack

Check for thread stack overflow

Ns_Fork

Perform a fork

Ns_GetThread

Get the thread object of the current thread.

Ns_GetThreadId

Get a unique integer ID for the current thread.

Ns_ThreadCreate, Ns_BeginThread, Ns_BeginDetachedThread

Create new thread

Ns_ThreadExit, Ns_ExitThread

Free or exit thread

Ns_ThreadGetName

Get thread name

Ns_ThreadId

Get thread ID

Ns_ThreadJoin, Ns_WaitThread, Ns_WaitForThread

Wait for thread exit

Ns_ThreadSelf

Get handle to thread

Ns_ThreadSetname

Set thread name

Ns_ThreadYield

Put the current thread to sleep momentarily, allowing other threads to run,

Ns_WaitForProcess

Wait for process to exit

Ns_WaitForStartup

Block until server startup

Ns_WaitProcess

Wait for process to exit

The following table tells you what to look under in your vendor-specific documentation for more information on threaded programming with respect to each function.

Function

Solaris

pthread

SGI sproc (2)

Threads:

Ns_ThreadCreate

thr_create

pthread_create

sproc (4)

Ns_ThreadJoin

thr_join

pthread_join (3)

waitpid

Ns_GetThreadId

thr_self

pthread_self

getpid

Mutexes:

Ns_MutexInit

mutex_int

pthread_mutex_init

usnewlock

Ns_MutexDestroy

mutex_destroy

pthread_mutex_des-troy

usfreelock

Ns_MutexLock

mutex_lock

pthread_mutex_lock

ussetlock

Ns_MutexUnlock

mutex_unlock

pthread_mutex_un-lock

usunsetlock

Semaphores:

Ns_SemaInit

sema_int

(5)

usnewsema

Ns_SemaDestroy

sema_destroy

(5)

usfreesema

Ns_SemaWait

sema_wait

(5)

uspsema

Ns_SemaPost

sema_post

(5)

usvsema

Events:

Ns_InitializeEvent

cond_int

pthread_cond_init

(6)

Ns_DestroyEvent

cond_destroy

pthread_cond_destroy

(6)

Ns_WaitForEvent

cond_wait

pthread_cond_wait

sigtimedwait

Ns_TimedWaitForEvent

cond_timedwait

pthread_cond_timed-wait

sigtimedwait

Ns_SetEvent

cond_signal

pthread_cond_signal

kill

Ns_BroadcastEvent

cond_broadcast

pthread_cond_broad-cast

kill

Critical Sections:

Ns_CsInit

(10)

pthread_mutex_init (10)

(10)

Ns_CsDestroy

(10)

pthread_mutex_de-stroy

(10)

Ns_CsEnter

(10)

pthread_mutex_lock

(10)

Ns_CsLeave

(10)

pthread_mutex_un-lock

(10)

Ns_TlsAlloc

thr_keycreate

pthread_keycreate

(11)

Ns_TlsSet

thr_setspecific

pthread_setspecific

(11)

Ns_TlsGet

thr_getspecific

pthread_getspecific

(11)

Notes:

(2) Threads on SGI Irix 5.3 are implemented as a process group with all attributes shared. As such, threads will show up as separate processes in a process listing using the ps command. Note, however, that although the server is implemented with multiple processes, it is still multithreaded in all respects (e.g., a single address space, open file table, etc.). In addition, if one process dies unexpectantly (e.g., core dump or on receiving a kill -9), the other processes will be notified and immediately exit. On Irix 6.2, you may run the 5.3 share group version (nsd binary) or a newer pthreads interface binary (nsdp).

(3) The pthread_join routine would allow multiple threads to wait for a single thread to exit on pthreads. However, in the nsthread library, only a single thread may wait using the Ns_ThreadJoin function.

(4) To allow any thread to wait for any other thread as in other multithreaded platforms, the SGI Irix threads interface uses a thread manager process which actually performs the sproc and waitpid calls on behalf of the other process threads.

(5) Pthreads does not include a semaphore and is emulated with a mutex and condition variable.

(6) SGI Irix does not include an event object and is emulated with ordinary process signals and the sigtimedwait and kill system calls.

(7) Nsthread events are emulated with pthread condition variables.

(10) Critical sections are emulated with a mutex and a condition variable.

(11) Thread local storage is not available on SGI sproc and is emulated using the PRDA, the process data area, as defined in the sys/prcnt.h header.

Tcl Interpreter Functions

The following functions are used to manipulate Tcl interpreters.

Ns_GetConnInterp

Get the Tcl interpreter for the connection

Ns_TclAllocateInterp

Allocate a Tcl interpreter for a server

Ns_TclDeAllocateInterp

Perform cleanup after deallocating a Tcl interpreter

Ns_TclDestroyInterp

Mark Tcl interpreter for deletion

Ns_TclInitInterps

Call a Tcl init procedure in the parent interpreter

Ns_TclInterpServer

Return name of server

Ns_TclMarkForDelete

Mark Tcl interpreter for deletion

Miscellaneous Functions

The following are miscellaneous utility functions in the AOLserver C API.

Ns_AdjTime

Adjust Ns_Time

Ns_Asctime

Perform asctime_r

Ns_CloseOnExec

Set close-on-exec flag

Ns_Ctime

Perform ctime_r

Ns_DiffTime

Get difference between two times

Ns_DupHigh

Move file descriptors

Ns_Encrypt

Encrypt a password in the form used by the Unix /etc/passwd file and the nsperm module.

Ns_ExecArgblk

Execute file with argument string

Ns_ExecArgv

Execute file with argument array

Ns_ExecProc

Execute file with argument array

Ns_ExecProcess

Execute file with argument string

Ns_FetchPage

Copy data from URL to dynamic string

Ns_FetchURL

Fetch a remote URL.

Ns_GetHostByAddr

Convert an IP address to a hostname

Ns_GetTime

Perform gettimeofday

Ns_GetUid

Return UID of user

Ns_GetUserHome

Get Unix user's home directory

Ns_Gmtime

Perform gmtime

Ns_HttpTime

Return a formatted time string

Ns_HtuuDecode

Perform base64 decode

Ns_HtuuEncode

Perform base64 encode

Ns_IncrTime

Increment time by seconds and microseconds

Ns_InetNtoa

Perform inet_ntoa

Ns_InfoBootTime

Return server boot time

Ns_InfoBuildDate

Return AOLserver build date

Ns_InfoConfigFile

Return full path name of the configuration file in use.

Ns_InfoErrorLog

Return error log name

Ns_InfoHomePath

Return directory where the AOLserver is installed.

Ns_InfoHostname

Return hostname of server

Ns_InfoLabel

Return source code label of server

Ns_InfoPid

Return server pid

Ns_InfoPlatform

Return platform

Ns_InfoServerName

Return AOLserver name string ("AOLserver").

Ns_InfoServersStarted

Determine if server has started

Ns_InfoServerVersion

Return AOLserver version string.

Ns_InfoShutdownPending

Determine if a server shutdown is pending

Ns_InfoStarted

Determine if server has started

Ns_InfoUptime

Return time server has been running

Ns_LibPath

Construct path relative to lib

Ns_Localtime

Perform localtime

Ns_Match

Compare two strings

Ns_ModuleLoad

Load a module into AOLserver

Ns_ModuleSymbol

Return symbol

Ns_NextWord

Find next word in string

Ns_PageRoot

Return path name of the AOLserver pages directory for a server.

Ns_ParseHeader

Parse Http headers

Ns_ParseHttpTime

Convert Http time into time_t

Ns_ParseUrl

Parse a URL

Ns_QuoteHtml

Quote an HTML string

Ns_Readdir

Perform readdir

Ns_Sigmask

Perform sigprocmask

Ns_Signal

Install signal handler

Ns_Sigwait

Perform sigwait

Ns_StrCaseFind

Perform strstr

Ns_StrToLower

Lowercase string

Ns_StrToUpper

Uppercase string

Ns_StrTrim

Trim string

Ns_StrTrimLeft

Trim blanks from left

Ns_StrTrimRight

Trim blanks from right

Ns_StringPrint

Print string

Ns_Strtok

Perform strtok_r

Ns_TclEval

Execute a Tcl script

Ns_TclGetConn

Get connection

Ns_TclGetOpenChannel

Get open channel in interpreter

Ns_TclGetOpenFd

Get open file descriptor

Ns_TclInitModule

Source Tcl module before server startup

Ns_TclLibrary

Return private Tcl directory

Ns_TclLogError

Write errorInfo to the log file

Ns_TclAppendInt

Append integer to Tcl result

Ns_TclRegisterAtCreate

Register function for interpreter creation

Ns_TclRegisterDeferred

Register function for interpreter cleanup

Database Functions

The AOLserver provides several functions for accessing the database. These include convenient routines for sending DML and DDL SQL statements or SQL statements that return rows from the database. (DML stands for Data Manipulation Language and includes SQL statements to insert, update, and delete data. DDL stands for Data Definition Language and includes SQL statements to create tables and views.)

There are also powerful catalog functions that help you build custom responses based on the schema of the tables within the database. These functions are only available if the nsdb module is loaded.

The following groups of database functions are described in the following subsections.

Pool Functions

Functions used to obtain information about database pools and obtain handles to database pools.

SQL Query Functions

Functions used to send queries to the database and process the results

Stored Procedure Functions

Functions used to run stored procedures.

Miscellaneous Functions

Miscellaneous functions associated with the database.

Pool Functions

The functions in this category are listed in the following table.

Ns_DbBouncePool

Mark all database handles stale

Ns_DbPoolAllowable

Determine if pool is available

Ns_DbPoolDefault

Get default pool

Ns_DbPoolDescription

Get pool description

Ns_DbPoolGetHandle

Get database handle from pool

Ns_DbPoolGetMultipleHandles

Get multiple database handles from pool

Ns_DbPoolList

Get a list of available pools for a server

Ns_DbPoolPutHandle

Release a database handle for a pool

Ns_DbPoolTimedGetHandle

Get database handle from pool with timeout

Ns_DbPoolTimedGetMultipleHandles

Get multiple database handles from pool with timeout

SQL Query Functions

The AOLserver C Database API includes the following functions for sending queries to the database and processing the results. Rows are returned as Ns_Set structures described earlier.

Ns_Db0or1Row

Execute an SQL statement that must return <= 1 row

Ns_Db1Row

Execute an SQL statement that must return one row

Ns_DbBindRow

Return an Ns_Set structure of columns returned by the previously-executed SQL command

Ns_DbCancel

Cancel an active SQL select statement

Ns_DbDML

Execute an SQL DML statement

Ns_DbExec

Execute an SQL command

Ns_DbFlush

Flush any waiting rows

Ns_DbGetRow

Fetch the next waiting row after an Ns_DbSelect

Ns_DbInterpretSqlFile

Parse DML statements and send to database

Ns_DbSelect

Send a row-generating query to the database

Stored Procedure Functions

The following functions handle stored procedures.

Ns_DbSpExec

Run a stored procedure

Ns_DbSpGetParams

Get output parameters from stored procedure

Ns_DbSpReturnCode

Get return code from stored procedure

Ns_DbSpSetParam

Set input parameter for stored procedure

Ns_DbSpStart

Start execution of a stored procedure

Miscellaneous Functions

The following functions provide additional ways to manipulate the database.

Ns_DbDriverDbType

Get database type

Ns_DbDriverName

Get driver for database

Ns_DbQuoteValue

Adds extra single quote to single quotes in string

Ns_DbRegisterDriver

Register database driver with the server

Ns_DbSetException

Set last error message for database

Top of Page

[ Previous ] [ Contents ] [ Index ] [ Next ]
Copyright © 1998-99 America Online, Inc.