AOLserver

# Connection and Socket C Library Functions

$Header: /cvsroot/aolserver/aolserver.com/docs/devel/c/index.html,v 1.1 2002/03/07 19:15:35 kriston Exp $

## Ns_BindSock

Bind socket as root

### Syntax

        int Ns_BindSock (
        struct sockaddr_in* saPtr
        );

### Description

Bind a socket as root. This function can only be called before server startup.

## Ns_ConnAuthPasswd

Return password

### Syntax

        char *Ns_ConnAuthPasswd(
        Ns_Conn *conn
        );

### Description

The Ns_ConnAuthPasswd function returns the decoded password from the header information associated with the connection.

### Examples

        /* PassTrace - A server trace to log users and passwords. */
        void
        PassTrace(void *ctx, Ns_Conn *conn)
        {
            char *user;
            char *pass;

            user = Ns_ConnAuthUser(conn);
            pass = Ns_ConnAuthPasswd(conn);
            if (user != NULL && pass != NULL) {
                    Ns_Log(Notice, "User: %s Password: %s", user, pass);
            }
        }

## Ns_ConnAuthUser

Return user name

### Syntax

        char *Ns_ConnAuthUser(
        Ns_Conn *conn
        );

### Description

The Ns_ConnAuthUser function returns the decoded user name from the header information associated with the connection.

### Examples

       See the example for Ns_ConnAuthPasswd.

## Ns_ConnClose

Close a connection

### Syntax

        int Ns_ConnClose(
        Ns_Conn *conn
        );

### Description

The Ns_ConnClose function closes a connection. The semantics of this call are specific to the driver associated with the connection. In the case of a socket driver (the nssock module), this function will cause the socket associated with the connection to be closed. Ns_ConnClose returns a status of NS_OK or NS_ERROR.

This function is called by AOLserver before running any registered traces. You do not normally need to call it.

## Ns_ConnCondSetHeaders

Set the value for a header field conditionally

### Syntax

        void Ns_ConnCondSetHeaders(
        Ns_Conn *conn,
        char *field,
        char *value
        );

### Description

The Ns_ConnCondSetHeaders function sets the value of a field if and only if the field/value pair does not already exist. The search for an existing field is not case sensitive.

### Examples

            /* Set a Cookie header if not already set. */
            Ns_ConnCondSetHeaders(conn, "Cookie", "randomStuff");

## Ns_ConnConstructHeaders

Put HTTP header into DString

### Syntax

        void Ns_ConnConstructHeaders(
        Ns_Conn *conn,
        Ns_DString *dsPtr
        );

### Description

Put the header of an HTTP response into the DString. Content-Length and Connection-Keepalive headers will be added if possible.

## Ns_ConnContentLength

Return content length

### Syntax

        int Ns_ConnContentLength(
        Ns_Conn *conn
        );

### Description

The Ns_ConnContentLength function returns the number of bytes in the content associated with the connection.

### Examples

            /* Copy the content from the browser to a DString. */
            Ns_DString ds;
            int len;

            Ns_DStringInit(&ds);
            len = Ns_ConnContentLength(conn);
            Ns_ConnCopyToDString(conn, len, &ds);

## Ns_ConnContentSent

Check if browser sent content

### Syntax

        int Ns_ConnContentSent (
        Ns_Conn* conn
        );

### Description

Returns TRUE if the browser sent any content, such as in a PUT request. Returns FALSE otherwise.

## Ns_ConnCopyToChannel

Copy content to Tcl channel

### Syntax

        int Ns_ConnCopyToChannel (
        Ns_Conn* conn,
        size_t iToCopy,
        Tcl_Channel chan
        );

### Description

Copy content, such as in a PUT request, from the connection into an open Tcl channel. iToCopy bytes will be copied.

## Ns_ConnCopyToDString

Copy data from connection to dynamic string

### Syntax

        int Ns_ConnCopyToDString(
        Ns_Conn *conn,
        size_t iToCopy,
        Ns_DString *pds
        );

### Description

The Ns_ConnCopyToDString function copies iToCopy bytes of data from the connection to the Ns_DString pointed to by pds. Ns_ConnCopyToDString returns a status of NS_OK or NS_ERROR.

### Examples

       See the example for Ns_ConnContentLength.

## Ns_ConnCopyToFd

Copy content to file descriptor

### Syntax

        int Ns_ConnCopyToFd (
        Ns_Conn* conn,
        size_t iToCopy,
        int fd
        );

### Description

Copy content, such as in a PUT request, from the connection into an open file descriptor. iToCopy bytes will be copied.

## Ns_ConnCopyToFile

Copy data from connection to a file

### Syntax

        int Ns_ConnCopyToFile(
        Ns_Conn *conn,
        size_t iToCopy,
        FILE *fp
        );

### Description

The Ns_ConnCopyToFile function copies iToCopy bytes of data from the connection to the file pointed to by fp. Ns_ConnCopyToFile returns a status of NS_OK or NS_ERROR.

### Examples

            /* Copy the content from the browser to a file. */
            FILE *fp;
            int len;

            fp = fopen("content.out", "w");
            len = Ns_ConnContentLength(conn);
            Ns_ConnCopyToFile(conn, len, fp);
            fclose(fp);

## Ns_ConnDriverContext

Return driver context

### Syntax

        void *Ns_ConnDriverContext(
        Ns_Conn *conn
        );

### Description

