Sun Java System Web Server 6.1 SP7 NSAPI Programmer's Guide

Chapter 3 Creating Custom SAFs

This chapter describes how to write your own NSAPI plug-ins that define custom Server Application Functions (SAFs). Creating plug-ins allows you to modify or extend the Sun Java System Web Server’s built-in functionality. For example, you can modify the server to handle user authorization in a special way or generate dynamic HTML pages based on information in a database.

This chapter has the following sections:

Future Compatibility Issues

The NSAPI interface may change in a future version of Sun Java System Web Server. To keep your custom plug-ns upgradable, do the following:

The SAF Interface

All SAFs (custom and built-in) have the same C interface regardless of the request-handling step for which they are written. They are small functions designed for a specific purpose within a specific request-response step. They receive parameters from the directive that invokes them in the obj.conf file, from the server, and from previous SAFs.

Here is the C interface for a SAF:

int function(pblock *pb, Session *sn, Request *rq);

The next section discusses the parameters in detail.

The SAF returns a result code that indicates whether and how it succeeded. The server uses the result code from each function to determine how to proceed with processing the request. See Result Codes for details of the result codes.

SAF Parameters

This section discusses the SAF parameters in detail. The parameters are:

pb (parameter block)

The pb parameter is a pointer to a pblock data structure that contains values specified by the directive that invokes the SAF. A pblock data structure contains a series of name-value pairs.

For example, a directive that invokes the basic-nsca function might look like:

AuthTrans fn=basic-ncsa auth-type=basic dbm=/sun/server61/userdb/rs


In this case, the pb parameter passed to basic-ncsa contains name-value pairs that correspond to auth-type=basic and dbm=/Sun/WebServer61/server1/userdb/rs.

NSAPI provides a set of functions for working with pblock data structures. For example, pblock_findval() returns the value for a given name in a pblock. See Parameter Block Manipulation Routines working with parameter blocks.

sn (session)

The sn parameter is a pointer to a session data structure. This parameter contains variables related to an entire session (that is, the time between the opening and closing of the TCP/IP connection between the client and the server). The same sn pointer is passed to each SAF called within each request for an entire session. The following list describes the most important fields in this data structure (seeChapter 7, NSAPI Function Reference NSAPI routines for manipulating the session data structure).

rq (request)

The rq parameter is a pointer to a request data structure. This parameter contains variables related to the current request, such as the request headers, URI, and local file system path. The same request pointer is passed to each SAF called in the request-response process for an HTTP request.

The following list describes the most important fields in this data structure (see Chapter 7, NSAPI Function Reference for information about NSAPI routines for manipulating the request data structure).

Result Codes

Upon completion, a SAF returns a result code. The result code indicates what the server should do next. The result codes are:

Creating and Using Custom SAFs

Custom SAFs are functions in shared libraries that are loaded and called by the server.

ProcedureTo create a custom SAF

  1. Write the Source Code using the NSAPI functions. Each SAF is written for a specific directive.

  2. Compile and Link the source code to create a shared library ( .so , .sl , or .dll) file.

  3. Load and Initialize the SAF by editing the magnus.conf file to:

    • Load the shared library file containing your custom SAF(s)

      • Initialize the SAF if necessary

  4. Instruct the Server to Call the SAFs by editing obj.conf to call your custom SAF(s) at the appropriate time.

  5. Restart the Server .

  6. Test the SAF by accessing your server from a browser with a URL that triggers your function.

    The following sections describe these steps in greater detail.

Write the Source Code

Write your custom SAFs using NSAPI functions. For a summary of some of the most commonly used NSAPI functions, see Overview of NSAPI C Functions available routines, see Chapter 7, NSAPI Function Reference

For examples of custom SAFs, see nsapi/examples/ in the server root directory, and also seeChapter 5, Examples of Custom SAFs and Filters

The signature for all SAFs is:

int function(pblock *pb, Session *sn, Request *rq);

For more details on the parameters, seeSAF Parameters

The Sun Java System Web Server runs as a multi-threaded single process. On UNIX platforms there are actually two processes (a parent and a child), for historical reasons. The parent process performs some initialization and forks the child process. The child process performs further initialization and handles all of the HTTP requests.

Keep the following in mind when writing your SAF:

Compile and Link

