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.
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");
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);
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.
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);
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.
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);
}
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");
}
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.
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.
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".
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.
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.
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));
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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;
}
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.)
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
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
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).
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.
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 ...
}
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!
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_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.
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 ...
}
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.