The Ns_ConnDriverContext function returns a pointer to the communications driver context associated with the connection. This context is set in the Ns_QueueConn function. This function exists primarily for AOLserver communications driver developers.

## Ns_ConnDriverName

Return driver name

### Syntax

        char *Ns_ConnDriverName(
        Ns_Conn *conn
        );

### Description

The Ns_ConnDriverName function returns the communications driver name associated with the connection.

## Ns_ConnFlushContent

Flush remaining content

### Syntax

        int Ns_ConnFlushContent (
        Ns_Conn* conn
        );

### Description

Read all remaining content sent by the browser, for example in a PUT request, and throw it away.

## Ns_ConnFlushHeaders

Mark the end of the headers

### Syntax

        int Ns_ConnFlushHeaders(
        Ns_Conn *conn,
        int status
        );

### Description

The Ns_ConnFlushHeaders functions returns a single blank line that signifies the end of the headers. It also sets the state of the connection from header buffering mode to immediate sending of data to the client. Before this function is called, any headers are not actually sent to the client but instead are buffered in the Ns_Conn structure to avoid the cost of sending the headers in individual network packets.

The status is a standard error code such as 403 for access denied or 200 for OK. Returns NS_OK or NS_ERROR.

This function is normally required just before sending content to the client.

### Examples

        /* A simple Hello request function. */
        int
        MyHello(Ns_Conn *conn, void *ctx)
        {
            char hello[] = "hello";
            int len;

            len = strlen(hello);
            Ns_ConnSetRequiredHeaders(conn, "text/plain", len);
            Ns_ConnFlushHeaders(conn, 200);
            return Ns_ConnWrite(conn, hello, len);
        }

## Ns_ConnGetQuery

Construct Ns_Set representing query data

### Syntax

        Ns_Set *Ns_ConnGetQuery(
        Ns_Conn *conn
        );

### Description

The Ns_ConnGetQuery function constructs and returns an Ns_Set structure representing the query data associated with the connection. It reads the POST content or the query string. The POST content takes precedence over the query string.

Note that you must not call Ns_SetFree on the result of this function.

### Examples

            /* Get the value from an  form tag. */
            Ns_Set *set;
            char *value;

            set = Ns_ConnGetQuery(conn);
            if (set != NULL) {
                    value = Ns_SetGetValue(set, "mydata");
            }

## Ns_ConnGets

Read content into a buffer

### Syntax

        char *Ns_ConnGets(
        char *buf,
        size_t sz,
        Ns_Conn *conn
        );

### Description

The Ns_ConnGets function reads sz bytes of a single line (until newline/cr) from the connection into the buffer specified by buf. Ns_ConnGets returns buf or, in the case of a read error, NULL.

## Ns_ConnHeaders

Return headers

### Syntax

        Ns_Set *Ns_ConnHeaders(
        Ns_Conn *conn
        );

### Description

The Ns_ConnHeaders function returns, as an Ns_Set, the headers associated with the connection.

### Examples

            /* Log the Referer header. */
            Ns_Set *headers;
            char *refer;

            headers = Ns_ConnHeaders(conn);
            if (headers != NULL) {
                    refer = Ns_SetGet(headers, "Referer");
                    if (refer != NULL) {
                            Ns_Log(Notice, "Referer: %s", refer);
                    }
            }

## Ns_ConnHost

Return host

### Syntax

        char *Ns_ConnHost(
        Ns_Conn *conn
        );

### Description

The Ns_ConnHost function returns the server hostname associated with the connection.

## Ns_ConnInit

Run socket init procedure

### Syntax

        int Ns_ConnInit (
        Ns_Conn* connPtr
        );

### Description

Run a socket driver's init procedure. This function is usually only called internally.

## Ns_ConnLocation

Return location

### Syntax

        char *Ns_ConnLocation(
        Ns_Conn *conn
        );

### Description

The Ns_ConnLocation function returns the HTTP location associated with the connection. For example: http://www.avalon.com:81.

Multiple communications drivers can be loaded into a single server. This means a server may have more than one location. For example, if the nsssl module is loaded and bound to port 8000 and the nssock module is loaded and bound to port 9000, the server would have the following two locations: http://www.avalon.com:9000 https://www.avalon.com:8000 For this reason it is important to use the Ns_ConnLocation function to determine the driver location at run time.

## Ns_ConnModifiedSince

Determine if content modified since a specified date

### Syntax

        int Ns_ConnModifiedSince(
        Ns_Conn *conn,
        time_t mtime
        );

### Description

The Ns_ConnModifiedSince function returns 1 if the content associated with the connection has been modified since mtime. It uses the HTTP header variable "If-Modified-Since".

## Ns_ConnOutputHeaders

Get Ns_Set of headers to send to client

### Syntax

        Ns_Set * Ns_ConnOutputHeaders(
        Ns_Conn *conn
        );

### Description

Get a writeable Ns_Set containing headers to send back to the client.

## Ns_ConnPeer

Return name of peer

### Syntax

        char *Ns_ConnPeer(
        Ns_Conn *conn
        );

### Description

The Ns_ConnPeer function returns the name of the peer associated with the connection.

The peer address is determined by the communications driver in use by the connection. Typically it is a dotted IP address, for example, 199.221.53.205, but this is not guaranteed.

## Ns_ConnPeerPort

Return peer port

### Syntax

        int Ns_ConnPeerPort (
        Ns_Conn* conn
        );

