[ 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.
Server-Parsed HTML Functions Functions for registering new SHTML commands.

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 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 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_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 C API function often uses dynamically allocated strings. The Ns_DString*

structure is used for this purpose. Ns_DStrings contains a small amount of static space but will overflow to allocated memory if needed. Within the , 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_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 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 Mime 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 does not authenticate the user when world permission is allowed to a URL, this user may not be a valid user.

    char *authPasswd;

Decoded user password from the header information. Because the 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*

.

    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_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.
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.
Configuration File Functions Functions used to access the in-memory representation of the configuration file data.
Logging Functions Functions used to write information to the AOLserver log file.
Mime-Related Functions Functions used to access and manipulate Mime type information.
Scheduled Procedures Functions Functions used to schedule procedures to be run daily, weekly, or at specified intervals.
Sockets Interface Functions for managing sockets.
Storage and Retrieval Functions Functions used to store and retrieve information specific to URLs or virtual servers.
Thread Interface Functions Functions used to interact with the threads interface of AOLserver.
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_GetRequest Return the parameters of a request
Ns_RegisterAtExit Register an exit procedure.
Ns_RegisterRequest Register a function to handle HTTP requests for a method/URL combination
Ns_RegisterServerShutdown Register a shutdown procedure for a virtual server.
Ns_RegisterServerTrace Register a trace procedure for a virtual server.
Ns_RegisterShutdown Register a shutdown procedure.
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_SetRequestAuthorizeProc Set function used by Ns_AuthorizeRequest

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_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_UrlIsMiniWeb Check if a MiniWeb that corresponds to a URL exists
Ns_UrlToFile Construct the filename that corresponds to a URL
Ns_UrlToNvd Construct the MiniWeb document.nvd file 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_ConnFlushHeaders Mark the end of the headers
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_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
Ns_ReturnError (no longer supported) Return a short error 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

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_ConnCopyToDString Copy data from connection to dynamic string
Ns_ConnCopyToFile Copy data from connection to a file
Ns_ConnDriverContext Return driver context
Ns_ConnDriverName Return driver name
Ns_ConnGetQuery Construct Ns_Set representing query data
Ns_ConnGets Read content into a buffer
Ns_ConnHeaders Return headers
Ns_ConnHost Return host
Ns_ConnLocation Return location
Ns_ConnModifiedSince Determine if content modified since a specified date
Ns_ConnPeer Return name of peer
Ns_ConnPort Return port
Ns_ConnPuts Send a string to a client
Ns_ConnRead Read content into buffer
Ns_ConnReadLine Read a line from a connection
Ns_ConnResponseLength Return response length
Ns_ConnResponseStatus Return response status
Ns_ConnSendFd Write file to connection content
Ns_ConnSendFp Write file to connection content
Ns_ConnServer Return name of virtual server
Ns_ConnWrite Send data to a client

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 3 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_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

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_LogRaw Log raw data
Ns_LogTime Construct local date and time for log file
Ns_RollFile Rename a file and increment its backup number

Mime-Related Functions

The functions in this category are listed in the following table.
Ns_ServerGetMimeIcon Get pathname for file associated with MIME type
Ns_ServerGetMimeType Get the Mime type for a filename
Ns_ServerSetDefaultMimeType Set default MIME type
Ns_ServerSetNoExtensionMimeType Set "no-extension" MIME type
Ns_ServerUpdateMimeType Assign an extension to a MIME type

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

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 or the guide to "Windows Socket Services" in the Microsoft Win32 documentation.
Function Description
Ns_ClearSockErrno Clear error number for socket connection
Ns_GetSockErrno Get error number for socket connection
Ns_SetSockErrno Set error number for socket connection
Ns_SockAsyncConnect Create a remote socket and return immediately
Ns_SockCallback Register a socket callback function
Ns_SockCloseLater Close a remote socket which has not yet timed out
Ns_SockConnect Create a socket to remote host and port
Ns_SockListen Create a socket on a specified address and port
Ns_SockPipe Return a pair of connected sockets
Ns_SockSetBlocking Set a socket in blocking mode
Ns_SockSetNonBlocking Set a socket in nonblocking mode
Ns_SockStrError Return string for socket error number
Ns_SockTimedConnect Create a remote socket within a specified time

Storage and Retrieval Functions

The functions in this category are listed in the following table.
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_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

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_AllocThreadLocalStorage Allocate an ID which can store a pointer unique to each thread.
Ns_BeginDetachedThread Begin a new detached thread which does not need to be waited for.
Ns_BeginThread Begin a new thread which can be waited for.
Ns_BroadcastEvent Wake all threads blocked in Ns_WaitForEvent.
Ns_DestroyCriticalSection Destory a critical section object.
Ns_DestroyEvent Destory an event object.
Ns_DestroyMutex Destory a mutex object.
Ns_DestroySemaphore Destory a semaphore object.
Ns_EnterCriticalSection Enter a critical section of code, perhaps recursively.
Ns_GetThread Get the thread object of the current thread.
Ns_GetThreadId Get a unique integer ID for the current thread.
Ns_GetThreadLocalStorage Get the pointer at the unique ID for the current thread.
Ns_InitializeCriticalSection Initialize a critical section object.
Ns_InitializeEvent Initialize an event object.
Ns_InitializeMutex Initialize a mutex object.
Ns_InitializeSemaphore Initialize a semaphore object.
Ns_InitializeThreads Initialize the nsthreads interface.
Ns_LeaveCriticalSection Leave a critical section of codee, perhaps recursively.
Ns_LockMutex Lock a mutext object.
Ns_ReleaseSemaphore Increment a sempahore object.
Ns_SetEvent Wait no more than one thread blocked in Ns_WaitForEvent
Ns_SetThreadLocalStorage Set the pointer for the unique ID for the current thread.
Ns_SetThreadPriority Set the scheduleing priority of a thread.
Ns_SetThreadStackSize Set the stack size for new threads.
Ns_ThreadYield Put the current thread to sleep momentarily, allowing other threads to run,
Ns_TimedWaitForEvent Wait for an event to be raised or a timeout.
Ns_UnlockMutex Unlock a mutex object.
Ns_WaitForEvent Wait for an event to be raised.
Ns_WaitForSemaphore Wait for a semaphore object to be incremented above 0.
Ns_WaitForThread Wait for a thread 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 (1) SGI IRIX 5.3 (2) Win32
Threads:
Ns_BeginThread thr_create pthread_create sproc (4) _beginthread
Ns_WaitForThread thr_join pthread_join (3) waitpid WaitForSingleObject (3)
Ns_GetThreadId thr_self pthread_self getpid GetCurrentThreadId
Mutexes:
Ns_InitializeMutex mutex_int pthread_mutex_init usnewlock CreateMutex
Ns_DestroyMutex mutex_destroy pthread_mutex_des-troy usfreelock CloseHandle
Ns_LockMutex mutex_lock pthread_mutex_lock ussetlock WaitForSingleObject
Ns_UnlockMutex mutex_unlock pthread_mutex_un-lock usunsetlock ReleaseMutex
Semaphores:
Ns_InitializeSema-phore sema_int (5) usnewsema CreateSemaphore
Ns_DestroySema-phore sema_destroy (5) usfreesema CloseHandle
Ns_WaitForSema-phore sema_wait (5) uspsema WaitForSingleObject
Ns_ReleaseSema-phore sema_post (5) usvsema ReleaseSemaphore
Events:
Ns_InitializeEvent cond_int pthread_cond_init (6) CreateEvent (7)
Ns_DestroyEvent cond_destroy pthread_cond_destroy (6) CloseHandle
Ns_WaitForEvent cond_wait pthread_cond_wait sigtimedwait WaitForMultipleObjects
Ns_TimedWaitForEvent cond_timedwait pthread_cond_timed-wait sigtimedwait WaitForMultipleObjects
Ns_SetEvent cond_signal pthread_cond_signal kill SetEvent
Ns_BroadcastEvent cond_broadcast pthread_cond_broad-cast kill SetEvent
Critical Sections:
Ns_Initialize-CriticalSection (8) pthread_mutex_init (9) (10) InitializeCriticalSection
Ns_DestroyCriticalSection (8) pthread_mutex_de-stroy (10) DestroyCriticalSection
Ns_EnterCritical-Section (8) pthread_mutex_lock (10) EnterCriticalSection
Ns_LeaveCritical-Section (8) pthread_mutex_un-lock (10) LeaveCriticalSection
Ns_AllocThread-LocalStorage thr_keycreate pthread_keycreate (11) TlsAlloc
Ns_SetThreadLocalStorage thr_setspecific pthread_setspecific (11) TlsSetValue
Ns_GetThread-LocalStorage thr_getspecific pthread_getspecific (11) TlsGetValue

Notes:
(1) The pthread interface comes in two implementations: The OSF DCE implementation based on the DEC CMA Threads interface which is used in the Alpha OSF and HP/UX 9 and 10 platforms and all other pthread libraries including LinuxThreads and SGI 6.2 pthreads. The two interfaces are identical in most respects. Pthreads is also now available for Solaris 2.5. Because pthreads on Solaris offer no real improvement over the original Solaris thread interface, nsthreads will continue to use the existing library to be compatible with Solaris 2.4.

(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). The pthreads version is generally lower in overhead for servers with many virtual servers.

(3) The pthread_join and WaitForSingleObject routines would all multiple threads to wait for a single thread to exit on pthread on Win32. However, in the nsthread library, only a single thread may wait using the Ns_WaitForThread function. The pthread and Win32 platforms enforce this restriction.

(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 modeled after Solaris and pthread condition variables, not Win32 events.

(8) Critical sections, also known as resursive mutexes, are not available in Solaris threads and are emulated with a mutex and event.

(9) Critical sections on pthreads are implemented as a mutex created with the recursive mutex attribute.

(10) Critical sections are not available on SGI Irix and are emulated.

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

Miscellaneous Functions

The following are miscellaneous utility functions in the AOLserver C API.
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_FetchPage Copy data from URL to dynamic string
Ns_FetchURL Fetch a remote URL.
Ns_GetHostByAddr Convert an IP address to a hostname
Ns_GetUserHome Get Unix user's home directory
Ns_HttpTime Return a formatted time string
Ns_InfoConfigFile Return full path name of the configuration file in use.
Ns_InfoHomePath Return directory where the AOLserver is installed.
Ns_InfoServerName Return AOLserver name string ("AOLserver").
Ns_InfoServerVersion Return AOLserver version string.
Ns_ModuleLoad Load a module into AOLserver
Ns_ModuleSymbol Return symbol
Ns_PageRoot Return path name of the AOLserver pages directory for a virtual server.
Ns_QuoteHtml Quote an HTML string
Ns_ServerGetContentFileCreationMode Get file mode for new content files
Ns_ServerGetCustomErrorResponse Get Custom URL for Errors
Ns_SignalServer Shutdown AOLserver
Ns_TclDbGetHandle Get a database handle
Ns_TclDeAllocateInterp Perform cleanup after deallocating a Tcl interpreter
Ns_TclEval Execute a Tcl script
Ns_TclInitInterps Call a Tcl init procedure in the parent interpreter

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. 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
Table Functions Functions used to obtain information about the tables in the database.
Column Functions Functions used to obtain information about the columns of tables in the database.
Miscellaneous Functions Miscellaneous functions associated with the database.

Pool Functions

The functions in this category are listed in the following table.
Ns_DbPoolAllowable Determine if pool is available
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

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_DbSelect Send a row-generating query to the database

Table Functions

The following functions can be used to obtain information about the tables in the database. The functions manipulate an Ns_DbTableInfo structure. This structure should not be accessed or modified outside the list of functions and macros below. While much of this information could be obtained by querying the relevant database tables directly, the AOLserver caches this information for nearly instant lookup speeds. These functions are also portable across different database drivers.
Ns_DbFreeTableInfo Free memory associated with table information
Ns_DbGetTableInfo Get the Ns_DbTableInfo structure for a table
Ns_DbNewTableInfo Allocate structure for table information
Ns_DbTableDescription Return the description of a table
Ns_DbTableExists Determine whether table exists
Ns_DbTableList Get a list of tables in database
Ns_DbTableName Return the name of a table
Ns_DbTableValue Get arbitrary value from table information

Column Functions

The following functions can be used to obtain information about the columns of individual tables within the database. All of these functions except Ns_DbBestRowId require a pointer to an Ns_DbTableInfo structure returned by the Ns_DbGetTableInfo function.
Ns_DbAddColumnInfo Add column information to table
Ns_DbBestRowId Get a list of columns that uniquely identifies a row
Ns_DbColumnCount Return the number of columns in a table
Ns_DbColumnIndex Return the index of a column
Ns_DbColumnName Return the name of a column
Ns_DbColumnType Return the type of a column
Ns_DbColumnValue Get arbitrary value from column information

Miscellaneous Functions

The following functions provide additional ways to manipulate the database.
Ns_DbCloseDb Close a database handle
Ns_DbDriverName Get driver for database
Ns_DbDup Duplicate a database handle
Ns_DbInitialized Determine if nsdb module is initialized
Ns_DbOpenDb Obtain a database handle
Ns_DbQuoteValue Adds extra single quote to single quotes in string
Ns_DbRegisterDriver Register database driver with the server
Ns_DbReturnError Return a short database error message
Ns_DbSetException Set last error message for database

Server-Parsed HTML Functions

These functions are available only if the nsshtml module is loaded.
Function Description
Ns_RegisterShtmlCmd Register a new server-parsed HTML command.

Top of Page

[ Previous ] [ Contents ] [ Index ] [ Next ]
Copyright © 1996 America Online, Inc.