Summary of Contents for Netscape NETSCAPE ENTERPRISE SERVER 6.1 - NSAPI PROGRAMMER GUIDE
Page 1
NSAPI Programmer’s Guide Netscape Enterprise Server Version 6.1 April 2002 (Draft)
Page 2
Netscape Communications Corporation ("Netscape") and its licensors retain all ownership rights to the software programs offered by Netscape (referred to herein as "Software") and related documentation. Use of the Software and related documentation is governed by the license agreement for the Software and applicable copyright law. Your right to copy this documentation is limited by copyright law.
About This Book This book discusses how to use the Netscape® Server Application Programmer's Interface (NSAPI) to build plugins that define Server Application Functions (SAFs) to extend and modify Netscape Enterprise Server. The book also discusses the purpose and use of the configuration files obj.conf magnus.conf server.xml...
Page 16
This chapter presents a reference of the functions in the Netscape Server Application Programming Interface (API). You use NSAPI functions to define SAFs. • Chapter 6, “Examples of Custom SAFs” This chapter discusses examples of custom SAFs to use at each stage in the request handling process.
Where to Find Related Information NOTE Throughout this manual, all descriptions specific to UNIX® descriptions apply to the Linux® operating system as well, except where Linux is specifically mentioned. Where to Find Related Information Additional Enterprise Server documentation includes: • Netscape Enterprise Server Installation and Migration Guide •...
Page 18
Where to Find Related Information Netscape Enterprise Server NSAPI Programmer’s Guide • April 2002 (Draft)
Chapter 1 Basics of Server Operation The configuration and behavior of Netscape Enterprise Server is determined by a set of configuration files. You can change the settings in these configuration files either by using the Server Manager interface or by manually editing the files. The configuration file that contains instructions for how the server processes requests from clients is called .
Configuration Files Configuration Files The configuration and operation of the is controlled by configuration files. The configuration files reside in the directory . This server-root/server-id/config/ directory contains various configuration files for controlling different components, such as for configuring server-side JavaScript™ and jsa.conf netshare.conf configuring NetShare.
Configuration Files obj.conf This file contains instructions for the server about how to process requests from clients (such as browsers). The server looks at the configuration defined by this file every time it processes a request from a client. There is one file for each virtual server class, or grouping of virtual obj.conf servers.
Dynamic Reconfiguration Dynamic Reconfiguration You do not have to restart the server for changes to obj.conf mime.types , and virtual-server-specific ACL files to take effect. All you need to do server.xml is apply the changes by clicking the Apply link and then clicking the Load Configuration Files button on the Apply Changes screen.
Page 23
How the Server Handles Requests from Clients The example request shown below would be sent by a Netscape browser to request the server to send back the resource in . In this example, no foo.com /index.html body data is sent because the method is GET (the point of the request is to get some data, not to send it.) GET /index.html HTTP/1.0 User-agent: Mozilla...
How the Server Handles Requests from Clients Steps in the Request Handling Process When the server first starts up it performs some initialization and then waits for an HTTP request from a client (such as a browser). When it receives a request, it first selects a virtual server.
Writing New Server Application Functions Directives for Handling Requests The file contains a series of instructions, known as directives, that tell the obj.conf what to do at each stage in the request handling process. Each directive invokes a Server Application Function (SAF) with one or more arguments. Each directive applies to a specific stage in the request handling process.
Page 26
Writing New Server Application Functions Netscape Enterprise Server NSAPI Programmer’s Guide • April 2002 (Draft)
Chapter 2 Syntax and Use of obj.conf configuration file contains directives that instruct the Netscape obj.conf Enterprise Server how to handle requests from clients. This chapter discusses server instructions in ; the use of tags; the use of variables; the obj.conf Object flow of control in...
Server Instructions in obj.conf For example: NameTrans fn="document-root" root="D:/Netscape/Servers/docs" indicates when this instruction is executed during the request handling Directive process. The value is one of AuthTrans NameTrans PathCheck ObjectType , and Service Error AddLog The value of the argument is the name of the Server Application Function (SAF) to execute.
Page 29
Server Instructions in obj.conf • NameTrans Translates the URL specified in the request from a logical URL to a physical file system path for the requested resource. This may also result in redirection to another site. For example: NameTrans fn="document-root" root="D:/Netscape/Servers/docs" This example calls the function with a argument of...
Page 30
Server Instructions in obj.conf • Service Generates and sends the response to the client. This involves setting the HTTP result status, setting up response headers (such as content-type and content-length), and generating and sending the response data. The default response is to invoke the function to send the contents of the send-file requested file along with the appropriate header files to the client.
The <Object> Tag and the <Client> Tag The <Object> Tag and the <Client> Tag This section discusses the use of tags in the file <Object> <Client> obj.conf tags group together directives that apply to requests for particular <Object> resources, while tags group together directives that apply to requests <Client>...
The <Object> Tag and the <Client> Tag Objects that Use the name Attribute If a directive in the default object specifies a argument, the server NameTrans name switches to processing the directives in the object of that name before processing the remaining directives in the default object.
The <Object> Tag and the <Client> Tag The URL server_name would be translated to http:// /internalplan1.html . However, suppose that D:/Netscape/Servers/docs/internalplan1.html contains the following additional object: obj.conf <Object ppath="*internal*"> more directives... </Object> In this case, the partial path matches the path *internal* So now the server starts D:/Netscape/Servers/docs/internalplan1.html.
Variables Defined in server.xml <Client ip="198.95.251.*"> <Client dns="*.example.com"> See “Wildcard Patterns,” on page 325 for more information on wildcards. You can also use wildcards to specify a “negative” match, one that excludes clients that match the parameter value specified in the tag.
Flow of Control in obj.conf NOTE Variable substitution is allowed only in an file. It is not obj.conf allowed in any other Enterprise Server configuration files. Any variable referenced in an file must be defined in the obj.conf file at the , or level.
Flow of Control in obj.conf section in the default object must contain exactly one directive that NameTrans invokes the function. This functions translates the document-root server_name part of the requested URL to a physical directory that has http:// been designated as the server’s document root. For example: NameTrans fn="document-root"...
Flow of Control in obj.conf When that directive is executed, the server starts processing directives NameTrans in the object named <Object name="cgi"> more directives... </Object> When a directive has been successfully executed, there will be a NameTrans physical pathname associated with the requested resource. If the resultant pathname matches the (partial path) attribute of another object, the server ppath...
Flow of Control in obj.conf If the directive assigned a name or generated a physical pathname that NameTrans matches the attribute of another object, the server first applies the name ppath directives in the matching object before applying the directives in the PathCheck default object.
Flow of Control in obj.conf For more information about MIME types, see Appendix B, “MIME Types.” Forcing the Type If no previous directive has set the type, and the server does not find a ObjectType matching file extension in the types table, the still has no value even MIME...
Flow of Control in obj.conf NameTrans fn="pfx2dir" from="/cgi" dir="D:/netscape/servers/docs/mycgi" name="cgi" <Object name="cgi"> ObjectType fn="force-type" type="magnus-internal/cgi" Service fn="send-cgi" </Object> The server continues processing all directives including those in the ObjectType default object, but since the attribute has already been set, no other directive type can set it to another value.
Page 41
Flow of Control in obj.conf • The following directive tells the server to look up the resource’s ObjectType MIME type in the MIME types table: ObjectType fn="type-by-extension" • The server finds the following entry in the MIME types table, which sets the type attribute to text/html type=text/html exts=htm,html...
Flow of Control in obj.conf • object has no directives, so the server processes ServletByExt PathCheck directives in the default object. Let’s assume that all PathCheck PathCheck directives succeed. • Next, the server processes the directives, starting with the one in ObjectType object.
Flow of Control in obj.conf This directive matches requests whose method is , or , which covers HEAD POST nearly virtually all requests sent by browsers. The value of the argument uses type special pattern-matching characters. For complete information about the special pattern-matching characters, see Appendix C, “Wildcard Patterns.”...
Syntax Rules for Editing obj.conf Syntax Rules for Editing obj.conf Several rules are important in the file. Be very careful when editing this obj.conf file. Simple mistakes can make the server fail to start or operate incorrectly. Order of Directives The order of directives is important, since the server executes them in the order they appear in .
Syntax Rules for Editing obj.conf Separators The C language allows function names to be composed only of letters, digits, and underscores. You may use the hyphen (-) character in the configuration file in place of underscore (_) for your C code function names. This is only true for function names.
About obj.conf Directive Examples About obj.conf Directive Examples Every line in the file begins with one of the following keywords: obj.conf AuthTrans NameTrans PathCheck ObjectType Service AddLog Error <Object </Object> If any line of any example begins with a different word in the manual, the line is wrapping in a way that it does not in the actual file.
Chapter 3 Predefined SAFs and the Request Handling Process This chapter describes the standard directives and pre-defined Server Application Functions (SAFs) that are used in the file to give instructions to the obj.conf server. For a discussion of the use and syntax of , see the previous obj.conf chapter, Chapter 2, “Syntax and Use of obj.conf.”...
Page 48
Table 3-1 lists the SAFs that can be used with each directive. Table 3-1 Available Server Application Functions (SAFs) Per Directive AuthTrans Stage basic-auth basic-ncsa get-sslid qos-handler NameTrans Stage assign-name document-root home-page pfx2dir redirect strip-params unix-home PathCheck Stage check-acl deny-existence find-index find-links find-pathinfo...
AuthTrans Stage You can measure the performance of any SAF in by adding a obj.conf bucket-name parameter to the function, for example bucket= bucket=cache-bucket To list the performance statistics, use the Service function. service-dump As an alternative, you can use the Service function to generate stats-xml performance statistics;...
AuthTrans Stage The following AuthTrans-class functions are described in detail in this section: • calls a custom function to verify user name and password. basic-auth Optionally determines the user’s group. • verifies user name and password against an NCSA-style or basic-ncsa system DBM database.
Page 52
AuthTrans Stage (optional) specifies the full path and file name of the user groupdb database. This parameter will be passed to the group function. (optional) is the name of the group custom function that groupfn must have been previously loaded with load-modules. It has the same interface as all the SAFs, but it is called with the user name (user), password (pw), user database (userdb), and group database (groupdb) in the pb...
AuthTrans Stage basic-ncsa Applicable in -class directives. AuthTrans function verifies authorization information sent by the client basic-ncsa against a database. The Authorization header is sent as part of the basic server authorization scheme. This function is usually used in conjunction with the PathCheck-class function require-auth Parameters specifies the type of authorization to be used.
AuthTrans Stage See Also require-auth get-sslid Applicable in -class directives. AuthTrans NOTE This function is provided for backward compatibility only. The functionality of has been incorporated into the standard get-sslid processing of an SSL connection. function retrieves a string that is unique to the current SSL session, get-sslid and stores it as the variable in the...
NameTrans Stage Example AuthTrans fn=qos-handler See Also qos-error NameTrans Stage stands for Name Translation. directives translate virtual NameTrans NameTrans URLs to physical directories on your server. For example, the URL .html http://www.example.com/some/file could be translated to the full file-system path /usr/netscape/servers/docs/some/file.html directives should appear in the default object.
NameTrans Stage assign-name Applicable in -class directives. NameTrans function specifies the name of an object in that assign-name obj.conf matches the current request. The server then processes the directives in the named object in preference to the ones in the default object. For example, consider the following directive in the default object: NameTrans fn=assign-name name=personnel from=/personnel Let’s suppose the server receives a request for...
NameTrans Stage (optional) prevents the server from performing a stat on a nostat specified URL whenever possible. virtual-path The effect of nostat=" " in the NameTrans function assign-name is that the server assumes that a virtual-path stat on the specified will fail.
NameTrans Stage When the server receives a request for server-name http:// /somepath/somefile function replaces server-name with the value of its document-root http:// parameter. For example, if the document root directory is root , then when the server receives a request for /usr/netscape/servers/docs server-name , the...
NameTrans Stage Parameters is the path and name of the home page file. If path starts path with a slash (/), it is assumed to be a full path to a file. This function sets the server’s path variable and returns REQ_PROCEED.
Page 60
NameTrans Stage (optional) makes the server look for the PATHINFO find-pathinfo-forward forward in the path right after the ntrans-base instead of backward from the end of path as the server function find-pathinfo does by default. The value you assign to this parameter is ignored. If you do not wish to use this parameter, leave it out.
NameTrans Stage NameTrans fn=pfx2dir from=/icons/happy dir=/users/nikki/images The third example shows the use of the parameter. The find-pathinfo-forward server-name resource is translated to the physical pathname http:// /cgi-bin/ resource. /export/home/cgi-bin/ NameTrans fn="pfx2dir" find-pathinfo-forward="" from="/cgi-bin" dir="/export/home/cgi-bin" name="cgi" redirect Applicable in -class directives. NameTrans function lets you change URLs and send the updated URL to the redirect...
Page 62
NameTrans Stage Using Regular Expressions parameter allows you to use shell expressions to match a string. A shell regex expression is a string pattern made up of ordinary characters and any of the types of pattern sequences listed below. Table 3-2 Shell Expression Pattern Sequences Pattern Matches...
NameTrans Stage Examples In the first example, any request for server-name whatever is translated to a http:// request for whatever. http://tmpserver/ NameTrans fn=redirect from=/ url-prefix=http://tmpserver In the second example, any request for server-name whatever http:// /toopopular/ is translated to a request for whatever.
NameTrans Stage Example NameTrans fn=strip-params unix-home Applicable in -class directives. NameTrans UNIX Only. The function translates user names (typically of the form unix-home ~username) into the user’s home directory on the server’s UNIX machine. You specify a URL prefix that signals user directories. Any request that begins with the prefix is translated to the user’s home directory.
PathCheck Stage PathCheck Stage directives check the local file system path that is returned after the PathCheck step. The path is checked for things such as CGI path information and NameTrans for dangerous elements such as , and then any access /../ restriction is applied.
PathCheck Stage function specifies an Access Control List (ACL) to use to check check-acl whether the client is allowed to access the requested resource. An access control list contains information about who is or is not allowed to access a resource, and under what conditions access is allowed.
PathCheck Stage Examples PathCheck fn=deny-existence path=/usr/netscape/servers/docs/private PathCheck fn=deny-existence bong-file=/svr/msg/go-away.html find-index Applicable in -class directives. PathCheck function investigates whether the requested path is a directory. If find-index it is, the function searches for an index file in the directory, and then changes the path to point to the index file.
PathCheck Stage UNIX Only. The function searches the current path for symbolic or find-links hard links to other directories or file systems. If any are found, an error is returned. This function is normally used for directories that are not trusted (such as user home directories).
PathCheck Stage Parameters optional, common to all obj.conf functions bucket Examples PathCheck fn=find-pathinfo PathCheck fn=find-pathinfo find-pathinfo-forward="" get-client-cert Applicable in -class directives. PathCheck function gets the authenticated client certificate from the get-client-cert SSL3 session. It can apply to all HTTP methods, or only to those that match a specified pattern.
PathCheck Stage controls whether failure to get a client certificate will abort the HTTP require request. If require is absent the default value is 1. • 1 tells the function to abort the HTTP request if the client certificate is not present after dorequest is handled. In this case, the HTTP status is set to PROTOCOL_FORBIDDEN, and the function returns REQ_ABORTED.
Page 71
PathCheck Stage For example, if the base directory is D:/netscape/servers/docs/nikki/ then only requests for resources in this directory or its subdirectories (and their subdirectories and so on) trigger the search for dynamic configuration files. A request for the resource does D:/netscape/servers/docs/somefile.html not trigger the search in this case, since the requested resource is in a parent directory of the base directory.
Page 72
PathCheck Stage NOTE If the resolves to a resource or directory that is higher in the ppath directory tree (or is in a different branch of the tree) than the base directory, the function is not invoked. This is because load-config the base directory specifies the highest-level directory for which requests will invoke the...
PathCheck Stage Examples In this example, whenever the server receives a request for any resource containing the substring that resides in or a secret D:/netscape/servers/docs/nikki/ subdirectory thereof, it searches for a configuration file called checkaccess.nsconfig The server starts the search in the directory D:/netscape/servers/docs/nikki and searches subdirectories too.
PathCheck Stage See Also unix-uri-clean ntcgicheck Applicable in -class directives. PathCheck Windows NT/Windows 2000 Only. The function specifies the file ntcgicheck name extension to be added to any file name that does not have an extension, or to be substituted for any file name that has the extension .cgi Parameters is the replacement file extension.
PathCheck Stage Parameters (optional) is a wildcard local file system path on which this path function should operate. If no path is provided, the function applies to all paths. is the type of HTTP authorization used and must match the auth-type auth-type from the previous authorization function in AuthTrans.
PathCheck Stage Parameters is the URI of the content generator that acts as an index for the virtual-index URI the user enters. (optional) is a comma-separated list of URIs for which this from virtual-index is applicable. If from is not specified, the virtual-index always applies.
PathCheck Stage (optional) is the name of a file (not a URI) to be served if the bong-file restriction is not met optional, common to all obj.conf functions bucket ssl-logout Applicable in -class directives. PathCheck invalidates the current SSL session in the server's SSL session cache. ssl-logout This does not affect the current request, but the next time the client connects, a new SSL session will be created.
ObjectType Stage ObjectType Stage directives determine the MIME type of the file to send to the client in ObjectType response to a request. MIME attributes currently sent are , and type encoding . The MIME type sent to the client as the value of the language content-type header.
ObjectType Stage Make sure that the directive that calls this function comes last in the list of directives so that all other directives have a chance to set ObjectType ObjectType the MIME type first. If there is more than one directive in an object, all ObjectType the directives are applied in the order they appear.
ObjectType Stage If the , and have not been set for a charset content-encoding content-language response, then just before the headers are sent the defaults defined by are used. Note that by placing this function in different objects set-default-type , you can define different defaults for different parts of the document obj.conf tree.
ObjectType Stage optional, common to all obj.conf functions bucket Examples ObjectType fn=shtml-hacktype exec-hack=true type-by-exp Applicable in -class directives. ObjectType function matches the current path with a wildcard expression. If type-by-exp the two match, the parameter information is applied to the file. This is the type same as , except you use wildcard patterns for the files or...
ObjectType Stage See Also type-by-extension, force-type type-by-extension Applicable in -class directives. ObjectType This function instructs the server to look in a table of MIME type mappings to find the MIME type of the requested resource according to the extension of the requested resource.
Service Stage Service Stage class of functions sends the response data to the client. Service Every directive has the following optional parameters to determine Service whether the function is executed. All the optional parameters must match the current request for the function to be executed. •...
Page 84
Service Stage • UseOutputStreamSize (optional) determines the default output stream buffer size, in bytes, for data sent to the client. If this parameter is not specified, the default is bytes. 8192 NOTE parameter can be set to zero in the UseOutputStreamSize file to disable output stream buffering.
Page 85
Service Stage This directive usually comes last in the set of -class directives to give all Service other Service directives a chance to be invoked. This directive is invoked if the method of the request is , or , and the type does not start with HEAD POST .
Service Stage • sets up environment variables, launches a shell CGI program, send-shellcgi and sends the response to the client. • sets up environment variables, launches a WinCGI program, and send-wincgi sends the response to the client. • creates a performance report based on collected performance service-dump bucket data.
Service Stage optional, common to all Service-class functions ChunkedRequestTimeout optional, common to all obj.conf functions bucket Examples Service type=text/html method=GET fn=add-footer file="footers/footer1.html" Service type=text/html method=GET fn=add-footer file="D:/netscape/servers/footers/footer1.html" NSIntAbsFilePath="yes" See Also append-trailer, add-header add-header Applicable in -class directives. Service This function prepends a header to an HTML file that is sent to the client. The header is specified either as a filename or a URI -- thus the header can be dynamically generated.
Service Stage optional, common to all Service-class functions UseOutputStreamSize optional, common to all Service-class functions flushTimer optional, common to all Service-class functions ChunkedRequestBufferSize optional, common to all Service-class functions ChunkedRequestTimeout optional, common to all obj.conf functions bucket Examples Service type=text/html method=GET fn=add-header file="headers/header1.html"...
Service Stage (optional) is a time format string for :LASTMOD:. For timefmt details about time formats refer to Appendix D, “Time Formats.” If timefmt is not provided, :LASTMOD: will not be replaced with the time. optional, common to all Service-class functions type optional, common to all Service-class functions method...
Service Stage optional, common to all Service-class functions query optional, common to all Service-class functions UseOutputStreamSize optional, common to all Service-class functions flushTimer optional, common to all Service-class functions ChunkedRequestBufferSize optional, common to all Service-class functions ChunkedRequestTimeout optional, common to all obj.conf functions bucket Examples Service type=magnus-internal/imagemap method=(GET|HEAD)
Page 91
Service Stage "audio/*" sound.gif "video/*" movie.gif "application/octet-stream" binary.gif directory menu.gif all others unknown.gif Parameters (optional) is the path (relative to the directory being header indexed) and name of a file (HTML or plain text) which is included at the beginning of the directory listing to introduce the contents of the directory.
Service Stage Examples Service fn=index-common type=magnus-internal/directory method=(GET|HEAD) header=hdr readme=rdme.txt See Also cindex-init, index-simple, find-index, home-page index-simple Applicable in -class directives. Service function generates a simple index of the files in the requested index-simple directory. It scans a directory and returns an HTML page to the browser displaying a bulleted list of the files and directories in the directory.
Service Stage See Also cindex-init, index-common key-toosmall Applicable in -class directives. Service NOTE This function is provided for backward compatibility only and was deprecated in iPlanet™ Web Server 4.x. It is replaced by the PathCheck-class SAF ssl-check function returns a message to the client specifying that the key-toosmall secret key size for SSL communications is too small.
Service Stage list-dir Applicable in -class directives. Service function returns a sequence of text lines to the client in response to a list-dir request whose method is INDEX. The format of the returned lines is: name type size mimetype The name field is the name of the file or directory. It is relative to the directory being indexed.
Service Stage make-dir Applicable in -class directives. Service function creates a directory when the client sends a request whose make-dir method is MKDIR. The function can fail if the server can’t write to that directory. When remote file manipulation is enabled in the server, the file contains obj.conf -class function that invokes...
Service Stage Parameters is the full path and file name of the CGI program to path run. optional, common to all Service-class functions type optional, common to all Service-class functions method optional, common to all Service-class functions query optional, common to all Service-class functions UseOutputStreamSize optional, common to all Service-class functions flushTimer...
Service Stage optional, common to all Service-class functions flushTimer optional, common to all Service-class functions ChunkedRequestBufferSize optional, common to all Service-class functions ChunkedRequestTimeout optional, common to all obj.conf functions bucket Examples Service fn="remove-dir" method="RMDIR" remove-file Applicable in -class directives. Service function deletes a file when the client sends a request whose remove-file method is DELETE.
Service Stage Examples Service fn="remove-file" method="DELETE" rename-file Applicable in -class directives. Service function renames a file when the client sends a request with a rename-file header whose method is . It renames the file indicated by the URL to New-URL MOVE within the same directory if the user is authorized and the server has the New-URL...
Service Stage send-cgi Applicable in -class directives. Service function sets up the CGI environment variables, runs a file as a CGI send-cgi program in a new process, and sends the results to the client. For details about the CGI environment variables and their NSAPI equivalents, refer to section “CGI to NSAPI Conversion,”...
Page 100
Service Stage (UNIX only) Specifies the maximum CGI program rlimit_core core file size. A value of 0 disables writing cores. You can supply both current (soft) and maximum (hard) limits, separated by a comma. The soft limit must be listed first. If only one limit is specified, both limits are set to this value.
Service Stage <Object name="default"> NameTrans fn="pfx2dir" from="/cgi-bin" dir="/home/example.com/public_html/cgi-bin" name="cgi" </Object> <Object name="cgi"> ObjectType fn="force-type" type="magnus-internal/cgi" Service fn="send-cgi" user="$user" group="$group" dir="$dir" chroot="$chroot" nice="$nice" </Object> send-file Applicable in -class directives. Service function sends the contents of the requested file to the client. It send-file provides the , and...
Page 102
Service Stage optional, common to all Service-class functions query optional, common to all Service-class functions UseOutputStreamSize optional, common to all Service-class functions flushTimer optional, common to all Service-class functions ChunkedRequestBufferSize optional, common to all Service-class functions ChunkedRequestTimeout optional, common to all obj.conf functions bucket Examples Service type="*~magnus-internal/*"...
Service Stage send-range Applicable in -class directives. Service When the client requests a portion of a document, by specifying HTTP byte ranges, function returns that portion. send-range Parameters optional, common to all Service-class functions type optional, common to all Service-class functions method optional, common to all Service-class functions query...
Service Stage optional, common to all Service-class functions UseOutputStreamSize optional, common to all Service-class functions flushTimer optional, common to all Service-class functions ChunkedRequestBufferSize optional, common to all Service-class functions ChunkedRequestTimeout optional, common to all obj.conf functions bucket Examples Service fn=send-shellcgi Service type=magnus-internal/cgi fn=send-shellcgi send-wincgi Applicable in...
Service Stage service-dump Applicable in -class directives. Service function creates a performance report based on collected service-dump performance bucket data (see “The bucket Parameter,” on page 49”). To read the report, point the browser here: http://server_id:port/.perf Parameters must be perf for this function type optional, common to all Service-class functions method...
Service Stage shtml_send Applicable in -class directives. Service function parses an HTML document, scanning for embedded shtml_send commands. These commands may provide information from the server, include the contents of other files, or execute a CGI program. The function is shtml_send only available when the Shtml plugin ( on UNIX...
Service Stage stats-xml Applicable in -class directives. Service function creates a performance report in XML format. If stats-xml performance buckets have been defined, this performance report includes them. However, you do need to initialize this function using the function in stats-init , then use a function to direct requests to the...
Service Stage obj.conf <Object name="default"> NameTrans fn="assign-name" from="/stats-xml/*" name="stats-xml" </Object> <Object name="stats-xml"> Service fn="stats-xml" </Object> See Also service-dump, stats-init upload-file Applicable in -class directives. Service function uploads and saves a new file when the client sends a upload-file request whose method is if the user is authorized and the server has the needed file system privileges.
AddLog Stage Examples Service fn=upload-file AddLog Stage After the server has responded to the request, the AddLog directives are executed to record information about the transaction. If there is more than one directive, all are executed. AddLog The following AddLog-class functions are described in detail in this section: •...
AddLog Stage optional, common to all obj.conf functions bucket Examples # Log all accesses to the global log file AddLog fn=common-log # Log accesses from outside our subnet (198.93.5.*) to # nonlocallog <Client ip="*~198.93.5.*"> AddLog fn=common-log name=nonlocallog </Client> See Also flex-init init-clf record-useragent...
AddLog Stage Examples # Log all accesses to the global log file AddLog fn=flex-log # Log accesses from outside our subnet (198.93.5.*) to # nonlocallog <Client ip="*~198.93.5.*"> AddLog fn=flex-log name=nonlocallog </Client> See Also flex-init init-clf common-log record-useragent flex-rotate-init record-useragent Applicable in -class directives.
Error Stage Error Stage If a server application function results in an error, it sets the HTTP response status code and returns the value . When this happens, the server stops REQ_ABORTED processing the request. Instead, it searches for an Error directive matching the HTTP response status code or its associated reason phrase, and executes the directive’s function.
Error Stage (optional) is a three-digit number representing the HTTP code response status code, such as 401 or 407. This can be any HTTP response status code or reason phrase according to the HTTP specification. The following is a list of common HTTP response status codes and reason strings.
Page 114
Error Stage Parameters (optional) is a three-digit number representing the HTTP code response status code, such as 401 or 407. The recommended value is 503. This can be any HTTP response status code or reason phrase according to the HTTP specification. The following is a list of common HTTP response status codes and reason strings.
Chapter 4 Creating Custom SAFs This chapter describes how to write your own NSAPI plugins that define custom Server Application Functions (SAFs). Creating plugins allows you to modify or extend the Netscape Enterprise 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.
The SAF Interface 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 file, from obj.conf...
SAF Parameters In this case, the parameter passed to contains name/value pairs basic-ncsa that correspond to auth-type=basic dbm=/netscape/servers/userdb/rs NSAPI provides a set of functions for working with data structures. For pblock example, returns the value for a given name in a .
Page 118
SAF Parameters • rq->vars is a pointer to a containing the server’s “working” variables. This pblock includes anything not specifically found in the following three pblocks. The contents of this vary depending on the specific request and the type of pblock SAF.
Result Codes Result Codes Upon completion, a SAF returns a result code. The result code indicates what the server should do next. The result codes are: • REQ_PROCEED indicates that the SAF achieved its objective. For some request-response steps (AuthTrans, NameTrans, Service, and Error), this tells the server to proceed to the next request-response step, skipping any other SAFs in the current step.
Creating and Using Custom SAFs Load and Initialize the SAF by editing the file to: obj.conf -- Load the shared library file containing your custom SAF(s). -- Initialize the SAF if necessary. Instruct the Server to Call the SAFs by editing to call your custom SAF(s) at the appropriate time.
Creating and Using Custom SAFs Enterprise ServerIf necessary, write an initialization function that performs initialization tasks required by your new SAFs. The initialization function has the same signature as other SAFs: int function(pblock * , Session * , Request * SAFs expect to be able to obtain certain types of information from their parameters.
Creating and Using Custom SAFs Table 4-1 lists the library that you need to link to. Table 4-1 Libraries Platform Library (in addition to the standard Windows Windows NT/Windows ns-httpd40.dll libraries) 2000 HP-UX libns-httpd40.sl All other UNIX platforms libns-httpd40.so Linker Commands and Options for Generating a Shared Object To generate a shared library, use the commands and options listed in Table 4-2.
Creating and Using Custom SAFs Table 4-3 Linker flags Platform Flags Compaq -rpath dir:dir Linux -Wl,-rpath,dir:dir IRIX -Wl,-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 Table 4-4 lists the flags and defines that you need to use for compilation of your source code.
Creating and Using Custom SAFs Load and Initialize the SAF For each shared library (plugin) containing custom SAFs to be loaded into the Enterprise Server, add an directive that invokes the SAF to Init load-modules magnus.conf The syntax for a directive that calls load-modules [path]sharedlibname SAF1,...,SAFn"...
Page 125
Creating and Using Custom SAFs • function-name is the name of the SAF to execute. • nameN valueN are the names and values of parameters which are passed to =" " the SAF. Depending on what your new SAF does, you might need to add just one directive or you might need to add more than one directive to provide complete obj.conf instructions for invoking the new SAF.
Creating and Using Custom SAFs You also need to define objects that contain the directives that run the Service animations and specify the parameter. speed <Object name="small_anim"> Service fn=do_small_anim speed=40 </Object> <Object name="fullscreen_anim"> Service fn=do_big_anim speed=20 </Object> Reconfigure the Server After modifying , you need to reconfigure the server.
Overview of NSAPI C Functions 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 Netscape Server operating system and hardware platforms. They provide improved performance. They are thread-safe which is a requirement for SAFs.
Overview of NSAPI C Functions Protocol Utilities for Service SAFs Protocol utilities provide functionality necessary to implement Service SAFs: • returns the value for a given request header name, reading request_header the headers if necessary. This function must be used when requesting entries from the browser header pblock rq->headers...
Overview of NSAPI C Functions File I/O The file I/O functions provides platform-independent, thread-safe file I/O routines. • opens a file for read-only access. system_fopenRO • opens a file for read-write access, creating the file if system_fopenRW necessary. • opens a file for write-append access, creating the file if system_fopenWA necessary.
Overview of NSAPI C Functions • surrenders ownership of a critical section. crit_exit • disposes of a critical section variable. crit_terminate • creates a new condition variable. condvar_init • awakens any threads blocked on a condition variable. condvar_notify • blocks on a condition variable. condvar_wait •...
Required Behavior of SAFs for Each Directive Virtual Server The virtual server functions provide routines for retrieving information about virtual servers. • finds the virtual server to which a request is directed. request_get_vs • allocates a new slot for storing a pointer to data specific to a vs_alloc_slot certain virtual server.
Required Behavior of SAFs for Each Directive parameter is the primary mechanism for passing along information throughout the request-response process. On input to a SAF, contains whatever values were inserted or modified by previously executed SAFs. On output, 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.
Required Behavior of SAFs for Each Directive AuthTrans SAFs • Purpose: Verify any authorization information. Only basic authorization is currently defined in the HTTP/1.0 specification. • Check for header in which contains the Authorization rq->headers authorization type and uu-encoded user and password information. If header was not sent return REQ_NOACTION •...
Required Behavior of SAFs for Each Directive NameTrans SAFs • Purpose: Convert logical URI to physical path • Perform operations on logical path ( ) to convert it into a full ppath rq->vars local file system path. • Return contains the full local file system REQ_PROCEED ppath rq->vars...
CGI to NSAPI Conversion • Remove existing from . Insert correct content-type rq->srvhdrs content-type rq->srvhdrs • Create any other headers in rq->srvhdrs • Call to set HTTP response status. protocol_status • Call to send HTTP response and headers. protocol_start_response • Generate and send data to the client using net_write •...
Chapter 5 NSAPI Function Reference This chapter lists all the public C functions and macros of the Netscape Server Applications Programming Interface (NSAPI) in alphabetic order. These are the functions you use when writing your own Server Application Functions (SAFs). See Chapter 7, “Syntax and Use of magnus.conf,”...
NSAPI Functions (in Alphabetical Order) CALLOC macro is a platform-independent substitute for the C library routine CALLOC . It allocates bytes from the request’s memory pool. If pooled calloc num*size memory has been disabled in the configuration file (with the built-in pool-init SAF),...
NSAPI Functions (in Alphabetical Order) Syntax cinfo *cinfo_find(char *uri); Returns A pointer to a newly allocated structure if content info was found or NULL cinfo if no content was found structure that is allocated and returned contains pointers to the cinfo content-type, content-encoding, and content-language, if found.
NSAPI Functions (in Alphabetical Order) condvar_notify function is a critical-section function that awakens any condvar_notify threads that are blocked on the given critical-section variable. Use this function to awaken threads of execution of a given critical section. First, use crit_enter gain ownership of the critical section.
NSAPI Functions (in Alphabetical Order) condvar_wait Critical-section function that blocks on a given condition variable. Use this function to wait for a critical section (specified by a condition variable argument) to become available. The calling thread is blocked until another thread calls condvar_notify with the same condition variable argument.
NSAPI Functions (in Alphabetical Order) crit_exit Critical-section function that surrenders ownership of a critical section. Use this function to surrender ownership of a critical section. If another thread is blocked waiting for the section, the block will be removed and the waiting thread will be given ownership of the section.
NSAPI Functions (in Alphabetical Order) crit_terminate Critical-section function that removes a previously-allocated critical-section variable (a variable of type ). Use this function to release a critical-section CRITICAL variable previously obtained by a call to crit_init Syntax void crit_terminate(CRITICAL crvar); Returns void Parameters is a critical-section variable.
NSAPI Functions (in Alphabetical Order) Example /* Register the log_close function, passing it NULL */ /* to close *a log file when the server is */ /* restarted or shutdown. */ daemon_atrestart(log_close, NULL); NSAPI_PUBLIC void log_close(void *parameter) system_fclose(global_logfd); fc_open The fc_open function returns a pointer to that refers to an open file PRFileDesc (fileName).
NSAPI Functions (in Alphabetical Order) is a pointer to the session Session is a pointer to the request Request fc_close The fc_close function closes a file opened using . This function should only fc_open be called with files opened using fc_open Syntax void fc_close(PRFileDesc *fd, FcHdl *hDl;...
NSAPI Functions (in Alphabetical Order) See also filebuf_close, filebuf_open, filebuf_open_nostat, filebuf_getc filebuf_close function deallocates a file buffer and closes its associated file. filebuf_close Generally, use first to open a file buffer, and then filebuf_open filebuf_getc access the information in the file. After you have finished using the file buffer, use to close it.
NSAPI Functions (in Alphabetical Order) filebuf_open function opens a new file buffer for a previously opened file. It filebuf_open returns a new buffer structure. Buffered files provide more efficient file access by guaranteeing the use of buffered file I/O in environments where it is not supported by the operating system.
NSAPI Functions (in Alphabetical Order) Returns A pointer to a new buffer structure to hold the data, if successful or NULL if no buffer could be opened. Parameters is the platform-independent file descriptor of the file which has SYS_FILE fd already been opened.
NSAPI Functions (in Alphabetical Order) See also MALLOC, CALLOC, REALLOC, STRDUP, PERM_MALLOC, PERM_FREE, PERM_REALLOC, PERM_STRDUP func_exec function executes the function named by the entry in a specified func_exec . If the function name is not found, it logs the error and returns pblock REQ_ABORTED You can use this function to execute a built-in server application function (SAF) by...
NSAPI Functions (in Alphabetical Order) Parameters is the name of the function. char *name Example /* this block of code does the same thing as func_exec */ char *afunc = pblock_findval("afunction", pb); FuncPtr afnptr = func_find(afunc); if (afnptr) return (afnptr)(pb, sn, rq); See also func_exec log_error...
NSAPI Functions (in Alphabetical Order) The Session and Request parameters are the same as the ones passed into your SAF. specifies the format for the function that delivers the message. char *fmt printf represents a sequence of parameters for the function.
NSAPI Functions (in Alphabetical Order) net_ip2host function transforms a textual IP address into a fully-qualified net_ip2host domain name and returns it. NOTE This function works only if the directive is enabled in the file. For more information, see Chapter 7, “Syntax magnus.conf and Use of magnus.conf.”...
NSAPI Functions (in Alphabetical Order) Parameters is the platform-independent socket descriptor. SYS_NETFD sd is the buffer to receive the bytes. char *buf is the maximum number of bytes to read. int sz is the number of seconds to allow for the read operation before int timeout returning.
NSAPI Functions (in Alphabetical Order) Syntax int netbuf_buf2sd(netbuf *buf, SYS_NETFD sd, int len); Returns The number of bytes transferred to the socket, if successful or the constant if unsuccessful IO_ERROR Parameters is the buffer to send. netbuf *buf is the platform-independent identifier of the socket. SYS_NETFD sd is the length of the buffer.
NSAPI Functions (in Alphabetical Order) Returns The integer representing the character, if one was retrieved or the constant IO_EOF , for end of file or error IO_ERROR Parameters is the buffer from which to retrieve one character. netbuf b See also netbuf_buf2sd, netbuf_close netbuf_grab netbuf_open...
NSAPI Functions (in Alphabetical Order) Parameters is the platform-independent identifier of the socket. SYS_NETFD sd is the number of characters to allocate for the network buffer. int sz See also netbuf_buf2sd netbuf_close netbuf_getc, netbuf_grab param_create function creates a structure containing a specified param_create pb_param name and value.
NSAPI Functions (in Alphabetical Order) Returns 1 if the parameter was freed or 0 if the parameter was NULL. Parameters is the name-value pair stored in a pblock. pb_param *pp Example if (param_free(pblock_remove("content-type", rq-srvhdrs))) return; /* we removed it */ See also param_create, pblock_pinsert, pblock_remove pblock_copy...
NSAPI Functions (in Alphabetical Order) Returns A pointer to a newly allocated pblock Parameters is the size of the hash table (number of name-value pairs) for the pblock. int n See also pblock_copy, pblock_dup, pblock_find, pblock_findval, pblock_free, pblock_nvinsert, pblock_remove pblock_dup function duplicates a pblock.
NSAPI Functions (in Alphabetical Order) Parameters is the name of a name-value pair. char *name is the to be searched. pblock *pb pblock See also pblock_copy, pblock_dup, pblock_findval, pblock_free, pblock_nvinsert, pblock_remove pblock_findval function finds the value of a specified name in a pblock. If pblock_findval you just want the structure of the pblock, use the...
NSAPI Functions (in Alphabetical Order) Returns void Parameters is the to be freed. pblock *pb pblock See also pblock_copy, pblock_create, pblock_dup, pblock_find, pblock_findval, pblock_nvinsert, pblock_remove pblock_nninsert function creates a new entry with a given name and a pblock_nninsert numeric value in the specified .
NSAPI Functions (in Alphabetical Order) Returns A pointer to the newly allocated structure pb_param Parameters is the name of the new entry. char *name is the string value of the new entry. char *value is the into which the insertion occurs. pblock *pb pblock Example...
NSAPI Functions (in Alphabetical Order) Syntax char *pblock_pblock2str(pblock *pb, char *str); Returns The new version of the parameter. If is NULL, this is a new string; otherwise it is a reallocated string. In either case, it is allocated from the request’s memory pool.
NSAPI Functions (in Alphabetical Order) pblock_remove function removes a specified name-value entry from a pblock_remove specified pblock. If you use this function you should eventually call param_free in order to deallocate the memory used by the structure. pb_param Syntax pb_param *pblock_remove(char *name, pblock *pb); Returns A pointer to the named structure, if it was found or NULL if the named...
NSAPI Functions (in Alphabetical Order) is the into which the name-value pairs are stored. pblock *pb pblock See also pblock_copy, pblock_create, pblock_find, pblock_free, pblock_nvinsert, pblock_remove, pblock_pblock2str PERM_CALLOC macro is a platform-independent substitute for the C library PERM_CALLOC routine . It allocates num*size bytes of memory that persists after the calloc request that is being processed has been completed.
NSAPI Functions (in Alphabetical Order) Returns void Parameters is a pointer to block of memory. If the pointer is not one void *ptr (void *) created by , or , the behavior is PERM_MALLOC PERM_CALLOC PERM_STRDUP undefined. Example char *name; name = (char *) PERM_MALLOC(256);...
NSAPI Functions (in Alphabetical Order) PERM_REALLOC macro is a platform-independent substitute for the C library PERM_REALLOC routine . It changes the size of a specified memory block that was realloc originally created by , or . The contents of the object remains MALLOC CALLOC STRDUP...
NSAPI Functions (in Alphabetical Order) routine is functionally equivalent to PERM_STRDUP newstr = (char *) PERM_MALLOC(strlen(str) + 1); strcpy(newstr, str); A string created with should be disposed with PERM_STRDUP PERM_FREE Syntax char *PERM_STRDUP(char *ptr); Returns A pointer to the new string Parameters is a pointer to a string.
NSAPI Functions (in Alphabetical Order) protocol_dump822 function prints headers from a specified into a protocol_dump822 pblock specific buffer, with a specified size and position. Use this function to serialize the headers so that they can be sent, for example, in a mail message. Syntax char *protocol_dump822(pblock *pb, char *t, int *pos, int tsz);...
NSAPI Functions (in Alphabetical Order) The Session and Request parameters are the same as the ones passed into your SAF. is the stat structure for the file. stat *finfo structure contains the information about the file from the file system. You stat can get the structure info using...
NSAPI Functions (in Alphabetical Order) Example /* A noaction response from this function means the request was HEAD if (protocol_start_response(sn, rq) == REQ_NOACTION) { filebuf_close(groupbuf); /* close our file*/ return REQ_PROCEED; See also protocol_status protocol_status function sets the session status to indicate whether an error protocol_status condition occurred.
NSAPI Functions (in Alphabetical Order) Example /* if we find extra path-info, the URL was bad so tell the */ /* browser it was not found */ if (t = pblock_findval("path-info", rq->vars)) { protocol_status(sn, rq, PROTOCOL_NOT_FOUND, NULL); log_error(LOG_WARN, "function-name", sn, rq, "%s not found", path);...
NSAPI Functions (in Alphabetical Order) function is similar to the protocol_uri2url_dynamic protocol_uri2url function but should be used whenever the structures are Session Request available. This ensures that the URL that it constructs refers to the host that the client specified. Syntax char *protocol_uri2url(char *prefix, char *suffix, Session *sn, Request *rq);...
NSAPI Functions (in Alphabetical Order) Returns A pointer to the new space if the request could be satisfied. Parameters is a (void *) pointer to a block of memory. If the pointer is not one void *ptr created by , the behavior is undefined. MALLOC, CALLOC, STRDUP is the number of bytes to allocate.
NSAPI Functions (in Alphabetical Order) Syntax int request_header(char *name, char **value, Session *sn, Request *rq); Returns A result code, if the header was found, if the header REQ_PROCEED REQ_ABORTED was not found, if there was an error reading from the client. REQ_EXIT Parameters is the name of the header.
NSAPI Functions (in Alphabetical Order) Parameters is the string containing the name of the path. If the value of char *path path NULL, the function uses the entry in the pblock in the Request structure path vars denoted by is the request identifier for a server application function call. Request *rq Example fi = request_stat_path(path, rq);...
NSAPI Functions (in Alphabetical Order) function verifies that the client is who it claims to be; the session_maxdns function does not perform this verification. session_dns NOTE This function works only if the directive is enabled in the file. For more information, see Chapter 7, “Syntax magnus.conf and Use of magnus.conf.”...
NSAPI Functions (in Alphabetical Order) shexp_casecmp function validates a specified shell expression and compares shexp_casecmp it with a specified string. It returns one of three possible values representing match, no match, and invalid comparison. The comparison (in contrast to that of the function) is not case-sensitive.
NSAPI Functions (in Alphabetical Order) Parameters is the string to be compared. char *str is the shell expression (wildcard pattern) to compare against. char *exp Example /* Use wildcard match to see if this path is one we want */ char *path;...
NSAPI Functions (in Alphabetical Order) shexp_valid function validates a specified shell expression named by shexp_valid Use this function to validate a shell expression before using the function to compare the expression with a string. shexp_match Syntax int shexp_valid(char *exp); Returns The constant is a standard string.
NSAPI Functions (in Alphabetical Order) Example char *name1 = "MyName"; char *name2 = STRDUP(name1); See also MALLOC, FREE, CALLOC, REALLOC, PERM_MALLOC, PERM_FREE, PERM_CALOC, PERM_REALLOC, PERM_STRDUP system_errmsg function returns the last error that occurred from the most system_errmsg recent system call. This function is implemented as a macro that returns an entry from the global array .
NSAPI Functions (in Alphabetical Order) Example SYS_FILE logfd; system_fclose(logfd); See also system_errmsg, system_fopenRO, system_fopenRW, system_fopenWA, system_lseek, system_fread, system_fwrite, system_fwrite_atomic, system_flock, system_ulock system_flock function locks the specified file against interference from other system_flock processes. Use if you do not want other processes using the file you system_flock currently have open.
NSAPI Functions (in Alphabetical Order) Parameters is the file name. char *path See also system_errmsg, system_fopenRW, system_fopenWA, system_lseek, system_fread, system_fwrite, system_fwrite_atomic, system_flock, system_ulock, system_fclose system_fopenRW function opens the file identified by in read-write system_fopenRW path mode and returns a valid file descriptor. If the file already exists, system_fopenRW does not truncate it.
NSAPI Functions (in Alphabetical Order) Returns The system-independent file descriptor ( ) if the open succeeded or 0 if the SYS_FILE open failed. Parameters is the file name. char *path See also system_errmsg, system_fopenRO, system_fopenRW, system_lseek, system_fread, system_fwrite, system_fwrite_atomic, system_flock, system_ulock, system_fclose system_fread function reads a specified number of bytes from a specified file...
NSAPI Functions (in Alphabetical Order) Before can be used, you must open the file using any of the system_fwrite functions, except system_fopen system_fopenRO Syntax int system_fwrite(SYS_FILE fd, char *buf, int sz); Returns The constant if the write succeeded or the constant if the write IO_OKAY IO_ERROR...
NSAPI Functions (in Alphabetical Order) Example SYS_FILE logfd; char *logmsg = "An error occurred."; system_fwrite_atomic(logfd, logmsg, strlen(logmsg)); See also system_errmsg, system_fopenRO, system_fopenRW, system_fopenWA, system_lseek, system_fread, system_fwrite, system_flock, system_ulock, system_fclose system_gmtime function is a thread-safe version of the standard system_gmtime gmtime function.
NSAPI Functions (in Alphabetical Order) Syntax struct tm *system_localtime(const time_t *tp, const struct tm *res); Returns A pointer to a calendar time ( ) structure containing the local time. Depending on your system, the pointer may point to the data item represented by the second parameter, or it may point to a statically-allocated item.
NSAPI Functions (in Alphabetical Order) system_rename function renames a file. It may not work on directories if the system_rename old and new directories are on different file systems. Syntax int system_rename(char *old, char *new); Returns 0 if the operation succeeded or -1 if the operation failed. Parameters is the old name of the file.
NSAPI Functions (in Alphabetical Order) Syntax char *system_unix2local(char *path, char *lp); Returns A pointer to the local file system path string Parameters is the UNIX-style pathname to be converted. char *path is the local pathname. char *lp You must allocate the parameter , and it must contain enough space to hold the local pathname.
NSAPI Functions (in Alphabetical Order) Returns pointer to the current thread SYS_THREAD Parameters none. See also systhread_getdata, systhread_newkey, systhread_setdata, systhread_sleep, systhread_start, systhread_timerset systhread_getdata function gets data that is associated with a specified key systhread_getdata in the current thread. Syntax void *systhread_getdata(int key); Returns A pointer to the data that was earlier used with the function...
NSAPI Functions (in Alphabetical Order) Parameters none. See also systhread_current, systhread_getdata, systhread_setdata, systhread_sleep, systhread_start, systhread_timerset systhread_setdata function associates data with a specified key number for systhread_setdata the current thread. Keys are assigned by the function. systhread_newkey Syntax void systhread_setdata(int key, void *data); Returns void Parameters...
NSAPI Functions (in Alphabetical Order) systhread_start function creates a thread with the given priority, allocates systhread_start a stack of a specified number of bytes, and calls a specified function with a specified argument. Syntax SYS_THREAD systhread_start(int prio, int stksz, void (*fn)(void *), void *arg); Returns A new pointer if the call succeeded or the constant...
NSAPI Functions (in Alphabetical Order) See also systhread_current, systhread_getdata, systhread_newkey, systhread_setdata, systhread_sleep,systhread_start util_can_exec UNIX only function checks that a specified file can be executed, returning util_can_exec either a 1 (executable) or a 0. The function checks to see if the file can be executed by the user with the given user and group ID.
NSAPI Functions (in Alphabetical Order) Syntax int util_chdir2path(char *path); Returns 0 if the directory was changed or -1 if the directory could not be changed. Parameters is the name of a directory. char *path The parameter must be a writable string because it isn’t permanently modified. util_chdir2path function changes the current directory to a specified util_chdir2path...
NSAPI Functions (in Alphabetical Order) Parameters is the value of the Cookie: request header. char *cookie is the name of the cookie whose value is to be retrieved. char *name util_env_find function locates the string denoted by a name in a specified util_env_find environment and returns the associated value.
NSAPI Functions (in Alphabetical Order) util_env_replace function replaces the occurrence of the variable denoted util_env_replace by a name in a specified environment with a specified value. Use this function to change the value of a setting in an environment. Syntax void util_env_replace(char **env, char *name, char *value);...
NSAPI Functions (in Alphabetical Order) util_getline function scans the specified file buffer to find a line-feed or util_getline carriage-return/line-feed terminated string. The string is copied into the specified buffer, and NULL-terminates it. The function returns a value that indicates whether the operation stored a string in the buffer, encountered an error, or reached the end of the file.
NSAPI Functions (in Alphabetical Order) Parameters none. util_is_mozilla function checks whether a specified user-agent header util_is_mozilla string is a Netscape browser of at least a specified revision level, returning a 1 if it is and 0 otherwise. It uses strings to specify the revision level to avoid ambiguities like 1.56 >...
NSAPI Functions (in Alphabetical Order) util_itoa function converts a specified integer to a string, and returns the util_itoa length of the string. Use this function to create a textual representation of a number. Syntax int util_itoa(int i, char *a); Returns The length of the string created Parameters is the integer to be converted.
NSAPI Functions (in Alphabetical Order) util_sh_escape function parses a specified string and places a backslash ( util_sh_escape in front of any shell-special characters, returning the resultant string. Use this function to ensure that strings from clients won’t cause a shell to do anything unexpected.
NSAPI Functions (in Alphabetical Order) See also util_sprintf, util_vsnprintf, util_vsprintf util_sprintf function formats a specified string, using a specified format, util_sprintf into a specified buffer using the -style syntax without bounds checking. It printf returns the number of characters in the formatted buffer. Because doesn’t perform bounds checking, use this function only if util_sprintf...
NSAPI Functions (in Alphabetical Order) Syntax int util_strcasecmp(const char *s1, const char *s2); Returns 1 if is greater than 0 if is equal to -1 if is less than Parameters is the first string. char *s1 is the second string. char *s2 See also util_strncasecmp...
NSAPI Functions (in Alphabetical Order) util_strncasecmp function performs a comparison of the first characters in util_strncasecmp the alpha-numeric strings and returns a -1, 0, or 1 to signal which is larger or that they are identical. The function’s comparison is not case-sensitive. Syntax int util_strncasecmp(const char *s1, const char *s2, int n);...
NSAPI Functions (in Alphabetical Order) function does not check bounds for the parameter util_uri_escape Therefore, if is not NULL, it should be at least three times as large as the string is the string containing the original unescaped URI. char *s See also util_uri_is_evil, util_uri_parse, util_uri_unescape util_uri_is_evil...
NSAPI Functions (in Alphabetical Order) See also util_uri_is_evil, util_uri_unescape util_uri_unescape function converts the encoded characters of a URI into util_uri_unescape their ASCII equivalents. Encoded characters appear as %XX where XX is a hexadecimal equivalent of the character. NOTE You cannot use an embedded null in a string, because NSAPI functions assume that a null is the end of the string.
NSAPI Functions (in Alphabetical Order) Parameters is the buffer to receive the formatted string. char *s is the maximum number of bytes allowed to be copied. int n is the format string. The function handles only register char *fmt strings; it does not handle any width or precision strings. is an STD argument variable obtained from a previous call to va_list args va_start...
NSAPI Functions (in Alphabetical Order) vs_alloc_slot function allocates a new slot for storing a pointer to data vs_alloc_slot specific to a certain . The returned slot number may be used in VirtualServer* subsequent calls. The returned slot number is vs_set_data vs_get_data valid for any VirtualServer*...
NSAPI Functions (in Alphabetical Order) vs_get_default_httpd_object function obtains a pointer to the default (or vs_get_default_httpd_object root) from the virtual server's (in the configuration httpd_object httpd_objset defined by the file of the virtual server class). The default object is obj.conf typically named .
NSAPI Functions (in Alphabetical Order) vs_get_httpd_objset function obtains a pointer to the (the vs_get_httpd_objset httpd_objset configuration defined by the file of the virtual server class) for a given obj.conf virtual server. Plugins may only modify the time httpd_objset VSInitFunc (see for an explanation of time).
NSAPI Functions (in Alphabetical Order) See also vs_register_cb request_get_vs vs_get_mime_type function determines the MIME type that would be vs_get_mime_type returned in the header for the given URI. Content-type: The caller should FREE the returned string when done with it. Syntax char* vs_get_mime_type(const VirtualServer* vs, const char* uri);...
NSAPI Functions (in Alphabetical Order) vs_register_cb function allows a plugin to register functions that will vs_register_cb receive notifications of virtual server initialization and destruction events. The function would typically be called from an SAF in vs_register_cb Init magnus.conf When a new configuration is loaded, all registered (virtual server VSInitFunc initialization) callbacks are called for each of the virtual servers before any requests...
NSAPI Functions (in Alphabetical Order) Note that the stored pointer is maintained on a per- basis, not a VirtualServer* per-ID basis. Distinct s from different configurations may exist VirtualServer* simultaneously with the same virtual server IDs. However, since these are distinct s, they each have their own -specific data.
Page 214
NSAPI Functions (in Alphabetical Order) Netscape Enterprise Server NSAPI Programmer’s Guide • April 2002 (Draft)
Chapter 6 Examples of Custom SAFs This chapter discusses examples of custom Server Application Functions (SAFs) for each directive in the request-response process. You may wish to use these examples as the basis for implementing your own custom SAFs. For more information about creating your own custom SAFs, see Chapter 4, “Creating Custom SAFs.”...
Examples in the Build Examples in the Build subdirectory within the nsapi/examples/ plugins/nsapi/examples server installation directory contains examples of source code for SAFs. You can use the makefile in the same directory to compile the example.mak examples and create a library containing the functions in all the example files. To test an example, load the shared library into the Netscape Enterprise examples...
AuthTrans Example AuthTrans Example This simple example of an function demonstrate how to use your own AuthTrans custom ways of verifying that the username and password that a remote client provided is accurate. This program uses a hard coded table of usernames and passwords and checks a given user's password against the one in the static data array.
AuthTrans Example Note that this function does not actually enforce authorization requirements, it only takes given information and tells the server if it's correct or not. The function performs the enforcement, so add the PathCheck require-auth following directive also: PathCheck PathCheck fn=require-auth realm="test realm"...
NameTrans Example /* Verify password */ if(strcmp(pw, user_set[x].pw)) { log_error(LOG_SECURITY, "hardcoded-auth", sn, rq, "user %s entered wrong password", user); /* This will cause the enforcement function to ask */ /* user again */ return REQ_NOACTION; /* If we return REQ_PROCEED, the username will be accepted */ return REQ_PROCEED;...
NameTrans Example example allows URLs to explicitly include extra path explicit_pathinfo information for use by a CGI program. The extra path information is delimited from the main URL by a specified separator, such as a comma. For example: server-name http:// /cgi/marketing,/jan/releases/hardware In this case, the URL of the requested resource (which would be a CGI program) is server-name...
NameTrans Example Source Code This example is in the file in the ntrans.c nsapi/examples/ subdirectory of the server root directory. plugins/nsapi/examples #include "nsapi.h" #include <string.h> /* strchr */ #include "frame/log.h" /* log_error */ #ifdef __cplusplus extern "C" #endif NSAPI_PUBLIC int explicit_pathinfo(pblock *pb, Session *sn, Request *rq) /* Parameter: The character to split the path by */ char *sep = pblock_findval("separator", pb);...
PathCheck Example /* If there is an alternate document specified, use it. */ if(alt) { pb_param *pp = pblock_find("ppath", rq->vars); /* Trash the old value */ FREE(pp->value); /* We must dup it because the library will later free this pblock */ pp->value = STRDUP(alt);...
PathCheck Example Source Code The source code for this example is in in the pcheck.c nsapi/examples/ subdirectory within the server root directory. plugins/nsapi/examples #include "nsapi.h" /* Set to NULL to prevent problems with people not calling acf-init */ static char **hosts = NULL; #include <stdio.h>...
Page 225
PathCheck Example /* Check usage. Note that Init functions have special error logging */ if(!acf_file) { util_sprintf(err, "missing parameter to acf_init (need file)"); pblock_nvinsert("error", err, pb); return REQ_ABORTED; f = fopen(acf_file, "r"); /* Did we open it? */ if(!f) { util_sprintf(err, "can't open access control file %s (%s)", acf_file, system_errmsg());...
ObjectType Example /* Working variables */ char *remip = pblock_findval("ip", sn->client); register int x; if(!hosts) { log_error(LOG_MISCONFIG, "restrict-by-acf", sn, rq, "restrict-by-acf called without call to acf-init"); /* When we abort, the default status code is 500 Server Error */ return REQ_ABORTED; for(x = 0;...
ObjectType Example /* Set the content-type to magnus-internal/parsed-html */ pblock_nvinsert("content-type", "magnus-internal/parsed-html", rq->srvhdrs); function looks at the requested file name. If it ends with html2shtml .html the function looks for a file with the same base name, but with the extension instead.
Service Example /* Work variables */ pb_param *path = pblock_find("path", rq->vars); struct stat finfo; char *npath; int baselen; /* If the type has already been set, don't do anything */ if(pblock_findval("content-type", rq->srvhdrs)) return REQ_NOACTION; /* If path does not end in .html, let normal object types do their job */ baselen = strlen(path->value) - 5;...
Service Example Installing the Example To load the shared object containing your functions add the following line in the section of the file: Init magnus.conf yourlibrary Init fn=load-modules shlib= funcs=simple-service-init,simple-service To call the function to initialize the message representing simple-service-init the generated output, add the following line to the section in Init...
Page 230
Service Example * magnus.conf simple_msg = pblock_findval("generated-output", pb); return REQ_PROCEED; /* This is the customized Service SAF. * It sends the "generated-output" message to the client. NSAPI_PUBLIC int simple-service(pblock *pb, Session *sn, Request *rq) int return_value; char msg_length[8]; /* Use the protocol_status function to set the status of the * response before calling protocol_start_response.
Service Example /* Write the output using net_write*/ return_value = net_write(sn->csd, simple_msg, strlen(simple_msg)); if (return_value == IO_ERROR) { return REQ_EXIT; return REQ_PROCEED; More Complex Service Example function is a custom SAF which replaces the send-images doit.cgi demonstration available on the Netscape home pages. When a file is accessed as , the function checks if the file is /dir1/dir2/something.picgroup...
AddLog Example AddLog Example The example in this section demonstrates how to implement , a custom brief-log SAF for logging only three items of information about a request: the IP address, the method, and the URI (for example, 198.93.95.99 GET /jocelyn/dogs/homesneeded.html Installing the Example To load the shared object containing your functions add the following line in the...
Quality of Service Examples logmsg = (char *) MALLOC(strlen(ip) + 1 + strlen(method) + 1 + strlen(uri) + 1 + 1); len = util_sprintf(logmsg, "%s %s %s\n", ip, method, uri); /* The atomic version uses locking to prevent interference */ system_fwrite_atomic(logfd, logmsg, len);...
Page 235
Quality of Service Examples void decode(const char* val, PRInt32* var, pblock* pb) char* pbval; if ( (!var) || (!val) || (!pb) ) return; pbval = pblock_findval(val, pb); if (!pbval) return; *var = atoi(pbval); /*----------------------------------------------------------------------------- qos_error This function is meant to be an error handler for an HTTP 503 error code, which is returned by qos_handler when QOS limits are exceeded and enforced This sample function just prints out a message about which limits were exceeded.
Page 236
Quality of Service Examples decode("vsclass_connections_enforced", &vsc_conn_ef, apb); decode("server_bandwidth", &srv_bw, apb); decode("server_connections", &srv_conn, apb); decode("server_bandwidth_limit", &srv_bwlim, apb); decode("server_bandwidth_enforced", &srv_bw_ef, apb); decode("server_connections_limit", &srv_connlim, apb); decode("server_connections_enforced", &srv_conn_ef, apb); if ((vs_bwlim) && (vs_bw>vs_bwlim)) /* VS bandwidth limit was exceeded, display it */ ours = PR_TRUE; sprintf(error, "<P>Virtual server bandwidth limit of %d .
Page 237
Quality of Service Examples ours = PR_TRUE; sprintf(error, "<P>Global bandwidth limit of %d . Current bandwidth : %d . <P>", &srv_bwlim, srv_bw); if ((srv_connlim) && (srv_conn>srv_connlim)) /* SERVER connection limit was exceeded, display it */ ours = PR_TRUE; sprintf(error, "<P>Global connection limit of %d . Current connections : %d .
Page 239
Quality of Service Examples /* and enforce it */ ok = PR_FALSE; if ((vs_connlim) && (vs_conn>vs_connlim)) /* connection limit was exceeded, log it */ ereport(LOG_FAILURE, "Virtual server connection limit of %d exceeded. Current VS connections : %d", &vs_connlim, vs_conn); if (vs_conn_ef) /* and enforce it */ ok = PR_FALSE;...
Page 240
Quality of Service Examples if ((srv_bwlim) && (srv_bw>srv_bwlim)) /* bandwidth limit was exceeded, log it */ ereport(LOG_FAILURE, "Global bandwidth limit of %d exceeded. Current global bandwidth : %d", &srv_bwlim, srv_bw); if (srv_bw_ef) /* and enforce it */ ok = PR_FALSE; if ((srv_connlim) &&...
Chapter 7 Syntax and Use of magnus.conf When the Netscape Enterprise Server starts up, it looks in a file called magnus.conf in the server-id directory to establish a set of global variable settings that /config affect the server’s behavior and configuration. Enterprise Server executes all the directives defined in magnus.conf Except for the...
Init SAFs • Native Thread Pools • • Error Logging and Statistic Collection • • Security • Chunked Encoding • Miscellaneous For an alphabetical list of directives, see Appendix G, “Alphabetical List of Directives in magnus.conf.” Much of the functionality of the file cache is controlled by a NOTE configuration file called .
Init SAFs Upon failure, -class functions return . The server logs the error Init REQ_ABORTED according to the instructions in the directives in , and terminates. Error obj.conf Any other result code is considered a success. The following -class functions are described in detail in this section: Init •...
Page 244
Init SAFs Parameters: (optional) is a string of letters specifying the options to activate. opts Currently there is only one possible option: s tells the server to scan each HTML file in the directory being indexed for the contents of the HTML <TITLE> tag to display in the description field.
Init SAFs Example: Init fn=cindex-init widths=50,1,1,0 Init fn=cindex-init ignore=*private* Init fn=cindex-init widths=22,0,0,50 See Also index-common, find-index, home-page define-perf-bucket Applicable in -class directives. Init function creates a performance bucket, which you can define-perf-bucket use to measure the performance of SAFs in see “The bucket Parameter,”...
Init SAFs dns-cache-init Applicable in -class directives. Init function specifies that DNS lookups should be cached when dns-cache-init DNS lookups are enabled. If DNS lookups are cached, then when the server gets a client’s host name information, it stores that information in the DNS cache. If the server needs information about the client in the future, the information is available in the DNS cache.
Page 247
Init SAFs The log file stays open until the server is shut down or restarted (at which time all logs are closed and reopened). If the server has AddLog stage directives that call , the NOTE flex-log flexible log file must be initialized by during server flex-init initialization.
Page 248
Init SAFs Specifies the mode for log files. The default is 0644. file-mode Determines whether a log file is locked during a log flush. flock Boolean. The default is yes. logFileName Specifies the format of each log entry in the log file. format.
Page 249
Init SAFs You can now log cookies by logging the name component. Req->headers.cookie. NOTE Custom headers and other values specified through the Flex-Init directive should be in lower case. For example, to log the value of the custom header “Foobar” use: Req->headers.foobar and not Req->headers.Foobar...
Page 250
Init SAFs Table 7-1 Typical components of flex-init formatting Flex-log option Component headername Any header value %Req->headers. Name of authorized user %Req->vars.auth-user% name Value of a cookie %Req->headers.cookie. varname Value of any variable %Req->vars. in Req->vars Virtual Server ID %vsid% Examples The first example below initializes flexible logging into the file /usr/netscape/servers/https-servername/logs/access...
Init SAFs The second example initializes flexible logging into the file /user/netscape/servers/https-servername/logs/extended Init fn=flex-init extended="/usr/netscape/server6/https-servername/logs/extended" format.extended="%Ses->client.ip% - %Req->vars.auth-user% [%SYSDATE%] \"%Req->reqpb.clf-request%\" %Req->srvhdrs.clf-status% %Req->srvhdrs.content-length% %Req->headers.referer% \"%Req->headers.user-agent%\" %Req->reqpb.method% %Req->reqpb.uri% %Req->reqpb.query% %Req->reqpb.protocol%" The third example shows how logging can be tuned to prevent request handling threads from making blocking calls when writing to log files, instead delegating these calls to the log flush thread.
Page 252
Init SAFs the server moves the log file to a file whose name indicates the time of moving. The log functions in the stage in then start logging entries in a new AddLog obj.conf log file. The server does not need to be shut down while the log files are being rotated.
Init SAFs init-cgi Applicable in -class directives. Init function performs certain initialization tasks for CGI execution. init-cgi Two options are provided: timeout of the execution of the CGI script, and establishment of environment variables. Parameters (optional) specifies how many seconds the server waits for timeout CGI output.
Init SAFs See Also send-cgi, send-wincgi, send-shellcgi init-clf Applicable in -class directives. Init function opens the named log files to be used for common logging. init-clf function writes entries into the log files during the stage of common-log AddLog the request handling process. The log files stay open until the server is shut down (at which time the log files are closed) or restarted (at which time the log files are closed and reopened).
Init SAFs Examples Init fn=init-clf access=/usr/netscape/servers/https-boots/logs/access Init fn=init-clf templog=/tmp/mytemplog templog2=/tmp/mytemplog2 See Also common-log record-useragent flex-rotate-init init-uhome Applicable in -class directives. Init UNIX Only. The function loads information about the system’s user init-uhome home directories into internal hash tables. This increases memory usage slightly, but improves performance for servers that have a lot of traffic to home directories.
Init SAFs If you define your own Server Application Functions, you get the server to load them by using the function and specifying the shared library or dll load-modules to load. Parameters specifies either the full path to the shared library or dynamic shlib link library or a file name relative to the server configuration directory.
Init SAFs Directs output to the Windows NT/Windows 2000 console. stdout The required and only value is console. Example Init fn="nt-console-init" stdout=console stderr=console perf-init Applicable in -class directives. Init function enables system performance measurement via perf-init performance buckets. For more information about performance buckets, see the Netscape Enterprise Server Performance Tuning, Sizing, and Scaling Guide.
Init SAFs function changes the default values of pooled memory settings. pool-init The size of the free block list may be changed or pooled memory may be entirely disabled. Memory allocation pools allow the server to run significantly faster. If you are programming with the NSAPI, note that , and MALLOC...
Page 259
Init SAFs Upon accepting a connection, the server checks to see if the method that it received is known to it. If the server does not recognize the method, it returns a “501 Method Not Implemented” error message. Parameters is a comma separated list of the names of the methods you methods are registering.
Init SAFs Example The following example shows the use of and a register-http-method Service function for one of the methods. Init fn="register-http-method" methods="MY_METHOD1,MY_METHOD2" Service fn="MyHandler" method="MY_METHOD1" stats-init Applicable in -class directives. Init This function enables reporting of performance statistics in XML format. The actual report is generated by the function in stats-xml...
Init SAFs thread-pool-init Applicable in -class directives. Init This function creates a new pool of user threads. A pool must be declared before it’s used. To tell a plugin to use the new pool, specify the parameter when pool loading the plugin with the Init-class function load-modules One reason to create a custom thread pool would be if a plugin is not thread-aware, in which case you can set the maximum number of threads in the pool to 1.
Server Information stack size of each thread in the native (kernel) thread pool. stackSize Example Init fn=thread-pool-init name="my-custom-pool" maxthreads=5 minthreads=1 queuesize=200 Init fn=load-modules shlib="C:/mydir/myplugin.dll" funcs="tracker" pool="my-custom-pool" See also load-modules Server Information This section lists the directives in that specify information about the magnus.conf server.
Server Information Syntax path ExtraPath MtaHost Specifies the name of the SMTP mail server used by the server’s agents. This value must be specified before reports can be sent to a mailing address. NetSiteRoot Specifies the absolute pathname to the top-level directory under which server instances can be found.
Server Information ServerString Modifies the HTTP header . Can be used when the type, version, and name Server of the web server needs to be suppressed for security reasons. Syntax ServerString server_public_name/version Default Netscape-Enterprise/6.1 AOL TempDir Specifies the directory on the local volume that the server uses for its temporary files.
Language Issues User Windows NT/Windows 2000: The directive specifies the user account the User server runs with. By using a specific user account (other than LocalSystem), you can restrict or enable system features for the server. For example, you can use a user account that can mount files from another machine.
Language Issues • DefaultLanguage AdminLanguage For an international version of the server, this directive specifies the language for the Server Manager. Values are (English), (French), (German) or (Japanese). Default The default is ClientLanguage For an international version of the server, this directive specifies the language for client messages (such as File Not Found).
DNS Lookup DNS Lookup This section lists the directives in that affect DNS lookup. The magnus.conf directives are: • AsyncDNS • AsyncDNS Specifies whether asynchronous DNS is allowed. The directive must be set to for this directive to take effect. The value is either .
Threads, Processes and Connections Threads, Processes and Connections In Enterprise Server 6.1, acceptor threads on a listen socket accept connections and put them onto a connection queue. Session threads then pick up connections from the queue and service the requests. The session threads post more session threads if required at the end of the request.
Threads, Processes and Connections • RcvBufSize • RqThrottle • RqThrottleMin • SndBufSize • StackSize • StrictHttpHeaders • TerminateTimeout • ThreadIncrement • UseNativePoll (UNIX only) Also see the section “Native Thread Pools,” on page 274 for directives for controlling the pool of native kernel threads. Concurrency In a Windows NT/Windows 2000 environments, creates a specified number of native threads that:...
Threads, Processes and Connections HeaderBufferSize The size (in bytes) of the buffer used by each of the request processing threads for reading the request data from the client. The maximum number of request processing threads is controlled by the RqThrottle setting. Default The default value is (8 KB).
Threads, Processes and Connections The timeout countdown starts when the connection is handed over to the keep-alive subsystem. If there is no activity on the connection when the timeout expires, the connection is closed. Default The default value is seconds. The maximum value is seconds (5 minutes).
Threads, Processes and Connections One process per processor is recommended if you are running in multi-process mode. In Enterprise Server 6.1, there is always a primordial process in addition to the number of active processes specified by this setting. Enterprise ServerThere is additional discussion of this and other server configuration and performance tuning issues in the Netscape Enterprise Server Performance Tuning, Sizing, and Scaling Guide.
Threads, Processes and Connections RqThrottleMin Specifies the number of request processing threads that are created when the server is started. As the load on the server increases, more request processing threads are created (up to a maximum of threads). RqThrottle Default SndBufSize Specifies the size (in bytes) of the send buffer used by sockets.
Native Thread Pools ThreadIncrement The number of additional or new request processing threads created to handle an increase in the load on the server, for example when the number of pending connections (in the request processing queue) exceeds the number of idle request processing threads.
• NativePoolMaxThreads • NativePoolMinThreads • NativePoolQueueSize NativePoolStackSize Determines the stack size of each thread in the native (kernel) thread pool. Default NativePoolMaxThreads Determines the maximum number of threads in the native (kernel) thread pool. Enterprise Server Default NativePoolMinThreads Determines the minimum number of threads in the native (kernel) thread pool. Default NativePoolQueueSize Determines the number of threads that can wait in the queue for the thread pool.
• CGIExpirationTimeout • CGIStubIdleTimeout • CGIWaitPid (UNIX Only) • MaxCGIStubs • MinCGIStubs CGIExpirationTimeout This directive specifies the maximum time in seconds that CGI processes are allowed to run before being killed. The value of should not be set too low - 300 seconds (5 CGIExpirationTimeout minutes) would be a good value for most interactive CGIs;...
Error Logging and Statistic Collection Default MaxCGIStubs Controls the maximum number of CGIStub processes the server can spawn. This is the maximum concurrent CGIStub processes in execution, not the maximum number of pending requests. The default value should be adequate for most systems.
Error Logging and Statistic Collection • LogVsId • PidLog • StatsUpdateInterval ErrorLog directive specifies the directory where the server logs its errors. If ErrorLog errors are reported to a file, then the file and directory in which the log is kept must be writable by whatever user account the server runs as.
Error Logging and Statistic Collection LogFlushInterval This directive determines the log flush interval, in seconds, of the log flush thread. Default LogVerbose This directive determines whether verbose logging occurs or not. If the value is the server logs all server messages including those that are not logged by default. Default LogVsId This directive determines whether or not virtual server IDs are displayed in the...
Examples PidLog /var/ns-server/logs/pid PidLog /tmp/ns-server.pid StatsUpdateInterval This directive allows you to set the interval in seconds between collections of OS-specific statistics. The maximum interval is 86400 seconds (24 hours). To disable the gathering of OS-specific statistics altogether, set the number of seconds to or less.
Security If you use a large number for this value, you may need to restart the Enterprise Server when you make changes to the LDAP entries. For example, if this value is set to 120 seconds, the Enterprise Server might be out of sync with the LDAP server for as long as two minutes.
Security • SSLSessionTimeout • SSL3SessionTimeout CRLAgeCheck Specifies whether to shut down Enterprise Server if the age of a downloaded CRL exceeds the time specified in its Next Update field. This condition indicates that the CRL may not contain the most recent information available. To avoid the possibility of users authenticating with compromised certificates that would have been added to an up-to-date CRL, you can choose to have Enterprise Server shut down automatically when this condition occurs.
Page 283
Security ldap://ldap.example.com:5000/o=example.net?cn,mail, telephoneNumber?sub?(sn=Jensen) http[s]://[username:password@]hostname[:port]/path[?query_string] For example: https://ca.example.com:1025/getCRL?op=getCRL&issuepoint=Maste rCRL • The update_interval is the maximum amount of time in minutes to allow between CRL dowloads. At startup, Enterprise Server downloads all CRLs configured for automatic downloading. To determine the time of the next download, Enterprise Server uses this value or the time specified in the Next Update field of the CRL, whichever is sooner.
Security CRLUpdateCritical Specifies whether to shut down Enterprise Server when a CRL update fails for any reason. Before Enterprise Server shuts down, an error message is written to the log for later analysis. Syntax CRLUpdateCritical [on|off] Default This directive is added to only after automatic CRL downloads are magnus.conf enabled.
Security For more information about enabling SSL for individual virtual servers, see Chapter 8, “Virtual Server Configuration Files.” Syntax Security [on|off] Default Example Security off SSLCacheEntries Specifies the number of SSL sessions that can be cached. There is no upper limit. Syntax number SSLCacheEntries...
Chunked Encoding The seconds value is the number of seconds until a cached SSL2 session becomes invalid. If the directive is specified, the value of seconds is SSLSessionTimeout silently constrained to be between 5 and 100 seconds. Default The default value is 100. SSL3SessionTimeout directive controls SSL3 session caching.
Chunked Encoding NOTE parameter can be set to zero in the UseOutputStreamSize file to disable output stream buffering. For the obj.conf file, setting to zero has no magnus.conf UseOutputStreamSize effect. Syntax size UseOutputStreamSize The size value is the number of bytes. Default The default value is (8 KB).
Miscellaneous Miscellaneous This section lists miscellaneous other directives in magnus.conf • ChildRestartCallback • HTTPVersion • MaxRqHeaders • Umask (UNIX only) NOTE Directives noted with boolean values have the following equivalent values: on/yes/true off/no/false ChildRestartCallback This directive forces the callback of NSAPI functions that were registered using the function when the server is restarting or shutting down.
Miscellaneous Umask (UNIX only) This directive specifies the umask value used by the NSAPI functions to open files in different modes. Valid System_fopenWA() System_fopenRW() values for this directive are standard UNIX umask values. For more information on these functions, see system_fopenWA in Chapter 5, “NSAPI Function Reference.”...
Page 290
Miscellaneous Netscape Enterprise Server NSAPI Programmer’s Guide • April 2002 (Draft)
Chapter 8 Virtual Server Configuration Files file configures virtual servers. A master file, server.xml server.dtd determines the format and content of the file. This chapter describes server.xml both these files and contains the following sections: • The server.dtd File • The server.xml File •...
The server.xml File For example, the following code defines the (or virtual server class) VSCLASS element. The first line specifies that a element can contain , or VARS elements (if this element could not contain other elements, you would QOSPARAMS instead of a list of element names in parentheses).
The server.xml File If no virtual server (VS) can be found that matches an IP address or header, Host requests are processed using the default VS defined in the . This CONNECTIONGROUP VS could be made to output a customized error message, or even handle the request using a special document root.
The server.xml File Format of a Variable A variable is found when the following regular expression matches: \$[A-Za-z][A-Za-z0-9_]* This expression represents a $ followed by one or more alphanumeric characters. A delimited version (“${VARS}”) is not supported. To get a regular $ character, use $$ in files to have variable substitution.
The server.xml File The value of the dir parameter of the send-cgi SAF. $dir The value of the nice parameter of the send-cgi SAF. $nice Variable Evaluation Variables are evaluated when generating specific objset for individual virtual servers. Evaluation is recursive: variable values can contain other variables. For example: <SERVER>...
Elements in server.dtd and server.xml Elements in server.dtd and server.xml This section describes the XML elements in the files. server.dtd server.xml Subelements must be defined in the order in which they are listed. SERVER Defines a server. There can only be one of this element in a file.
Elements in server.dtd and server.xml LS (Listen Socket) Defines a listen socket. NOTE When you create a secure listen socket through the Server Manager, security is automatically turned on globally in When magnus.conf. you create a secure listen socket manually in , security server.xml must be turned on by editing...
Elements in server.dtd and server.xml (optional) Valid on Linux only. Specifies how long in seconds tcpdeferaccept the kernel should perform connection preprocessing and wait until the first packet of real data has arrived before waking the server. A value of 0 deactivates this feature. The default is 0. (optional) Allows you to modify the default TCP tcpnodelay data-gathering algorithm for sockets accepted from a...
Elements in server.dtd and server.xml IP address that the associated virtual servers use or the value matchingip default. Can be in dotted-pair or IPv6 notation. Cannot be any for INADDR_ANY. Must be default if the containing LS does not have ip=any. If the containing LS has ip=any, can be a specific IP address or default.
Elements in server.dtd and server.xml (optional) A space-separated list of the SSL2 ciphers used, ssl2ciphers with the prefix + to enable or - to disable, for example +rc4. Allowed values are rc4 rc4export rc2export idea desede3. (optional) Determines whether SSL3 is enabled. Legal values ssl3 are on, off, yes, no, 1, 0.
Page 302
Elements in server.dtd and server.xml Internal name for the MIME types listing. Used in a VS element to define the MIME types used by the virtual server. The MIME types name cannot begin with a number. The name of a MIME types file. For information about the file format of this file, see Appendix B, “MIME Types.”...
Elements in server.dtd and server.xml ACLFILE References one or more ACL files. Subelements: none Attributes: Internal name for the ACL file listing. Used in a VS element to define the ACL file used by the virtual server. An ACL file listing name cannot begin with a number.
Elements in server.dtd and server.xml (optional) Tells the server which object loaded from an rootobject obj.conf file is the default. The default object is expected to have all the name translation (NameTrans) directives for the virtual server; any server behavior that is configured in the default object affects the entire server.
Elements in server.dtd and server.xml (optional) Determines whether a VS is active (on) or inactive state (off, disable). The default is on (active). When inactive, a VS does not service requests. If a VS is disable, only the global server administrator can turn it on.
Virtual Server Selection for Request Processing USERDB Defines the user database used by the virtual server. See “User Database Selection,” on page 307 for more information about how a user database is selected for a given virtual server. Subelements: none Attributes: The user database name in the virtual server’s ACL file.
User Database Selection A virtual server is then selected as follows: • If the connection group is configured to only a default virtual server, that virtual server is selected. • If the connection group has more than one virtual server configured to it, the request header is matched to the attribute of a virtual server.
The Netscape LDAP Schema A user database is selected for a virtual server as follows: • If a has no subelement, user- or group-based ACLs fail. USERDB • When no attribute is present in a virtual server’s ACL definition, the database must have a subelement with an...
The Netscape LDAP Schema Underneath each organization, there must be two entries: organizationalUnit . A third, , can be present if device data is to ou=People ou=Groups ou=Devices be stored for the organization. Each user entry must have a unique value within a given organization.
Page 310
The Netscape LDAP Schema Netscape Enterprise Server NSAPI Programmer’s Guide • April 2002 (Draft)
Appendix A Data Structure Reference NSAPI uses many data structures which are defined in the header file, nsapi.h which is in the directory server-root /plugins/include The NSAPI functions described in Chapter 5, “NSAPI Function Reference,” provide access to most of the data structures and data fields. Before directly accessing a data structure in , check if an accessor function exists for it.
Privatization of Some Data Structures Privatization of Some Data Structures In iPlanet Web Server 4. , some data structures were moved from nsapi.h . The data structures in are now considered to be nsapi_pvt.h nsapi_pvt.h private data structures, and you should not write code that accesses them directly. Instead, use accessor functions.
pblock typedef struct { /* Information about the remote client */ pblock *client; /* The socket descriptor to the remote client */ SYS_NETFD csd; /* The input buffer for that socket descriptor */ netbuf *inbuf; /* Raw socket information about the remote */ /* client (for internal use) */ struct in_addr iaddr;...
pb_param struct pb_entry { pb_param *param; struct pb_entry *next; pb_param represents a name-value pair, as stored in a pb_param pb_entry typedef struct { char *name,*value; } pb_param; Session->client parameter block structure contains two entries: Session->client • entry is the IP address of the client machine. •...
stat typedef struct { /* Server working variables */ pblock *vars; /* The method, URI, and protocol revision of this request */ block *reqpb; /* Protocol specific headers */ int loadhdrs; pblock *headers; /* Server’s response headers */ pblock *srvhdrs; /* The object set constructed to fulfill this request */ httpd_objset *os;...
shmem_s struct stat { dev_t st_dev; /* device of inode */ inot_t st_ino; /* inode number */ short st_mode; /* mode bits */ short st_nlink; /* number of links to file /* short st_uid; /* owner’s user id */ short st_gid;...
Page 317
cinfo typedef struct { char *type; /* Identifies what kind of data is in the file*/ char *encoding; /* encoding identifies any compression or other /* /* content-independent transformation that’s been /* /* applied to the file, such as uuencode)*/ char *language;...
Page 318
cinfo Netscape Enterprise Server NSAPI Programmer’s Guide • April 2002 (Draft)
Appendix B MIME Types This appendix discusses the MIME types file. The sections are: • Introduction • Determining the MIME Type • How the Type Affects the Response • What Does the Client Do with the MIME Type? • Syntax of the MIME Types File •...
Determining the MIME Type Determining the MIME Type During the step in the request handling process, the server determines ObjectType the MIME type attributes of the resource requested by the client. Several different server application functions (SAFs) can be used to determine the MIME type, but the most commonly used one is .
What Does the Client Do with the MIME Type? For example, if the requested resource’s file extension is , the type is mapped .map . If the extension is , or , the type is magnus-internal/imagemap .cgi, .exe .bat set to magnus-internal/cgi type=magnus-internal/imagemap exts=map...
Syntax of the MIME Types File Syntax of the MIME Types File The first line in the MIME types file identifies the file format and must read: #--Netscape Communications Corporation MIME Information Other non-comment lines have the following format: type=type/subtype exts=[file extensions] •...
Page 323
Sample MIME Types File #--Netscape Communications Corporation MIME Information # Do not delete the above line. It is used to identify the filetype. type=application/octet-stream exts=bin,exe type=application/oda exts=oda type=application/pdf exts=pdf type=application/postscript exts=ai,eps,ps type=application/rtf exts=rtf type=application/x-mif exts=mif,fm type=application/x-gtar exts=gtar type=application/x-shar exts=shar type=application/x-tar exts=tar type=application/mac-binhex40 exts=hqx...
Page 324
Sample MIME Types File Netscape Enterprise Server NSAPI Programmer’s Guide • April 2002 (Draft)
Appendix C Wildcard Patterns This appendix describes the format of wildcard patterns used by the Netscape Enterprise Server. These wildcards are used in: • directives in the configuration file (see Chapter 2, “Syntax and Use of obj.conf obj.conf”) • various built-in SAFs (see Chapter 3, “Predefined SAFs and the Request Handling Process”) •...
Wildcard Examples Wildcard pattern Table C-1 Pattern Match any character except a or z. [^az] Negates the expression that follows. Wildcard Examples Table C-2 Wildcard examples Pattern Result Matches any string ending with the characters .example.com. *.example.com Matches either quark.example.com or (quark|energy).example.com energy.example.com.
Appendix D Time Formats This appendix describes the format strings used for dates and times. These formats are used by the NSAPI function , by some built-in SAFs such as util_strftime , and by server-parsed HTML ( append-trailer parse-html The formats are similar to those used by the C library routine, but not strftime identical.
Page 328
Table D-1 Symbol Meaning Day of month as decimal number (1-31) without leading zeros Hour in 12-hour format (01-12) Day of year as decimal number (001-366) Hour in 24-hour format (0-23) without leading zeros Hour in 12-hour format (1-12) without leading zeros Month as decimal number (01-12) line feed A.M./P.M.
Appendix E HyperText Transfer Protocol The HyperText Transfer Protocol (HTTP) is a protocol (a set of rules that describes how information is exchanged) that allows a client (such as a web browser) and a web server to communicate with each other. HTTP is based on a request/response model.
Requests For more information on the criteria for being conditionally compliant, see the Hypertext Transfer Protocol—HTTP/1.1 specification (RFC 2068) at: http://www.ietf.org/rfc/rfc2068.txt?number=2068 Requests A request from a browser to a server includes the following information: • Request Method, URI, and Protocol Version •...
Responses Table E-1 Common request headers Request header Description The name and version of the browser software. User-agent The URL of the document where the user clicked on the link. Referer The Internet host and port number of the resource being Host requested.
Page 332
Responses Some common status codes are shown in Table E-2. Table E-2 Common HTTP status codes Status code Meaning OK; request has succeeded for the method used (GET, POST, HEAD). The request has resulted in the creation of a new resource reference by the returned URI.
Responses Table E-2 Common HTTP status codes (Continued) Status code Meaning Server error. A server-related error occurred. The server administrator should check the server’s error log to see what happened. Sent if the quality of service mechanism was enabled and bandwidth or connection limits were attained.
Buffered Streams Buffered Streams Buffered streams improve the efficiency of network I/O (for example the exchange of HTTP requests and responses) especially for dynamic content generation. Buffered streams are implemented as transparent NSPR I/O layers, which means even existing NSAPI modules can use them without any change. The buffered streams layer adds following features to the Netscape Enterprise Server: •...
Page 335
Buffered Streams Output buffering has been built in to the functions that transmit data, such as (see Chapter 5, “NSAPI Function Reference.”). You can specify the net_write following Service SAF parameters that affect stream buffering, which are described in detail in Chapter 3, “Predefined SAFs and the Request Handling Process.” •...
Page 336
Buffered Streams Netscape Enterprise Server NSAPI Programmer’s Guide • April 2002 (Draft)
Appendix F Dynamic Results Caching Functions The functions described in this appendix allow you to write a results caching plugin for Netscape Enterprise Server. A results caching plugin, which is a SAF, caches data, a page, or part of a page in the web server address Service space, which the web server can refresh periodically on demand.
SAF that is visible to the plugin creates the handle to the cache. The Init Init SAF must pass the following parameters to the function: dr_cache_init • RefreshFunctionPointer • FreeFunctionPointer • KeyComparatorFunctionPtr • RefershInterval value must be a type. For more RefershInterval PrIntervalTime information, see the NSPR reference at:...
dr_cache_init function creates a persistent handle to the cache, or NULL on dr_cache_init failure. It is called by an SAF. Init Syntax PRInt32 dr_cache_init(DrHdl *hdl, RefreshFunc_t ref, FreeFunc_t fre, CompareFunc_t cmp, PRUint32 maxEntries, PRIntervalTime maxAge); Returns if successful. if an error occurs. Parameters is a pointer to an unallocated handle.
The plugin may simply decide to replace the cached entry even if it has not expired (based on some other business logic). The function is useful in dr_cache_refresh this case. This way the plugin does the cache refresh management actively by itself. Syntax PRInt32 dr_cache_refresh(DrHdl hdl, const char *key, PRUint32 klen, PRIntervalTime timeout, Entry *entry, Request *rq, Session *sn);...
Page 341
By default, this function refreshes the cache entry if it has expired by making a call to the function passed to . If no cache entry is found with the dr_cache_init specified , this function adds a new cache entry by calling the function before sending out the response.
is the length of the header data in bytes (which can be PRUint32 hlen is the length of the footer data in bytes (which can be PRUint32 flen is the timeout before this function aborts. PRIntervalTime timeout is ORed directives for this function (see Flags). PRUint32 flags is a pointer to the request.
Page 343
Returns if successful. IO_OKAY if an error occurs. IO_ERROR if an error in file handling occurs. FC_ERROR Parameters is the file to be inserted. const char *fileName is any header data (which can be NULL). const char *hdr is any footer data (which can be NULL). const char *ftr is the length of the header data in bytes (which can be 0).
Page 344
Netscape Enterprise Server NSAPI Programmer’s Guide • April 2002 (Draft)
Page 359
vs_alloc_slot 208 builtin SAFs 47 vs_get_data 208 vs_get_default_httpd_object 209 vs_get_doc_root 209 vs_get_httpd_objset 210 vs_get_id 210 vs_get_mime_type 211 cache vs_lookup_config_var 211 enabling memory allocation pool 257 vs_register_cb 212 CALLOC API function 140 vs_set_data 212 case sensitivity vs_translate_uri 213 in obj.conf 44 append-trailer function 88 certificates assign-name function 56...
Page 360
field in session parameter 117 creating getting DNS name for 314 custom SAFs 115 getting IP address for 314 crit_enter requests 22 API function 143 sessions and 312 crit_exit CLIENT_CERT environment variable 136 API function 144 clientauth attribute 301 crit_init API function 144 ClientLanguage magnus.conf directive 266...
Page 361
deny-existence function 66 enforcebandwidth attribute 305 descend parameter 72 enforceconnections attribute 305 dir parameter 59, 68, 99 Enterprise Server see server dir variable 296 environment variables directives and init-cgi function 253 for handling requests 25 CGI to NSAPI conversion 135 magnus.conf 241 obj.conf 47 Error directive 24...
Page 362
API function 342 in directives in obj.conf 28 file attribute force-type 39 for ACLFILE element 303 example 39 for MIME element 302 force-type function 78 file descriptor forcing closing 182 object type 39 locking 183 format.logFileName parameter 248 opening read-only 183 formats opening read-write 184 time 327...
Page 363
header files index-names parameter 67 nsapi.h 121, 311 index-simple function 92 header parameter 91 inetOrgPerson HeaderBufferSize in convergence tree 309 magnus.conf directive 270 Init headers 22 function descriptions 242 field in request parameter 118 requirements for SAFs 132 home-page function 58 init-cgi function 253 HOST environment variable 136 init-clf function 254...
Page 364
legacyls attribute 297 make-dir function 95 line continuation 45 MALLOC API function 153 linking SAFs 121 matching special characters 325 list-dir function 94 matchingip attribute 300 ListenQ magnus.conf directive 271 maxbps attribute 305 load-config function 70 MaxCGIStubs magnus.conf directive 277 loading custom SAFs 124 maxconn attribute 305...
Page 365
example of custom SAF 219 functions flow of control 35 overview 127 function descriptions 55 using 25 requirements for SAFs 134 NSAPI functions 139 summary 29 nsapi.h 121, 311 native thread pools location 121 defining in obj.conf 261 overview of data structures 311 settings in magnus.conf 274 NSCP_POOL_STACKSIZE 274 NativePoolMaxThreads...
Page 366
example of custom SAF 226 pblock flow of control 38 NSAPI data structure 313 function descriptions 78 see parameter block requirements for SAFs 134 pblock_copy summary 29 API function 159 order pblock_create of directives in obj.conf 44 API function 159 OTimeout pblock_dup magnus.conf directive 270...
Page 367
instructing the server to use 124 query parameter 83 loading and initializing 124 QUERY_STRING environment variable 136 pool-init function 257 query-handler function 95 port attribute 298 quotes 45 PostThreadsEarly magnus.conf directive 272 ppath attribute in obj.conf objects 31 in objects 32 predefined SAFs 47 RcvBufSize magnus.conf directive 272...
Page 368
NSAPI data structure 314 RqThrottleMin SAF parameter 117 magnus.conf directive 273 request_get_vs rules API function 175 for editing obj.conf 44 request_header API function 175 REQUEST_METHOD environment variable 136 request_stat_path API function 176 SAF behavior request_translate_uri for each directive 131 API function 177 SAFs request-handling process 21 alphabetical list 351...
Page 369
initialization directives in magnus.conf 241 NSAPI data structure 312 instructions for using plugins 124 resolving the IP address of 177, 178 instructions in obj.conf 27 SAF parameter 117 killing process of 279 Session->client modifying 19 NSAPI data structure 314 processing non-default objects 36 session_dns request handling 22 API function 177...
Page 370
sprintf, see util_sprintf strip-params function 63 srvhdrs subdir parameter 64 field in request parameter 118 symbolic links finding 68 settings in magnus.conf 281 syntax SSL2 directives in obj.conf 27 determining if enabled 300 for editing obj.conf 44 mime.types file 322 ssl2 attribute 300 system_errmsg ssl2ciphers attribute 301...
Page 371
systhread_newkey API function 191 determining if enabled 301 systhread_setdata tls attribute 301 API function 192 TLS rollback systhread_sleep determining if enabled 301 API function 192 tlsrollback attribute 301 systhread_start trailer parameter 88 API function 193 type parameter 79, 81, 83, 319 systhread_timerset type-by-exp function 81 API function 193...
Page 372
user home directories util_strncasecmp symbolic links and 68 API function 204 user parameter 99 util_uri_escape API function 204 user variable 295 util_uri_is_evil userdb parameter 51 API function 205 USERDBUSERDB element 306 util_uri_parse userfile parameter 53 API function 205 userfn parameter 51 util_uri_unescape util_can_exec API function 206...
Page 373
vs_get_id API function 210 vs_get_mime_type API function 211 vs_lookup_config_var API function 211 vs_register_cb API function 212 vs_set_data API function 212 vs_translate_uri API function 213 VSCLASS element 303 definition in server.dtd file 292 vsnprintf, see util_vsnprintf vsprintf, see util_vsprintf webapps_enable variable 295 webapps_file variable 295 weekday 327 wildcard patterns 325...
Need help?
Do you have a question about the NETSCAPE ENTERPRISE SERVER 6.1 - NSAPI PROGRAMMER GUIDE and is the answer not in the manual?
Questions and answers