### Description

Returns the port from which the peer is connected.

## Ns_ConnPort

Return port

### Syntax

        int Ns_ConnPort(
        Ns_Conn *conn
        );

### Description

The Ns_ConnPort function returns the server port number associated with the connection.

## Ns_ConnPrintfHeader

Return a formatted header

### Syntax

        int Ns_ConnPrintfHeader(
        Ns_Conn *conn,
        char *fmt,
        ...
        );

### Description

The Ns_ConnPrintfHeader function constructs a formatted string using the given format specification and any optional arguments. It then appends the necessary line feed and carriage return characters and sends the header to the client.

## Ns_ConnPuts

Send a string to a client

### Syntax

        int Ns_ConnPuts(
        Ns_Conn *conn,
        char *string
        );

### Description

The Ns_ConnPuts function sends the given string to the client. It returns NS_OK on success and NS_ERROR on failure.

## Ns_ConnRead

Read content into buffer

### Syntax

        int Ns_ConnRead(
        Ns_Conn *conn,
        void *pvBuf,
        int iToRead
        );

### Description

The Ns_ConnRead function reads iToRead bytes from the connection into pvBuf. Ns_ConnRead returns the status NS_ERROR or the number of bytes read from the connection.

### Examples

        /* Read content from the browser into buf. */
        char buf[1024];

        Ns_ConnRead(conn, buf, sizeof(buf));

## Ns_ConnReadHeaders

Read headers into Ns_Set

### Syntax

        int Ns_ConnReadHeaders (
        Ns_Conn* conn,
        Ns_Set* psetHeaders,
        int* iRead
        );

### Description

Read headers from the conn and put them into the passed-in set.

## Ns_ConnReadLine

Read a line from a connection

### Syntax

        int Ns_ConnReadLine(
        Ns_Conn *conn,
        Ns_DString *pdsLine,
        int* *iRead
        );

### Description

The Ns_ConnReadLine function reads an \n or \r terminated line from the connection into the Ns_DString pointed to by pdsLine. The iRead argument will contain the number of bytes read. Ns_ConnReadLine returns a status of NS_OK or NS_ERROR.

## Ns_ConnRedirect

Perform internal redirect

### Syntax

        int Ns_ConnRedirect (
        Ns_Conn* conn,
        char* url
        );

### Description

Perform an internal redirect, i.e., make it appear that the user requested a different URL and then run that request. This doesn't require an additional thread.

## Ns_ConnReplaceHeaders

Replace output headers for connection

### Syntax

        void Ns_ConnReplaceHeaders(
        Ns_Conn *conn,
        Ns_Set *newheaders
        );

### Description

The Ns_ConnReplaceHeaders function sets the current output headers for the connection to the newheaders set. It copies the newheaders set and frees memory associated with the old output headers in the connection.

## Ns_ConnResponseLength

Return response length

### Syntax

        int Ns_ConnResponseLength(
        Ns_Conn *conn
        );

### Description

The Ns_ConnResponseStatus function returns the response length associated with the connection. This value is only meaningful after a response has been returned to the client. This function will normally be used in trace functions. See Ns_RegisterTrace for more information about traces.

## Ns_ConnResponseStatus

Return response status

### Syntax

        int Ns_ConnResponseStatus(
        Ns_Conn *conn
        );

### Description

The Ns_ConnResponseStatus function returns the response status associated with the connection. This value is only meaningful after a response has been returned to the client. This function will normally be used in trace functions. See Ns_RegisterTrace for more information about traces.

## Ns_ConnReturnAdminNotice

Return a short notice to a client to contact system administrator

### Syntax

        void Ns_ConnReturnAdminNotice(
        Ns_Conn *conn,
        int status,
        char *notice,
        char *html
        );

### Description

The Ns_ConnReturnAdminNotice function returns to a client a simple HTML page with the given notice as the title of the page. It also appends a message directing users to contact the system administrator or web master if specified in the configuration file. The page includes the /NS/Asset/notice.gif image at the top of the page. If the html parameter is not NULL, it is added to the page after the notice. The HTML source can be arbitrarily long and should not contain the
or
begin or end tags; these tags will be added by Ns_ConnReturnAdminNotice. Ns_ConnReturnAdminNotice returns a status of NS_OK or NS_ERROR.

## Ns_ConnReturnBadRequest

Return an "invalid request" HTTP status line.

### Syntax

        int Ns_ConnReturnBadRequest(
        Ns_Conn *conn,
        char *reason
        );

### Description

Calls Ns_ConnReturnStatus or Ns_ConnReturnNotice with a status code of 400 to indicate that the request was invalid.

## Ns_ConnReturnData

Return an HTML string to a client

### Syntax

        EXTERN int Ns_ConnReturnData(
        Ns_Conn *conn,
        int status,
        char *html,
        int len,
        char *type
        );

### Description

The Ns_ConnReturnData function calls the Ns_ConnSetRequiredHeaders function with the given status followed by the given HTML string. The length is used to generate the Content-Length header. If the length is -1, the function calculates the Content-Length from the string. The type is used to generate the Content-Type header. Ns_ConnReturnData returns a status of NS_OK or NS_ERROR.

## Ns_ConnReturnFile

Return a file to a client

### Syntax

        int Ns_ConnReturnFile(
        Ns_Conn *conn,
        int status,
        char *type,
        char *file
        );

### Description