Compile and link your code with the native compiler for the target platform. For UNIX, use the gmake command. For Windows, use the nmake command. For Windows, use Microsoft Visual C++ 6.0 or newer. You must have an import list that specifies all global variables and functions to access from the server binary. Use the correct compiler and linker flags for your platform. Refer to the example Makefile in the server_root/plugins/nsapi/examples directory.

Adhere to the following guidelines for compiling and linking.

Include Directory and nsapi.h File

Add the server_root/plugins/include (UNIX) or server_root\plugins\include (Windows) directory to your makefile to include the nsapi.h file.


Add the server_root/bin/https/lib (UNIX) or server_root\bin\https\bin (Windows) library directory to your linker command.

The following table lists the library that you need to link to.

Table 3–1 Libraries




ns-httpd40.dll (in addition to the standard Windows libraries)


All other UNIX platforms

Linker Commands and Options for Generating a Shared Object

To generate a shared library, use the commands and options listed in the following table.

Table 3–2 Linker Commands and Options



Solaris™ Operating System (SPARC® Platform Edition) 

ld -G or cc -G


link -LD


cc +Z -b -Wl,+s -Wl,-B,symbolic


cc -p 0 -berok -blibpath:$(LD_RPATH)


cc -shared


gcc -shared


cc -shared

Additional Linker Flags

Use the linker flags in the following table to specify which directories should be searched for shared objects during runtime to resolve symbols.

Table 3–3 Linker Flags



Solaris SPARC 

-R dir:dir


(no flags, but the ns-httpd40.dll file must be in the system PATH variable)






-rpath dir:dir





On UNIX, you can also set the library search path using the LD_LIBRARY_PATH environment variable, which must be set when you start the server.

Compiler Flags

The following table lists the flags and defines you need to use for compilation of your source code.

Table 3–4 Compiler Flags and Defines



Solaris SPARC 













-o32 -exceptions -DXP_UNIX -KPIC

All platforms 


The following table lists the optional flags and defines you can use.

Table 3–5 Optional Flags and Defines






Needed for the proxy utilities function include file putil.h

Compiling 3.x Plugins on AIX

For AIX only, plug-ins built for 3.x versions of the server must be relinked to work with 4.x and 6.x versions. The files you need, which are in the server_root/plugins/nsapi/examples/ directory, are as follows:

Load and Initialize the SAF

For each shared library (plug-in) containing custom SAFs to be loaded into the Sun Java System Web Server, add an Init directive that invokes the load-modules SAF to magnus.conf.

The syntax for a directive that calls load-modules is:

Init fn=load-modules shlib=[path]sharedlibname funcs="SAF1,...,SAFn"

Init fn=load-modules 

If necessary, also add an Init directive that calls the initialization function for the newly loaded plug-in. For example, if you defined the function init_my_new_SAF() to perform an operation on the maxAnimLoop parameter, you would add a directive such as the following to magnus.conf:

Init fn=init_my_animations maxAnimLoop=5

Instruct the Server to Call the SAFs

Next, add directives to obj.conf to instruct the server to call each custom SAF at the appropriate time. The syntax for directives is:

Directive fn=function-name [name1="value1"]...[nameN="valueN"]

NameTrans fn=pfx2dir from="/animations/small"
dir="D:/Sun/WebServer61/server1/docs/animations/small" name="small_anim"
NameTrans fn=pfx2dir from="/animations/fullscreen"


You also need to define objects that contain the Service directives that run the animations and specify the speed parameter.

<Object name="small_anim">
Service fn=do_small_anim speed=40
<Object name="fullscreen_anim">
Service fn=do_big_anim speed=20


Restart the Server

After modifying obj.conf, you need to restart the server. A restart is required for all plug-ins that implement SAFs and/or filters.

Test the SAF

Test your SAF by accessing your server from a browser with a URL that triggers your function. For example, if your new SAF is triggered by requests to resources in http://server-name/animations/small, try requesting a valid resource that starts with that URI.

You should disable caching in your browser so that the server is sure to be accessed. In Netscape Navigator you may hold the shift key while clicking the Reload button to ensure that the cache is not used. (Note that the shift-reload trick does not always force the client to fetch images from source if the images are already in the cache.)

You may also wish to disable the server cache using the cache-init SAF.

Examine the access log and error log to help with debugging.

Overview of NSAPI C Functions

NSAPI provides a set of C functions that are used to implement SAFs. They serve several purposes. They provide platform independence across Sun Java System Web Server operating system and hardware platforms. They provide improved performance. They are thread-safe which is a requirement for SAFs. They prevent memory leaks. And they provide functionality necessary for implementing SAFs. You should always use these NSAPI routines when defining new SAFs.

