Summary of Contents for Netscape NETSCAPE ENTERPRISE SERVER 6.0 - NSAPI PROGRAMMER GUIDE
Page 1
NSAPI Programmer’s Guide Netscape Enterprise Server Version 6.0 November 2001...
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 , server.xml, and obj.conf magnus.conf...
Page 16
This chapter discusses examples of custom SAFs to use at each stage in the request handling process. • Chapter 7, “Syntax and Use of magnus.conf” This appendix discusses the variables you can set in the configuration file to configure the during initialization. magnus.conf •...
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 21
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 24
Writing New Server Application Functions Netscape Enterprise Server NSAPI Programmer’s Guide • November 2001...
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/Server4/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 27
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/Server4/docs" This example calls the function with a argument of...
Page 28
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 The Object Tag Directives in the file are grouped into objects that begin with an obj.conf tag and end with a tag. The default object provides <Object> </Object> instructions to the server about how to process requests by default. Each new object modifies the default object’s behavior.
The Object Tag <Object name="default"> NameTrans fn="pfx2dir" from="/cgi" dir="D:/netscape/server4/docs/mycgi" name="cgi" </Object> When that directive is executed, the server starts processing directives NameTrans in the object named <Object name="cgi"> more directives... </Object> Object that Use the ppath Attribute When the server finishes processing the directives in the default object, NameTrans the logical URL of the request will have been converted to a physical pathname.
Variables Defined in server.xml The URL server_name would be translated to http:// /internalplan1.html . However, suppose that D:/Netscape/Server4/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/Server4/docs/internalplan1.html.
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/server4/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 38
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.
Page 44
About obj.conf Directive Examples Netscape Enterprise Server NSAPI Programmer’s Guide • November 2001...
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 46
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 50
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 This function is provided for backward compatibility only. The NOTE 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/server4/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/server4/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 58
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...
NameTrans Stage 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. http://bigger/better/morepopular/ NameTrans fn=redirect from=/toopopular url=http://bigger/better/morepopular strip-params Applicable in -class directives. NameTrans function removes embedded semicolon-delimited parameters strip-params from the path.
PathCheck Stage If you want the server to scan the password file only once at startup, use the Init-class function init-uhome magnus.conf Parameters is the URL prefix to translate, usually “/~”. from is the subdirectory within the user’s home directory that subdir contains their web documents.
PathCheck Stage • denies access to directories with certain file system links find-links • locates extra path info beyond the file name for the find-pathinfo PATH_INFO CGI environment variable. • gets the authenticated client certificate from the SSL3 get-client-cert session. •...
PathCheck Stage Examples PathCheck fn=check-acl acl="*HRonly*" deny-existence Applicable in -class directives. PathCheck function sends a “not found” message when a client tries to deny-existence access a specified path. The server sends “not found” instead of “forbidden,” so the user cannot tell whether the path exists or not. Parameters (optional) is a wildcard pattern of the file-system path to path...
PathCheck Stage function does nothing if there is a query string, if the HTTP find-index method is not GET, or if the path is that of a valid file. Parameters is a comma-separated list of index file names to look for. Use index-names spaces only if they are part of a file name.
PathCheck Stage optional, common to all obj.conf functions bucket checkFileExistence check linked file for existence and abort request with 403 (forbidden) if this check fails. Examples PathCheck fn=find-links disable=sh dir=/foreign-dir PathCheck fn=find-links disable=so dir=public_html See Also init-uhome, unix-home find-pathinfo Applicable in -class directives.
Page 66
PathCheck Stage Parameters controls whether to actually try to get the certificate, or just test for its dorequest presence. If dorequest is absent the default value is 0. • 1 tells the function to redo the SSL3 handshake to get a client certificate, if the server does not already have the client certificate.
PathCheck Stage load-config Applicable in -class directives. PathCheck function searches for configuration files in document directories load-config and adds the file’s contents to the server’s existing configuration. These configuration files (also known as dynamic configuration files) specify additional access control information for the requested resource. Depending on the rules in the dynamic configuration files, the server might or might not allow the client to access the requested resource.
Page 68
PathCheck Stage For example, the following tag specifies that requests for resources in the <OBJECT> directory are subject to the access rules in the file D:/netscape/server4/docs my.nsconfig <Object ppath="D:/netscape/server4/docs/*"> PathCheck fn="load-config" file="my.nsconfig" descend=1 basedir="D:/netscape/server4/docs" </Object> If the resolves to a resource or directory that is higher in the NOTE ppath directory tree (or is in a different branch of the tree) than the base...
PathCheck Stage (optional) specifies base directory. This is the highest-level basedir directory for which requests will invoke the load-config function and is also the directory where the server starts searching for configuration files. If basedir is not specified, the base directory is assumed to be the root directory that results from translating the requested resource’s URL to a physical pathname.
PathCheck Stage tildeok if present, allows tilde”~” characters in URIs. This is a potential security risk on the Windows NT platform, where longfi~1.htm might reference longfilename.htm but does not go through the proper ACL checking. If present, “//” sequences are allowed. If present, “//”...
PathCheck Stage require-auth Applicable in -class directives. PathCheck function allows access to resources only if the user or group is require-auth authorized. Before this function is called, an authorization function (such as ) must be called in an directive. basic-auth AuthTrans If a user was authorized in an directive, and the...
PathCheck Stage set-virtual-index Applicable in -class directives. PathCheck function specifies a virtual index for a directory, which set-virtual-index determines the URL forwarding. The index can refer to a LiveWire application, a servlet in its own namespace, a Netscape Application Server applogic, and so on. is returned if none of the URIs listed in the from parameter match REQ_NOACTION the current URI.
PathCheck Stage The function returns if SSL is not enabled, or if the REQ_NOACTION secret-keysize parameter is not specified. If the secret keysize for the current session is less than the specified and the parameter is not specified, the secret-keysize bong-file function returns with a status of...
ObjectType Stage Parameters optional, common to all obj.conf functions bucket If present, “//” sequences are allowed. dotdirok Examples PathCheck fn=unix-uri-clean See Also nt-uri-clean ObjectType Stage directives determine the MIME type of the file to send to the client in ObjectType response to a request.
ObjectType Stage • allows you to define a default set-default-type charset , and for the response being sent back content-encoding content-language to the client. • requests that files are parsed for shtml-hacktype .htm .html server-parsed html commands. • sets the content-type header for the response based on the type-by-exp requested path.
ObjectType Stage Examples ObjectType fn=force-type type=text/plain ObjectType fn=force-type lang=en_US See Also type-by-extension, type-by-exp set-default-type Applicable in -class directives. ObjectType This function allows you to define a default , and charset content-encoding for the response being sent back to the client. content-language If the , and...
ObjectType Stage shtml-hacktype Applicable in -class directives. ObjectType function changes the content-type of any file shtml-hacktype .htm .html and returns . This provides magnus-internal/parsed-html REQ_PROCEED backward compatibility with server-side includes for files with .htm .html extensions. The function may also check the execute bit for the file on UNIX systems.
ObjectType Stage (optional) is the language assigned to a matching request (the lang content-language header). (optional) is the character set for the magnus-charset charset parameter in rq->srvhdrs. If the browser sent the Accept-charset header or its User-agent is mozilla/1.1 charset or newer, then append “;...
Service Stage If the extension of the requested resource is , the html type-by-extension file sets the type to . If the extension is , the function sets the type to text/html .txt text/plain Parameters optional, common to all obj.conf functions bucket Examples ObjectType fn=type-by-extension...
Page 80
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 81
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/server4/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 87
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 Enterprise Servercindex-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 Enterprise Servercindex-init, index-common key-toosmall Applicable in -class directives. Service This function is provided for backward compatibility only and was NOTE 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 96
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 98
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 47”). 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 110
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/server4/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 114
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 ns-httpd40.dll libraries) HPUX 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 HPUX -Wl,+b,dir,dir -blibpath:dir:dir 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 Compiling 3.x Plugins on AIX For AIX only, plugins built for 3.x versions of the server must be relinked to work with 4.x and 6.x versions. The files you need, which are in the server_root directory, are as follows: /plugins/nsapi/examples/ •...
Creating and Using Custom SAFs • is a comma-separated list of function names to be loaded from the funcs shared library. Function names are case-sensitive. You may use dash (-) in place of underscore (_) in function names. There should be no spaces in the function name list.
Page 122
Creating and Using Custom SAFs For example, if you define a new SAF you could just add AuthTrans PathCheck an appropriate directive in the default object. However, if you define a new SAF to be invoked only when the requested resource is in a particular Service directory or has a new kind of file extension, you would need to take extra steps.
Overview of NSAPI C Functions <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. See “Dynamic obj.conf Reconfiguration,” on page 20 for details. Test the SAF Test your SAF by accessing your server from a browser with a URL that triggers your function.
Overview of NSAPI C Functions This section provides an overview of the function categories available and some of the more commonly used routines. All the public routines are detailed in Chapter 5, “NSAPI Function Reference.” The main categories of NSAPI functions are: •...
Overview of NSAPI C Functions • sets the HTTP response status code and reason phrase protocol_status • sends the HTTP response and all HTTP headers to protocol_start_response the browser. Memory Management Memory management routines provide fast, platform-independent versions of the standard memory management routines.
Overview of NSAPI C Functions • closes a file. system_fclose • reads from a file. system_fread • writes to a file. system_fwrite • locks the given file before writing to it. This avoids system_fwrite_atomic interference between simultaneous writes by multiple processes or threads. Network I/O Network I/O functions provide platform-independent, thread-safe network I/O routines.
Overview of NSAPI C Functions Enterprise ServerUtilities Utility functions include platform-independent, thread-safe versions of many standard library functions (such as string manipulation) as well as new utilities useful for NSAPI. • (UNIX only) registers a user function to be called when the daemon_atrestart server is sent a restart signal (HUP) or at shutdown.
Required Behavior of SAFs for Each Directive • finds the document root for a virtual server. vs_get_doc_root • obtains a pointer to the virtual server class vs_get_httpd_objset configuration for a given virtual server. • finds the ID of a virtual server. vs_get_id •...
Required Behavior of SAFs for Each Directive • ObjectType SAFs • Service SAFs • Error SAFs • AddLog SAFs Init SAFs • Purpose: Initialize at startup. • Called at server startup and restart. • NULL • Initialize any shared resources such as files and global variables. •...
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 210
NSAPI Functions (in Alphabetical Order) Netscape Enterprise Server NSAPI Programmer’s Guide • November 2001...
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 221
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 226
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 231
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 232
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 233
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 235
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 236
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 H, “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 240
Init SAFs In common (fancy) indexing, the directory list shows the name, last modified date, size and description for each indexed file or directory. 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>...
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 243
Init SAFs The log file stays open until the server is shut down or restarted (at which time all logs are closed and reopened). NOTE If the server has AddLog stage directives that call , the flex-log flexible log file must be initialized by during server flex-init initialization.
Page 244
Init SAFs Specifies the size of the global log buffer. The default is buffer-size 8192. See the third flex-init example below. Specifies the maximum number of logging buffers to use. num-buffers The default is 1000. See the third flex-init example below.
Page 245
Init SAFs Table 7-1 Typical components of flex-init formatting Flex-log option Component Status %Req->srvhdrs.clf-status% Response content length %Req->srvhdrs.content-length% Response content type %Req->srvhdrs.content-type% Referer header \"%Req->headers.referer%\" User-agent header \"%Req->headers.user-agent%\" HTTP Method %Req->reqpb.method% HTTP URI %Req->reqpb.uri% HTTP query string %Req->reqpb.query% HTTP protocol version %Req->reqpb.protocol% Accept header %Req->headers.accept%...
Page 246
Init SAFs This will record the following items • ip or hostname, followed by the three characters “ - ” • the user name, followed by the two characters “ [” • the system date, followed by the two characters “] ” •...
Init SAFs Init fn=flex-init buffer-size=16384 num-buffers=2000 access="/usr/netscape/server4/https-servername/logs/access" format.access="%Ses->client.ip% - %Req->vars.auth-user% [%SYSDATE%] \"%Req->reqpb.clf-request%\" %Req->srvhdrs.clf-status% %Req->srvhdrs.content-length%" See Also flex-rotate-init, flex-log flex-rotate-init Enterprise ServerApplicable in -class directives. Init function configures log rotation for all log files on the flex-rotate-init server, including error logs and the , and common-log flex-log...
Init SAFs (optional) determines whether error logs are rotated. Values rotate-error are yes (the default) and no. (optional) specifies the file name of a user-supplied program rotate-callback to execute following log file rotation. The program is passed the post-rotation name of the rotated log file as its parameter. Example This example enables log rotation, starting at midnight and occurring every hour.
Init SAFs (optional) specifies the path to the CGI stub binary. If not cgistub-path Enterprise Server specified, looks in the following directories, in the following order, relative to the server instance’s config directory: ../private/Cgistub, then ../../bin/https/bin/Cgistub. Use the first directory to house an suid Cgistub (that is, a Cgistub owned by root which has the set-user-ID-on-exec bit set).
Page 250
Init SAFs NOTE If the server has an AddLog stage directive that calls common-log common log files must be initialized by during init-clf initialization. This function should only be called once. If it is called again, the NOTE new call will replace log file names from all previous calls. If you move, remove, or change the log file without shutting down or restarting the server, client accesses might not be recorded.
Init SAFs 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. Parameters (optional) specifies the full file system path to a file other pwfile...
Init SAFs is a comma separated list of the names of the functions in the funcs shared library or dynamic link library to be made available for use by other Init directives or by Service directives in obj.conf. The list should not contain any spaces. The dash (-) character may be used in place of the underscore (_) character in function names.
Init SAFs 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. Parameters flag to disable the use of system performance measurement disable via performance buckets.
Init SAFs NOTE Any memory you allocate from Init-class functions will be allocated as persistent memory, even if you use . The server cleans up MALLOC only the memory that is allocated while processing a request, and because Init-class functions are run before processing any requests, their memory is allocated globally.
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 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 sub-section lists the directives in that specify information about magnus.conf the server. They are: • ExtraPath • MtaHost • NetSiteRoot •...
Server Information 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 TempDir Specifies the directory on the local volume that the server uses for its temporary files. On UNIX, this directory must be owned by, and writable by, the user the server runs as. See also the directives User and TempDirSecurity. Syntax path TempDir...
Language Issues execute permissions to any CGI programs. The user account should not have write access to the configuration files. This ensures that in the unlikely event that someone compromises the server, they won’t be able to change configuration files and gain broader access to your machine.
DNS Lookup ClientLanguage For an international version of the server, this directive specifies the language for client messages (such as File Not Found). Values are (English), (French), (German) or (Japanese). Default The default is DefaultCharSet For an international version of the server, this directive specifies the default character set for the server.
Threads, Processes and Connections Default The default is directive specifies whether the server performs DNS lookups on clients that access the server. When a client connects to your server, the server knows the client’s IP address but not its host name (for example, it knows the client as 198.95.251.30, rather than its host name ).
Page 263
Threads, Processes and Connections • The process of adding new session threads is strictly limited by the value. RqThrottle • To avoid creating too many threads when the backlog increases suddenly (such as the startup of benchmark loads), the decision whether more threads are needed is made only once every 16 or 32 times a connection is made based on how many session threads already exist.
Threads, Processes and Connections ConnQueueSize Specifies the number of outstanding (yet to be serviced) connections that the web server can have. It is recommended that this value always be greater than the operating system limit for the maximum number of open file descriptors per process.
Threads, Processes and Connections KeepAliveTimeout This directive determines the maximum time that the server holds open an HTTP Keep-Alive connection or a persistent connection between the client and the server. The Keep-Alive feature for earlier versions of the server allows the client/server connection to stay open while the server processes the client request.
Threads, Processes and Connections Default MaxProcs (UNIX Only) Specifies the maximum number of processes that the server can have running simultaneously. If you don’t include in your file, the server MaxProcs magnus.conf defaults to running a single process. One process per processor is recommended if you are running in multi-process mode.
Threads, Processes and Connections There is additional discussion of this and other server configuration and performance tuning issues in the Netscape Enterprise Server Performance Tuning, Sizing, and Scaling Guide. Default RqThrottleMin Specifies the number of request processing threads that are created when the server is started.
Native Thread Pools TerminateTimeout Specifies the time that the server waits for all existing connections to terminate before it shuts down. Default 30 seconds 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.
Native Thread Pools On Windows NT, the default native pool is always being used and Enterprise Server uses fibers (user-scheduled threads) for initial request processing. Using custom additional pools on Windows NT introduces no additional overhead. The directives are: • NativePoolStackSize •...
This section lists the directives in that affect requests for CGI magnus.conf programs. The directives are: • 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.
CGIWaitPid (UNIX Only) For UNIX platforms, when is set to on, the action for the SIGCHLD CGIWaitPid signal is the system default action for the signal. If a NSAPI plugin fork/execs a child process, it should call with its child process when waitpid CGIWaitPid...
Error Logging and Statistic Collection Error Logging and Statistic Collection This section lists the directives in that affect error logging and the magnus.conf collection of server statistics. They are: • ErrorLog • ErrorLogDateFormat • LogFlushInterval • LogVerbose • LogVsId • PidLog ErrorLog directive specifies the directory where the server logs its errors.
Error Logging and Statistic Collection ErrorLogDateFormat directive specifies the date format that the server logs ErrorLogDateFormat use. Syntax format ErrorLogDateFormat The format can be any format valid for the C library function . See strftime Appendix D, “Time Formats.” Default %d/%b/%Y:%H:%M:%S LogFlushInterval This directive determines the log flush interval, in seconds, of the log flush thread.
To shut down your server, kill the base server process listed in the pid log file by using a signal. To tell your server to reread its configuration files and reopen -TERM its log files, use with the signal. kill -HUP If the file isn’t writable by the user account that the server uses, the server...
Security Default ACLUserCacheSize determines the number of users in the User Cache. ACLUserCacheSize Default ACLGroupCacheSize determines how many group IDs can be cached for a single ACLGroupCacheSize UID/cache entry. Default Security This section lists the directives in that affect server access and magnus.conf security issues for Enterprise Server.
Security 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 magnus.conf. For more information about enabling SSL for individual virtual servers, see Chapter 8, “Virtual Server Configuration Files.”...
Chunked Encoding SSLSessionTimeout directive controls SSL2 session caching. SSLSessionTimeout Syntax seconds SSLSessionTimeout 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.
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.”...
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) Number of acceptor threads for the listen socket. acceptorthreads The recommended value is the number of processors in the machine. The default is 1, legal values are 1 - 1024. (optional) The socket family type. The default is inet, legal family values are inet, inet6, and nca.
Elements in server.dtd and server.xml Tells the server what to put in the host name section of any servername URLs it sends to the client. This affects URLs the server automatically generates; it doesn’t affect the URLs for directories and files stored in the server. This name should be the alias name if your server uses an alias.
Elements in server.dtd and server.xml (optional) A space-separated list of the SSL3 ciphers used, ssl3tlsciphers with the prefix + to enable or - to disable, for example +rsa_des_sha. Allowed SSL3 values are rsa_rc4_128_md5 rsa3des_sha rsa_des_sha rsa_rc4_40_md5 rsa_rc2_40_md5 rsa_null_md5 Allowed TLS values are rsa_des_56_sha, rsa_rc4_56_sha (optional) Determines whether TLS is enabled.
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 296 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.
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 305
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 306
cinfo Netscape Enterprise Server NSAPI Programmer’s Guide • November 2001...
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 311
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 312
Sample MIME Types File Netscape Enterprise Server NSAPI Programmer’s Guide • November 2001...
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 one occurrence of a character between a and z. [a-z] Match any character except a or z. [^az] This expression, followed by another expression, removes any pattern matching the second expression. Wildcard Examples Table C-2 Wildcard examples Pattern...
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 316
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 320
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 323
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 324
Buffered Streams Netscape Enterprise Server NSAPI Programmer’s Guide • November 2001...
Page 325
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:...
Page 327
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 329
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.
Page 330
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 331
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 332
Netscape Enterprise Server NSAPI Programmer’s Guide • November 2001...
Page 333
Appendix G Alphabetical List of NSAPI Functions and Macros CALLOC 138 cinfo_find 138 condvar_init 139 condvar_notify 140 condvar_terminate 140 condvar_wait 141 crit_enter 141 crit_exit 142 crit_init 142 crit_terminate 143 daemon_atrestart 143...
Page 355
vs_alloc_slot 204 vs_get_data 204 cache vs_get_default_httpd_object 205 enabling memory allocation pool 253 vs_get_doc_root 205 CALLOC API function 136 vs_get_httpd_objset 206 vs_get_id 206 case sensitivity vs_get_mime_type 207 in obj.conf 41 vs_lookup_config_var 207 certificates vs_register_cb 208 settings in magnus.conf 275 vs_set_data 208 certmaps attribute 295 vs_translate_uri 209 append-trailer function 84...
Page 356
sessions and 300 crit_init API function 140 CLIENT_CERT environment variable 132 crit_terminate clientauth attribute 291 API function 141 ClientLanguage magnus.conf directive 261 field in session parameter 113 code parameter 109, 110 custom SAFs comments creating 111 in obj.conf 42 Common Log subsystem, initializing 249 common-log function 105 compiling custom SAFs 117...
Page 357
disable parameter 64 ErrorLog magnus.conf directive 272 disable-types parameter 68 errorlog attribute 294 magnus.conf directive 262 ErrorLogDateFormat magnus.conf directive 273 DNS lookup directives in magnus.conf 261 errors finding most recent system error 178 DNS names sending customized messages 109, 110 getting clients 302 escape parameter 59 dns-cache-init function 242...
Page 358
file name extensions funcs parameter 121, 252 MIME types 307 functions object type 35 NSAPI file parameter 68, 82, 83 reference 135 pre-defined SAFs 45 filebuf_buf2sd see also SAFs API function 142, 143 filebuf_close API function 144 filebuf_getc API function 144 filebuf_open -G option 120 API function 145...
Page 359
HTTPS_KEYSIZE environment variable 132 getting clients 302 HTTPS_SECRETKEYSIZE environment variable 133 ip attribute 288 HTTPVersion iponly function 105, 106 magnus.conf directive 279 HUP signal PidLog and 274 HyperText Transfer Protocol see HTTP KeepAliveTimeout magnus.conf directive 264, 265 KernelThreads magnus.conf directive 265 key-toosmall function 89 id attribute for ACLFILE element 292...
Page 360
log file memory allocation analyzer for 105, 106 pool-init function 253 log file format 244 memory management routines 125 log_error method parameter 66, 79 API function 148 mime attribute 293 logfileName parameter 243 MIME element 291 LogFlushInterval MIME types 307 magnus.conf directive 273 mime.types file 19, 307 logging...
Page 361
net_read API function 150 obj.conf 19 net_write adding directives for new SAFs 121 API function 151 case sensitivity 41 netbuf_buf2sd comments 42 API function 151 directive syntax 25 netbuf_close directives 25, 45 API function 152 directives summary 26 netbuf_getc flow of control 32 API function 152 OBJECT tag 29 netbuf_grab...
Page 362
parameter block pblock_pb2env manipulation routines 124 API function 159 SAF parameter 112 pblock_pblock2str parameters API function 159 for obj.conf directives 41 pblock_pinsert for SAFs 112 API function 160 path name pblock_remove converting Unix-style to local 185 API function 161 path names 42 pblock_str2pblock path parameter 57, 62, 63, 71, 92, 108 API function 161...
Page 363
API function 166 reference NSAPI protocol_set_finfo functions 135 API function 166 NSAPI data structures 299 protocol_start_response register-http-method function 254 API function 167 relink_36plugin file 120 protocol_status API function 168 REMOTE_ADDR environment variable 132 protocol_uri2url REMOTE_HOST environment variable 132 API function 169 REMOTE_IDENT environment variable 132 pwfile parameter 61 REMOTE_USER environment variable 132...
Page 365
SERVER_SOFTWARE environment variable 132 shexp_valid API function 177 SERVER_URL environment variable 133 shlib parameter 120, 251 servercertnickname attribute 290 shmem_s ServerConfigurationFile NSAPI data structure 304 magnus.conf directive 258 shtml_send function 102 ServerID magnus.conf directive 258 shtml-hacktype function 77 servername attribute 290 ShtmlMaxDepth parameter 102 ServerRoot magnus.conf directive 258...
Page 366
magnus.conf directive 276 API function 181 ssl-logout function 73 system_fwrite_atomic API function 182 SSLPARAMS element 290 system_gmtime SSLSessionTimeout API function 183 magnus.conf directive 277 system_localtime StackSize API function 183 magnus.conf directive 267 system_lseek stat API function 184 structure 303 system_rename state attribute 294 API function 185 statistic collection...
Page 367
allocating a key for 187 creating 189 mapping to other servers 57 getting a pointer to 186 translated to file path 27 getting data belonging to 187 url parameter 59 putting to sleep 188 urlhosts attribute 293 setting data belonging to 188 checking against subject pattern 296 setting interrupt timer 189 url-prefix parameter 59...
Page 368
API function 195 VARS element 287 util_is_url Virtual Server API function 195 selection for request processing 295 util_itoa virtual server routines 127 API function 196 virtual-index parameter 72 util_later_than VS (Virtual Server) element 293 API function 196 vs_alloc_slot util_sh_escape API function 204 API function 197 vs_get_data util_snprintf...
Need help?
Do you have a question about the NETSCAPE ENTERPRISE SERVER 6.0 - NSAPI PROGRAMMER GUIDE and is the answer not in the manual?
Questions and answers