The Ns_ConnReturnFile function returns the entire contents of the given file to the client. In addition to setting the HTTP status response line and Content-Type headers from the given parameters, Ns_ConnReturnFile also uses the stat system call to generate the appropriate Last-Modified and Content-Length headers. Ns_ConnReturnFile returns a status of NS_OK or NS_ERROR.

## Ns_ConnReturnForbidden

Return a "request forbidden" HTTP status line.

### Syntax

        int Ns_ConnReturnForbidden(
        Ns_Conn *conn
        );

### Description

Calls Ns_ConnReturnStatus or Ns_ConnReturnNotice with a status code of 403 to indicate that the request is forbidden. There is no Authorization header that will authorize access from this IP address.

## Ns_ConnReturnHtml

Return an HTML string to a client

### Syntax

        int Ns_ConnReturnHtml(
        Ns_Conn *conn,
        int status,
        char *html,
        int len
        );

### Description

The Ns_ConnReturnHtml function calls the Ns_ConnSetRequiredHeaders function with the given status followed by the given HTML string. The length is used to generate the Content-Length header. If the length is -1, the function calculates the Content-Length from the string. Ns_ConnReturnHtml returns a status of NS_OK or NS_ERROR.

## Ns_ConnReturnInternalError

Return an "internal error" HTTP status line.

### Syntax

        int Ns_ConnReturnInternalError(
        Ns_Conn *conn
        );

### Description

Calls Ns_ConnReturnStatus or Ns_ConnReturnNotice with a status code of 500 to indicate that an internal error occurred.

## Ns_ConnReturnNoResponse

Return a "no response" HTTP status line.

### Syntax

        int Ns_ConnReturnNoResponse(
        Ns_Conn *conn
        );

### Description

Calls Ns_ConnReturnStatus or Ns_ConnReturnNotice with a status code of 204 to indicate that the request requires no response.

## Ns_ConnReturnNotFound

Return a "not found" HTTP status line.

### Syntax

        int Ns_ConnReturnNotFound(
        Ns_Conn *conn
        );

### Description

Calls Ns_ConnReturnStatus or Ns_ConnReturnNotice with a status code of 404 to indicate that the requested URL was not found on the server.

## Ns_ConnReturnNotice

Return a short notice to a client

### Syntax

        int Ns_ConnReturnNotice(
        Ns_Conn *conn,
        int status,
        char *notice,
        char *html
        );

### Description

The Ns_ConnReturnNotice function returns to a client a simple HTML page with the given notice as the title of the page. The page includes the /NS/Asset/notice.gif image at the top of the page. If the html parameter is not NULL, it is added to the page after the notice. The HTML source can be arbitrarily long and should not contain the
or
begin or end tags; these tags will be added by Ns_ConnReturnNotice. AOLserver uses Ns_ConnReturnNotice extensively, to achieve a consistent look on the pages it automatically generates. Ns_ConnReturnNotice returns a status of NS_OK or NS_ERROR.

## Ns_ConnReturnNotImplemented

Return a "not implemented" HTTP status line.

### Syntax

        int Ns_ConnReturnNotImplemented(
        Ns_Conn *conn
        );

### Description

Calls Ns_ConnReturnStatus or Ns_ConnReturnNotice with a status code of 500 to indicate that the request has not been implemented by the server.

## Ns_ConnReturnNotModified

Return a "not modified" HTTP status line.

### Syntax

        int Ns_ConnReturnNotModified(
        Ns_Conn *conn
        );

### Description

Calls Ns_ConnReturnStatus or Ns_ConnReturnNotice with a status code of 304 to indicate that the requested data have not been modified since the time specified by the If-Modified-Since header sent by the client.

## Ns_ConnReturnOk

Return an "OK" HTTP status line.

### Syntax

        int Ns_ConnReturnOk(
        Ns_Conn *conn
        );

### Description

Calls Ns_ConnReturnStatus or Ns_ConnReturnNotice with a status code of 200 to indicate that the request was successful.

## Ns_ConnReturnOpenChannel

Write channel content to conn

### Syntax

        int Ns_ConnReturnOpenChannel (
        Ns_Conn* conn,
        int status,
        char* type,
        Tcl_Channel chan,
        int len
        );

### Description

Write len bytes of an open Tcl channel out to the conn. Return HTTP status in status and Content-type in type.

## Ns_ConnReturnOpenFd

Return a file to a client

### Syntax

        int Ns_ConnReturnOpenFile(
        Ns_Conn *conn,
        int status,
        char *type,
        int fd,
        int len
        );

### Description

The Ns_ConnReturnOpenFd function is the same as Ns_ConnReturnFile except that it takes an fd argument instead of a file name, and it requires an additional length argument. It returns the entire contents of the given file to the client. Ns_ConnReturnOpenFd returns a status of NS_OK or NS_ERROR.

## Ns_ConnReturnOpenFile

Return a file to a client

### Syntax

        int Ns_ConnReturnOpenFile(
        Ns_Conn *conn,
        int status,
        char *type,
        FILE *fp,
        int len
        );

### Description

The Ns_ConnReturnOpenFile function is the same as Ns_ConnReturnFile except that it takes a FILE *fp argument instead of a file name, and it requires an additional length argument. It returns the entire contents of the given file to the client. Ns_ConnReturnOpenFile returns a status of NS_OK or NS_ERROR.

## Ns_ConnReturnRedirect

Return an HTTP redirect response to a client