This section provides an overview of the function categories available and some of the more commonly used routines. All of the public routines are detailed in Chapter 7, NSAPI Function Reference.

The main categories of NSAPI functions are:

Parameter Block Manipulation Routines

The parameter block manipulation functions provide routines for locating, adding, and removing entries in a pblock data structure:

Protocol Utilities for Service SAFs

Protocol utilities provide functionality necessary to implement Service SAFs:

Memory Management

Memory management routines provide fast, platform-independent versions of the standard memory management routines. They also prevent memory leaks by allocating from a temporary memory (called “pooled” memory) for each request, and then disposing the entire pool after each request. There are wrappers for standard memory routines for using permanent memory. To disable pooled memory for debugging, see the built-in SAF pool-init in Chapter 2, SAFs in the magnus.conf File

File I/O

The file I/O functions provide platform-independent, thread-safe file I/O routines.

Network I/O

Network I/O functions provide platform-independent, thread-safe network I/O routines. These routines work with SSL when it’s enabled.


Thread functions include functions for creating your own threads that are compatible with the server’s threads. There are also routines for critical sections and condition variables.


Utility functions include platform-independent, thread-safe versions of many standard library functions (such as string manipulation), as well as new utilities useful for NSAPI.

Note –

You cannot use an embedded null in a string, because NSAPI functions assume that a null is the end of the string. Therefore, passing unicode-encoded content through an NSAPI plug-in doesn’t work.

Virtual Server

The virtual server functions provide routines for retrieving information about virtual servers.

Required Behavior of SAFs for Each Directive

When writing a new SAF, you should define it to do certain things, depending on which stage of the request-handling process will invoke it. For example, SAFs to be invoked during the Init stage must conform to different requirements than SAFs to be invoked during the Service stage.

The rq parameter is the primary mechanism for passing along information throughout the request-response process. On input to a SAF, rq contains whatever values were inserted or modified by previously executed SAFs. On output, rq contains any modifications or additional information inserted by the SAF. Some SAFs depend on the existence of specific information provided at an earlier step in the process. For example, a PathCheck SAF retrieves values in rq->vars that were previously inserted by an AuthTrans SAF.

This section outlines the expected behavior of SAFs used at each stage in the request-handling process.

Init SAFs

AuthTrans SAFs

NameTrans SAFs

PathCheck SAFs

ObjectType SAFs

Input SAFs

Output SAFs

Service SAFs

Error SAFs

AddLog SAFs

CGI to NSAPI Conversion

You may have a need to convert a CGI variable into an SAF using NSAPI. Since the CGI environment variables are not available to NSAPI, you’ll retrieve them from the NSAPI parameter blocks. The table below indicates how each CGI environment variable can be obtained in NSAPI.

Keep in mind that your code must be thread-safe under NSAPI. You should use NSAPI functions that are thread-safe. Also, you should use the NSAPI memory management and other routines for speed and platform independence.

Table 3–6 Parameter Blocks for CGI Variables

CGI getenv()  



pblock_findval("auth-type", rq->vars);


pblock_findval("auth-user", rq->vars);


pblock_findval("content-length", rq->headers);


pblock_findval("content-type", rq->headers);




pblock_findval( "*", rq->headers); (* is lowercase; dash replaces underscore)


pblock_findval("path-info", rq->vars);


pblock_findval("path-translated", rq->vars);


pblock_findval("query", rq->reqpb); (GET only; POST puts query string in body data)


pblock_findval("ip", sn->client);


session_dns(sn) ? session_dns(sn) : pblock_findval("ip", sn->client);


pblock_findval( "from", rq->headers);(not usually available)


pblock_findval("auth-user", rq->vars);


pblock_findval("method", req->reqpb);


pblock_findval("uri", rq->reqpb);


char *util_hostname();


conf_getglobals()->Vport; (as a string)


pblock_findval("protocol", rq->reqpb);



Sun Java System-specific:



pblock_findval("auth-cert", rq->vars) ;


char *session_maxdns(sn);(may be null)


security_active ? "ON" : "OFF";


pblock_findval("keysize", sn->client);


pblock_findval("secret-keysize", sn->client);


pblock_findval( query", rq->reqpb); (GET only, POST puts query string in entity-body data)


http_uri2url_dynamic("","", sn, rq);