### Syntax

        int Ns_ConnReturnRedirect(
        Ns_Conn *conn,
        char *location
        );

### Description

The Ns_ConnReturnRedirect function returns a properly formatted HTTP redirect message for the given location. This causes the browser to seamlessly open the new location on behalf of the user. Ns_ConnReturnRedirect returns NS_OK or NS_ERROR.

## Ns_ConnReturnStatus

Return a status message to a client

### Syntax

        int Ns_ConnReturnStatus(
        Ns_Conn *conn,
        int status
        );

### Description

The Ns_ConnReturnStatus function calls Ns_ConnSetRequiredHeaders with the given status and reason and then immediately calls Ns_ConnFlushHeaders. It can be used when only the status of the request must be returned to the client.

The status is a standard error code such as 403 for access denied or 200 for OK. Returns NS_OK or NS_ERROR.

## Ns_ConnReturnUnauthorized

Return an "unauthorized" HTTP status line.

### Syntax

        int Ns_ConnReturnUnauthorized(
        Ns_Conn *conn
        );

### Description

Calls Ns_ConnReturnStatus or Ns_ConnReturnNotice with a status code of 401 to indicate that the request did not include a valid Authorization header or the header did not specify an authorized user. The user will usually be prompted for a username/password after this status is returned.

## Ns_ConnRunRequest

Execute procedure for method and URL pattern

### Syntax

        int Ns_ConnRunRequest(
        Ns_Conn *conn
        );

### Description

Locate and execute the procedure for the given method and URL pattern (in the conn->request). Returns a standard request procedure result, normally NS_OK.

## Ns_ConnSendChannel

Send Tcl channel content to conn

### Syntax

        int Ns_ConnSendChannel (
        Ns_Conn* conn,
        Tcl_Channel chan,
        int len
        );

### Description

Read len bytes from an open Tcl channel and write it out to the conn until EOF.

## Ns_ConnSendDString

Write a DString to the conn

### Syntax

        int Ns_ConnSendDString(
        Ns_Conn *conn,
        Ns_DString *dsPtr
        );

### Description

Write out a DString to the conn.

## Ns_ConnSendFd

Write file to connection content

### Syntax

        int Ns_ConnSendFd(
        Ns_Conn *conn,
        int fd,
        int len
        );

### Description

The Ns_ConnSendFd function writes len bytes from the file pointed to by fd to the connection. Ns_ConnSendFd returns the status NS_ERROR or NS_OK.

## Ns_ConnSendFp

Write file to connection content

### Syntax

        int Ns_ConnSendFp(
        Ns_Conn *conn,
        FILE *fp,
        int len
        );

### Description

The Ns_ConnSendFp function writes len bytes from the file pointed to by fp to the connection. Ns_ConnSendFp returns the status NS_ERROR or NS_OK.

## Ns_ConnServer

Return name of server

### Syntax

        char *Ns_ConnServer(
        Ns_Conn *conn
        );

### Description

The Ns_ConnServer function returns the name of the server associated with the connection.

## Ns_ConnSetExpiresHeader

Return an "expires" header for the given time

### Syntax

        void Ns_ConnSetExpiresHeader(
        Ns_Conn *conn,
        char *httptime
        );

### Description

The Ns_ConnSetExpiresHeader formats and sends a header that will expire, using the time specified by the httptime string. You can use the Ns_HttpTime function to generate the time specification string.

## Ns_ConnSetHeaders

Set the value for a header field

### Syntax

        void Ns_ConnSetHeaders(
        Ns_Conn *conn,
        char *field,
        char *value
        );

### Description

The Ns_ConnSetHeaders function sets the value of a field in the output headers, replacing an existing field/value pair.

## Ns_ConnSetLastModifiedHeader

Return a last modified header using the given time

### Syntax

        void Ns_ConnSetLastModifiedHeader(
        Ns_Conn *conn,
        time_t *when
        );

### Description

The Ns_ConnSetLastModifiedHeader function formats and sends a Last-Modified header based on the given time. The time parameter is most often generated with the stat system call on an existing file.

## Ns_ConnSetLengthHeader

Return a Content-Length header

### Syntax

        void Ns_ConnSetLengthHeader(
        Ns_Conn *conn,
        int len
        );

### Description

The Ns_ConnSetLengthHeader function formats and sends a Content-Length header for the given length.

## Ns_ConnSetRequiredHeaders

Return the required HTTP headers

### Syntax

        void Ns_ConnSetRequiredHeaders(
        Ns_Conn *conn,
        char *contentType,
        int contentLength
        );

### Description

The Ns_ConnSetRequiredHeaders function writes the required headers of the HTTP response. If contentType is NULL, it defaults to 'text/html'. If contentLength is 0, no contentLength header will be written out.

The Ns_ConnReturnStatus function can be used to return a status-only response to the client.

## Ns_ConnSetTypeHeader

Return a Content-Type header

### Syntax

        void Ns_ConnSetTypeHeader(
        Ns_Conn *conn,
        char *type
        );

### Description

The Ns_ConnSetTypeHeader function formats and sends a Content-Type header for the given type. You can use the Ns_GuessMimeType() function to look up a Content-Type string for filename.

## Ns_ConnWrite

Send data to a client

### Syntax

        int Ns_ConnWrite(
        Ns_Conn *conn,
        void *buf,
        int len
        );

### Description

The Ns_ConnWrite function attempts to write out the specified length of data from the given buffer to the client. It returns the number of bytes sent or -1 if there is an error. This function may write fewer than len bytes.

### Examples

        /* Write towrite bytes from buf. */

        while (towrite > 0) {
            int nwrote;

            nwrote = Ns_ConnWrite(conn, buf, towrite);
            if (nwrote == -1) {
                    /* ... handle error ... */
            }
            buf += nwrote;
            towrite -= nwrote;
        }

## Ns_DriverEnableKeepalive

Enable HTTP keepalive on driver

### Syntax

        void Ns_DriverEnableKeepalive (
        Ns_Driver driver
        );

### Description

This function is used by socket drivers; it enables HTTP keepalive on the specified driver.

## Ns_GetDriver

Get socket driver

### Syntax

        Ns_Driver Ns_GetDriver (
        char* hServer,
        char* hDriver
        );

### Description

Find the socket driver of the current server and the specified driver name. (The hserver argument is ignored; it is only there for backwards compatibility.)

## Ns_GetDriverContext

Get socket driver context

### Syntax

        void* Ns_GetDriverContext (
        Ns_Driver drv
        );

### Description

Return a socket driver's context pointer, which is set when the driver is registered with Ns_RegisterDriver.

## Ns_GetDriverLabel

Get socket driver label

### Syntax

        char* Ns_GetDriverLabel (
        Ns_Driver driver
        );

### Description

Get the name of the socket driver as it appears in the configuration file. For example, the following configuration file entries would result in this function returning "mysocket": ns_section ns/server/server1/modules ns_param mysocket nsssl

## Ns_GetDriverName

Get socket driver name

### Syntax

        char* Ns_GetDriverName (
        Ns_Driver driver
        );

### Description

Get the name (for eample, `nsssl' or `nssock') of a socket driver.

## Ns_GetDriverProc

Get a communications driver procedure

### Syntax

        int Ns_GetDriverProc(
        Ns_Driver driver,
        Ns_DrvId id,
        void **pprocPtrPtr
        );

### Description

Get a communications driver procedure for the specified ID. Valid ID values are listed in the left column of the table below.

The procPtrPtr will be filled in with the address of a registerd driver function. NS_ERROR will be returned if no registered function could be found. The resulting function is of the type shown in the right column below

ID Value

Resulting Function Type

Ns_DrvIdName

typedef char *(Ns_ConnDriverNameProc) (void *pConnCtx);

Ns_DrvIdStart

typedef int (Ns_DriverStartProc) (char *hServer, char *hDriver, void **ppDriverCtx);

Ns_DrvIdAccept

typedef int (Ns_DriverAcceptProc) (void *pDriverCtx, void **ppConnCtx);

Ns_DrvIdStop

typedef void (Ns_DriverStopProc) (void *pDriverCtx);

Ns_DrvIdInit

typedef int (Ns_ConnInitProc) (void *pConnCtx);

Ns_DrvIdRead

typedef int (Ns_ConnReadProc) (void *pConnCtx, void *pvBuf, int iToRead);

Ns_DrvIdWrite

typedef int (Ns_ConnWriteProc) (void *pConnCtx, void *pvBuf, int iToWrite);

Ns_DrvIdClose

typedef int (Ns_ConnCloseProc) (void *pConnCtx);

Ns_DrvIdFree

typedef void (Ns_ConnFreeProc) (void *pConnCtx);

Ns_DrvIdPeer

typedef char *(Ns_ConnPeerProc) (void *pConnCtx);

Ns_DrvIdLocation

typedef char *(Ns_ConnLocationProc) (void *pConnCtx);

Ns_DrvIdHost

typedef char *(Ns_ConnHostProc) (void *pConnCtx);

Ns_DrvIdPort

typedef int (Ns_ConnPortProc) (void *pConnCtx);

Ns_DrvIdSendFd

typedef int (Ns_ConnSendFdProc) (void *pConnCtx, int fd, int nsend);

Ns_DrvIdSendFile

typedef int (Ns_ConnSendFileProc) (void *pConnCtx, char *file);

Ns_DrvIdDetach

typedef void *(Ns_ConnDetachProc) (void *pConnCtx);

Ns_DrvIdConnectionFd

typedef int (Ns_ConnConnectionFdProc) (void *pConnCtx);

Ns_DrvIdMoveContext

(unsupported)

Ns_DrvIdPeerPort

typedef int (Ns_ConnPeerPortProc) (void *pConnCtx);

Ns_DrvIdSetSSLAuth

typedef int (Ns_SetSSLAuthProc) (void *pCtx, Ns_SSLAuthProc *, void *ctx, Ns_FreeAuthCtxProc *);

Ns_DrvIdSSLHandshake

typedef void *(Ns_SSLHandshakeProc) (void *aCtx, int socket, char *DN, Ns_SSLAuthProc *auth, void *authctx, Ns_FreeAuthCtxProc *pFree);

:

## Ns_GetFirstDriver

Get pointer to first socket driver

### Syntax

        void* Ns_GetFirstDriver (
        char* ignored
        );

### Description

Returns a pointer to the first socket driver. Use this function with Ns_GetNextDriver.

## Ns_GetHostByAddr

Convert an IP address to a hostname

### Syntax

        int Ns_GetHostByAddr(
        Ns_DString *pds,
        char *addrStr
        );

### Description

The Ns_GetHostByAddr function converts a numeric IP address into a host name. If no name can be found, the function returns NS_FALSE; otherwise, it returns NS_TRUE. Because the response time of the Domain Name Service can be slow, this function may significantly delay the response to a client. The hostname string is appended to the specified Ns_DString (pds).

## Ns_GetNextDriver

Get pointer to next socket driver

### Syntax

        void* Ns_GetNextDriver (
        Ns_Driver driver
        );

### Description

Returns a pointer to the next socket driver. Use this function with Ns_GetFirstDriver.

## Ns_GetSockAddr

Get socket driver address

### Syntax

        int Ns_GetSockAddr (
        struct sockaddr_in* saPtr,
        char* host,
        int port
        );

### Description

Specify host and port in saPtr. Specify an IP address or a hostname for host. A NULL host means INADDR_ANY.

## Ns_QueueConn

Make and queue a new conn

### Syntax

        int Ns_QueueConn (
        Ns_Driver driver,
        void* ctx
        );

### Description

Make a new conn and put it on the list of conns to be served. This function is called by socket drivers.

## Ns_RegisterDriver

Register a socket driver

### Syntax

        Ns_Driver Ns_RegisterDriver (
        char* hServer,
        char* hDriver,
        Ns_DrvProc* procs,
        void* ctx
        );

### Description

Register a socket driver.

## Ns_RegisterLocation

Register location for socket driver

### Syntax

        int Ns_RegisterLocation (
        char* name,
        char* location,
        char* address,
        int port
        );

### Description

Register the built-in socket driver with the name of the socket driver and a location, host, and port. For example: Ns_RegisterLocation("nssock", "http://host:port/", "hostname.com", 80) After this call, the server will immediately begin serving pages from that location, host, and port.

## Ns_SockAsyncConnect

Create a remote socket and return immediately

### Syntax

        SOCKET Ns_SockAsyncConnect (
        char *host,
        int port
        );

### Description

Ns_SockAsyncConnect creates a socket connected to a remote host and port, returning immediately with the connection in progress. A select call can later be used to determine when the connection has been established.

### Examples

        SOCKET sock;
        fd_set set;
        struct timeval tv;
        sock = Ns_SockAsyncConnect("mailhost", 25);
        ... perform some other work while connection is in progress...

        ... check for connection ...
        tv.tv_sec = 2; /* allow 2 more seconds */
        tv.tv_usec = 0;
        FD_ZERO(&set);
        FD_SET(sock, &set);
        if (select(sock+1, NULL, &set, NULL, &tv) != 1) {
          ... timeout - close socket and return error...
          Ns_CloseLater(sock);
        } else {
          ... use socket ...
        }

## Ns_SockCallback

Register a socket callback function

### Syntax

        int Ns_SockCallback (
        SOCKET sock,
        Ns_SockProc *proc,
        void *ctx,
        int when
        );

### Description

Ns_SockCallback registers a user-defined socket callback function and should be called by your module at startup time. You must create a listening TCP socket (named sock). The ctx argument is your context which will be passed back as the second argument of your callback function.

The when argument is a bitmask with one or more of the following options specified:

NS_SOCK_READ:

the socket is readable

NS_SOCK_WRITE:

the socket is writeable

NS_SOCK_EXCEPTION:

the socket has an exceptional condition

NS_SOCK_EXIT:

the server is shutting down

The proc is your socket callback function in the following format: typedef int (Ns_SockProc) (int sock, void *arg, int why); The sock will be a readable, writable socket. The arg is the ctx you passed to Ns_SockCallback. The why argument is the when you passed to Ns_SockCallback.

At startup time, AOLserver creates a single socket service thread dedicated to handling socket callbacks. Since several sockets are needed to listen for connection requests, and because connection requests are handled so quickly, all the socket drivers share a single thread for that purpose.

### Examples

        1. Create a C callback function to handle a request. The callback
           function must execute without blocking so that other sockets can
           get serviced. Typically, the callback function just performs an
           accept() call and queues the request. The prototype is:
        typedef int (Ns_SockProc) (SOCKET sock, void *context, int
    why);

            The parameters are:

       sock
                 the registered socket
       context
                 your context passed to Ns_SockCallback()
       why
                 the reason the function was called, which is one of the following:
       NS_SOCK_READ: the socket is readable
       NS_SOCK_WRITE: the socket is writeable
       NS_SOCK_EXCEPTION: the socket has an exceptional condition
       NS_SOCK_EXIT: the server is shutting down

         The callback function must return either NS_TRUE to tell the
                    socket thread to keep watching the socket or NS_FALSE to
                    tell the socket thread to stop watching the socket.

            For example:

        int
        MySock(SOCKET sock, void *context, int why)
        {
              if (why == NS_SOCK_READ) {
                      .. handle read ..
                    if (error) {
                                return NS_FALSE;
                    } else {
                            return NS_TRUE;
                      }
              } else if (why == NS_SOCK_EXIT) {
                      .. free(context) ..
                      return NS_FALSE;
              }
        }
        2. At server startup time, your module must register your callback
           function with the server using the Ns_SockCallback() function.

            This example specifies that MySock will be called when the socket
                    is readable or when the server is shutting down:

        Ns_SockCallback(sock, MySock, myCtx,
            NS_SOCK_READ | NS_SOCK_EXIT);

            Remember that there is only one socket service thread, so your
                    callback function must return immediately without
                    blocking!

## Ns_SockCancelCallback

Remove a socket callback

### Syntax

        void Ns_SockCancelCallback(
        int sock
        );

### Description

Remove a callback registered on a socket.

## Ns_SockConnect

Create a socket to a remote host and port

### Syntax

        SOCKET Ns_SockConnect (
        char *host,
        int port
        );

### Description

Ns_SockConnect creates a socket connected to a remote host and port. Ns_SockConnect waits for the connection to be established before returning.

### Examples

        sock = Ns_SockConnect("mailhost", 25);
        if (sock != INVALID_SOCKET) {
         ... talk SMTP over sock ...
        }

## Ns_SockListen

Create a socket on a specified address and port

### Syntax

        SOCKET Ns_SockListen (
        char *host,
        int port
        );

### Description

Ns_SockListen creates a socket listening for connections on the specified address and port.

### Examples

        sock = Ns_SockListen("localhost", 25);
        while (1) {
           new = accept(sock, NULL, 0);
           ... communicate with client on new ...
        }

## Ns_SockListenCallback

Register a socket callback function and create socket

### Syntax

        int Ns_SockListenCallback (
        char* address,
        int port,
        Ns_SockProc* proc,
        void* ctx
        );

### Description

Ns_SockListenCallback registers a user-defined socket callback function and should be called by your module at startup time. It also creates, binds, and listens on the socket (with the specified address and port) for you.

The proc is your socket callback function. The ctx argument is your context which will be passed back as the second argument of your callback function.

The when argument is a bitmask with one or more of the following options specified:

NS_SOCK_READ:

the socket is readable

NS_SOCK_EXIT:

the server is shutting down

## Ns_SockPipe

Return a pair of connected sockets

### Syntax

        int Ns_SockPipe (
        SOCKET socks[2]
        );

### Description

Ns_SockPipe returns a pair of connected sockets. On Unix, Ns_SockPipe uses socketpair(). A socket pipe can be used for IPC between threads or as a way to wakeup a thread waiting in a select call as in the example below.

### Examples

        SOCKET sockPipe[2];
        /* Init - called at startup to create the pipe. */
        void Init(void)
        {
            Ns_SockPipe(sockPipe);
        }
        /* Wakeup - called by another thread to stop InteruptableIO in
           another thread. */

        void Wakeup(void)
        {
          send(sockPipe[1], "w", 1, 0);
        }
        /* InterruptableIO - called by a thread dedicated to reading from
           a remote host.  Reading will continue until another thread
           calls Wakeup, causing sockPipe to be readable. */

        void InteruptableIO(void)
        {
              SOCKET sock, max;
              fd_set set;
              char sig;
              sock = Ns_SockConnect("slowmachine", 6767);
              FD_ZERO(&set);
              FD_SET(sock, &set);
              FD_SET(sockPipe[0], &set);
              max = sockPipe;
              if (sock > max) {
                 max = sock;
              }
              while (1) {
                  select(max+1, &set, NULL, NULL, NULL);
                  if (FD_ISSET(sockPipe[0], &set)) {
                          /* Another thread called Wakeup().
                           * Read the signal and return. */
                          recv(sockPipe[0], &sig, 1, 0);
                          closesocket(sock);
                          return;
                  } else if (FD_ISSET(sock, &set)) {
                          recv(sock, buf, sizeof(buf), 0);
                          ... process buf ...
                  }
              }
        }

       Note: Interruptable I/O typically makes use of the alarm() system call
       on Unix. The method above, used throughout AOLserver, works on all
       platforms and avoids the alarm system call which is inappropriate for
       a multithreaded application.

## Ns_SockPortBound

Determine if port is bound

### Syntax

        int Ns_SockPortBound (
        int port
        );

### Description

This function returns a boolean value specifying whether the specified port is already bound. The port is a TCP port, and INADDR_ANY is assumed.

## Ns_SockSetBlocking

Set a socket in blocking mode

### Syntax

        Ns_SockSetBlocking (
        SOCKET sock
        );

### Description

Ns_SockSetBlocking sets a socket in blocking I/O mode.

## Ns_SockSetNonBlocking

Set a socket in nonblocking mode

### Syntax

        Ns_SockSetNonBlocking (
        SOCKET sock
        );

### Description

Ns_SockSetNonBlocking sets a socket in nonblocking I/O mode.

## Ns_SockTimedConnect

Create a remote socket within a specified time

### Syntax

        SOCKET Ns_SockTimedConnect (
        char *host,
        int port,
        int timeout
        );

### Description

Ns_SockTimedConnect creates a socket connected to a remote host and port, ensuring that the connection is established within the number of seconds specified by the timeout argument.

### Examples

        sock = Ns_SockTimedConnect("mailhost", 25);
        if (sock == INVALID_SOCKET) {
           ... timeout or error connecting ...
        } else {
           ... use socket ...
        }

## Ns_TclGetConn

Get connection

### Syntax

        Ns_Conn* Ns_TclGetConn (
        Tcl_Interp* interp
        );

### Description

Return the conn associated with this thread. The interp parameter is ignored and should be NULL.

## Ns_WriteConn

Send a specified length of data to the client

### Syntax

        int Ns_WriteConn(
        Ns_Conn *conn,
        char *buf,
        int len
        );

### Description

The Ns_WriteConn function performs the same function as Ns_ConnWrite, except that Ns_WriteConn guarantees to write as many bytes as are specified in len. It writes the specified length of data from the buffer to the client.