Netscape ENTERPRISE SERVER 6.0 - NSAPI PROGRAMMER GUIDE Manual

Nsapi
Table of Contents

Advertisement

Quick Links

NSAPI Programmer's Guide
Netscape Enterprise Server
Version 6.0
November 2001

Advertisement

Table of Contents
loading
Need help?

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

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.
  • Page 3: Table Of Contents

    Contents About This Book ............. . . 15 Chapter 1 Basics of Server Operation .
  • Page 4 Service ................37 AddLog .
  • Page 5 ssl-logout ................73 unix-uri-clean .
  • Page 6 sn (session) ............... . 113 rq (request) .
  • Page 7 fc_open ................142 fc_close .
  • Page 8 protocol_start_response ............. 167 protocol_status .
  • Page 9 util_env_find ..............192 util_env_free .
  • Page 10 Installing the Example ............. . 219 Source Code .
  • Page 11 Language Issues ..............260 AdminLanguage .
  • Page 12 LogFlushInterval ..............273 LogVerbose .
  • Page 13 User Database Selection ..............296 The Netscape LDAP Schema .
  • Page 14 Appendix F Dynamic Results Caching Functions ....... . 325 dr_cache_destroy ..............326 dr_cache_init .
  • Page 15: About This Book

    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 •...
  • Page 17: Chapter 1 Basics Of Server Operation

    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 .
  • Page 18: Configuration Files

    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.
  • Page 19: Obj.conf

    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.
  • Page 20: Dynamic Reconfiguration

    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...
  • Page 22: Steps In The Request Handling Process

    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.
  • Page 23: Directives For Handling Requests

    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...
  • Page 25: Chapter 2 Syntax And Use Of Obj.conf

    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...
  • Page 26: Summary Of The Directives

    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.
  • Page 29: The Object Tag

    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.
  • Page 30: Object That Use The Ppath Attribute

    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.
  • Page 31: Variables Defined In Server.xml

    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.
  • Page 32: Flow Of Control In Obj.conf

    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.
  • Page 33: How The Server Knows To Process Other Objects

    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"...
  • Page 34: Pathcheck

    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...
  • Page 35: Objecttype

    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.
  • Page 36: Forcing The Type

    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...
  • Page 37: Service

    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...
  • Page 39: Default Service Directive

    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.
  • Page 40: Addlog

    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.”...
  • Page 41: Syntax Rules For Editing Obj.conf

    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 .
  • Page 42: Separators

    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.
  • Page 43: About Obj.conf Directive Examples

    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...
  • Page 45: Chapter 3 Predefined Safs And The Request Handling Process

    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...
  • Page 47: The Bucket Parameter

    The bucket Parameter Table 3-1 Available Server Application Functions (SAFs) Per Directive Service Stage add-footer add-header append-trailer imagemap index-common index-simple key-toosmall list-dir make-dir query-handler remove-dir remove-file rename-file send-cgi send-file send-range send-shellcgi send-wincgi service-dump shtml_send stats-xml upload-file AddLog Stage common-log flex-log record-useragent Error Stage send-error...
  • Page 48: Authtrans Stage

    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;...
  • Page 49: Basic-Auth

    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...
  • Page 51: Basic-Ncsa

    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.
  • Page 52: Get-Sslid

    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...
  • Page 53: Nametrans Stage

    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.
  • Page 54: Assign-Name

    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...
  • Page 55: Document-Root

    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.
  • Page 56: Home-Page

    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...
  • Page 57: Pfx2Dir

    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.
  • Page 59: Redirect

    NameTrans Stage NameTrans fn=pfx2dir from=/icons/happy dir=/users/nikki/images The third example shows the use of the parameter. The find-pathinfo-forward server-name resource is translated to the physical pathname http:// /cgi-bin/ resource. /export/home/cgi-bin/ NameTrans fn="pfx2dir" find-pathinfo-forward="" from="/cgi-bin" dir="/export/home/cgi-bin" name="cgi" redirect Applicable in -class directives. NameTrans function lets you change URLs and send the updated URL to the redirect...
  • Page 60: Strip-Params

    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.
  • Page 61: Pathcheck Stage

    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.
  • Page 62: Check-Acl

    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. •...
  • Page 63: Deny-Existence

    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...
  • Page 64: Find-Links

    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.
  • Page 65: Find-Pathinfo

    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.
  • Page 67: Load-Config

    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...
  • Page 69: Nt-Uri-Clean

    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.
  • Page 70: Ntcgicheck

    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, “//”...
  • Page 71: Require-Auth

    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...
  • Page 72: Set-Virtual-Index

    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.
  • Page 73: Ssl-Logout

    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...
  • Page 74: Objecttype Stage

    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.
  • Page 75: Force-Type

    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.
  • Page 76: Set-Default-Type

    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...
  • Page 77: Shtml-Hacktype

    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.
  • Page 78: Type-By-Extension

    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 “;...
  • Page 79: Service Stage

    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 .
  • Page 82: Add-Footer

    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.
  • Page 83: Add-Header

    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.
  • Page 84: Append-Trailer

    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"...
  • Page 85: Imagemap

    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...
  • Page 86: Index-Common

    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.
  • Page 88: Index-Simple

    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.
  • Page 89: Key-Toosmall

    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.
  • Page 90: List-Dir

    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.
  • Page 91: Make-Dir

    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...
  • Page 92: Remove-Dir

    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...
  • Page 93: Remove-File

    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.
  • Page 94: Rename-File

    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...
  • Page 95: Send-Cgi

    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.
  • Page 97: Send-File

    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/*"...
  • Page 99: Send-Range

    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...
  • Page 100: Send-Wincgi

    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...
  • Page 101: Service-Dump

    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...
  • Page 102: Shtml_Send

    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...
  • Page 103: Stats-Xml

    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...
  • Page 104: Upload-File

    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.
  • Page 105: Addlog Stage

    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: •...
  • Page 106: Flex-Log

    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...
  • Page 107: 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.
  • Page 108: Error Stage

    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.
  • Page 109: Qos-Error

    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.
  • Page 111: Chapter 4 Creating Custom Safs

    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.
  • Page 112: The Saf Interface

    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...
  • Page 113: Sn (Session)

    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.
  • Page 115: Result Codes

    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.
  • Page 116: Write The Source Code

    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.
  • Page 117: Compile And Link

    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.
  • Page 118: Linker Commands And Options For Generating A Shared Object

    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.
  • Page 119: Compiler Flags

    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.
  • Page 120: Load And Initialize The Saf

    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/ •...
  • Page 121: Instruct The Server To Call The Safs

    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.
  • Page 123: Reconfigure The Server

    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.
  • Page 124: Parameter Block Manipulation Routines

    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: •...
  • Page 125: Memory Management

    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.
  • Page 126: Network I/O

    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.
  • Page 127: Enterprise Serverutilities

    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.
  • Page 128: Required Behavior Of Safs For Each Directive

    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 •...
  • Page 129: Init Safs

    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. •...
  • Page 130: Nametrans Safs

    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...
  • Page 131: Error Safs

    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 •...
  • Page 132 CGI to NSAPI Conversion Table 4-6 CGI getenv() NSAPI AUTH_TYPE pblock_findval("auth-type", rq->vars); AUTH_USER pblock_findval("auth-user", rq->vars); CONTENT_LENGTH pblock_findval("content-length", rq->headers); CONTENT_TYPE pblock_findval("content-type", rq->headers); GATEWAY_INTERFACE "CGI/1.1" HTTP_* pblock_findval( "*", rq->headers); (* is lower-case, dash replaces underscore) PATH_INFO pblock_findval("path-info", rq->vars); PATH_TRANSLATED pblock_findval("path-translated", rq->vars); QUERY_STRING pblock_findval("query", rq->reqpb);...
  • Page 133 CGI to NSAPI Conversion Table 4-6 CGI getenv() NSAPI HTTPS_SECRETKEYSIZE pblock_findval("secret-keysize", sn->client); QUERY pblock_findval( query", rq->reqpb); (GET only, POST puts query string in entity-body data) SERVER_URL http_uri2url_dynamic("","", sn, rq); Chapter 4 Creating Custom SAFs...
  • Page 134 CGI to NSAPI Conversion Netscape Enterprise Server NSAPI Programmer’s Guide • November 2001...
  • Page 135: Chapter 5 Nsapi Function Reference

    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,”...
  • Page 136: Calloc

    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),...
  • Page 137: Condvar_Init

    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.
  • Page 138: Condvar_Notify

    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.
  • Page 139: Condvar_Wait

    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.
  • Page 140: Crit_Exit

    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.
  • Page 141: Crit_Terminate

    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.
  • Page 142: Fc_Open

    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).
  • Page 143: Fc_Close

    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;...
  • Page 144: Filebuf_Close

    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.
  • Page 145: Filebuf_Open

    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.
  • Page 146: Free

    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.
  • Page 147: Func_Exec

    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...
  • Page 148: Log_Error

    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...
  • Page 149: Malloc

    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.
  • Page 150: Net_Ip2Host

    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.”...
  • Page 151: Net_Write

    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.
  • Page 152: Netbuf_Close

    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.
  • Page 153: Netbuf_Grab

    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...
  • Page 154: Param_Create

    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.
  • Page 155: Pblock_Copy

    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...
  • Page 156: Pblock_Dup

    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.
  • Page 157: Pblock_Findval

    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...
  • Page 158: Pblock_Nninsert

    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 .
  • Page 159: Pblock_Pb2Env

    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...
  • Page 160: Pblock_Pinsert

    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.
  • Page 161: Pblock_Remove

    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...
  • Page 162: Perm_Calloc

    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.
  • Page 163: Perm_Malloc

    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);...
  • Page 164: Perm_Realloc

    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...
  • Page 165: Prepare_Nsapi_Thread

    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.
  • Page 166: Protocol_Dump822

    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);...
  • Page 167: Protocol_Start_Response

    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...
  • Page 168: Protocol_Status

    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.
  • Page 169: Protocol_Uri2Url

    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);...
  • Page 170: Realloc

    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);...
  • Page 171: Request_Get_Vs

    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.
  • Page 172: Request_Stat_Path

    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.
  • Page 173: Request_Translate_Uri

    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);...
  • Page 174: Session_Maxdns

    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.”...
  • Page 175: Shexp_Casecmp

    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.
  • Page 176: Shexp_Match

    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;...
  • Page 177: Shexp_Valid

    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.
  • Page 178: System_Errmsg

    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 .
  • Page 179: System_Flock

    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.
  • Page 180: System_Fopenrw

    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.
  • Page 181: System_Fread

    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...
  • Page 182: System_Fwrite_Atomic

    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...
  • Page 183: System_Gmtime

    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.
  • Page 184: System_Lseek

    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.
  • Page 185: System_Rename

    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.
  • Page 186: Systhread_Attach

    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.
  • Page 187: Systhread_Getdata

    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...
  • Page 188: Systhread_Setdata

    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...
  • Page 189: Systhread_Start

    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...
  • Page 190: Util_Can_Exec

    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.
  • Page 191: Util_Chdir2Path

    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...
  • Page 192: Util_Env_Find

    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.
  • Page 193: Util_Env_Replace

    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);...
  • Page 194: Util_Getline

    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.
  • Page 195: Util_Is_Mozilla

    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 >...
  • Page 196: Util_Itoa

    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.
  • Page 197: Util_Sh_Escape

    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.
  • Page 198: Util_Sprintf

    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...
  • Page 199: Util_Strftime

    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...
  • Page 200: 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);...
  • Page 201: Util_Uri_Is_Evil

    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...
  • Page 202: Util_Uri_Unescape

    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.
  • Page 203: Util_Vsprintf

    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...
  • Page 204: Vs_Alloc_Slot

    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*...
  • Page 205: Vs_Get_Default_Httpd_Object

    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 .
  • Page 206: Vs_Get_Httpd_Objset

    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).
  • Page 207: Vs_Get_Mime_Type

    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);...
  • Page 208: Vs_Register_Cb

    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...
  • Page 209: Vs_Translate_Uri

    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...
  • Page 211: Chapter 6 Examples Of Custom Safs

    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.”...
  • Page 212: Examples In The Build

    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...
  • Page 213: Authtrans Example

    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.
  • Page 214: Source Code

    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"...
  • Page 215: Nametrans Example

    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;...
  • Page 216: Installing The Example

    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...
  • Page 217: Source Code

    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);...
  • Page 218 NameTrans Example #include "base/util.h" /* is_mozilla */ #include "frame/protocol.h" /* protocol_status */ #include "base/shexp.h" /* shexp_cmp */ #ifdef __cplusplus extern "C" #endif NSAPI_PUBLIC int https_redirect(pblock *pb, Session *sn, Request *rq) /* Server Variable */ char *ppath = pblock_findval("ppath", rq->vars); /* Parameters */ char *from = pblock_findval("from", pb);...
  • Page 219: Pathcheck Example

    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);...
  • Page 220: Source Code

    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());...
  • Page 222: Objecttype Example

    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;...
  • Page 223: Installing The Example

    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.
  • Page 224: Service Example

    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;...
  • Page 225: Installing The Example

    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.
  • Page 227: More Complex Service Example

    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...
  • Page 228: Addlog Example

    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...
  • Page 229 AddLog Example NSAPI_PUBLIC void brief_terminate(void *parameter) system_fclose(logfd); logfd = SYS_ERROR_FD; #ifdef __cplusplus extern "C" #endif NSAPI_PUBLIC int brief_init(pblock *pb, Session *sn, Request *rq) /* Parameter */ char *fn = pblock_findval("file", pb); if(!fn) { pblock_nvinsert("error", "brief-init: please supply a file name", pb); return REQ_ABORTED;...
  • Page 230: Quality Of Service Examples

    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 234 Quality of Service Examples PRBool ok = PR_TRUE; PRInt32 vs_bw = 0, vs_bwlim = 0, vs_bw_ef = 0, vs_conn = 0, vs_connlim = 0, vs_conn_ef = 0, vsc_bw = 0, vsc_bwlim = 0, vsc_bw_ef = 0, vsc_conn = 0, vsc_connlim = 0, vsc_conn_ef = 0, srv_bw = 0, srv_bwlim = 0, srv_bw_ef = 0, srv_conn = 0, srv_connlim = 0, srv_conn_ef = 0;...
  • 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) &&...
  • Page 237: Chapter 7 Syntax And Use Of Magnus.conf

    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...
  • Page 238: Init Safs

    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 .
  • Page 239: Enterprise Servercindex-Init

    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>...
  • Page 241: Define-Perf-Bucket

    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,”...
  • Page 242: Dns-Cache-Init

    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 “] ” •...
  • Page 247: Flex-Rotate-Init

    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...
  • Page 248: Init-Cgi

    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.
  • Page 249: Init-Clf

    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.
  • Page 251: Init-Uhome

    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...
  • Page 252: Nt-Console-Init

    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.
  • Page 253: Perf-Init

    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.
  • Page 254: Register-Http-Method

    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.
  • Page 255: Stats-Init

    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...
  • Page 256: Thread-Pool-Init

    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.
  • Page 257: Server Information

    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 •...
  • Page 258: Mtahost

    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.
  • Page 259: Tempdir

    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...
  • Page 260: Language Issues

    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.
  • Page 261: Clientlanguage

    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.
  • Page 262: Dns

    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.
  • Page 264: Connqueuesize

    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.
  • Page 265: Keepalivetimeout

    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.
  • Page 266: Maxprocs (Unix Only)

    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.
  • Page 267: Rqthrottlemin

    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.
  • Page 268: Terminatetimeout

    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.
  • Page 269: Nativepoolstacksize

    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 •...
  • Page 270: Cgi

    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.
  • Page 271: Cgiwaitpid (Unix Only)

    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...
  • Page 272: Error Logging And Statistic Collection

    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.
  • Page 273: Errorlogdateformat

    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.
  • Page 274: Acl

    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...
  • Page 275: Aclusercachesize

    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.
  • Page 276: Sslcacheentries

    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.”...
  • Page 277: Sslsessiontimeout

    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.
  • Page 278: Chunkedrequestbuffersize

    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).
  • Page 279: Miscellaneous

    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.
  • Page 280: Umask (Unix Only)

    Miscellaneous Umask (UNIX only) This directive specifies the umask value used by the NSAPI functions to open files in different modes. Valid System_fopenWA() System_fopenRW() values for this directive are standard UNIX umask values. For more information on these functions, see system_fopenWA in Chapter 5, “NSAPI Function Reference.”...
  • Page 281: Chapter 8 Virtual Server Configuration Files

    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 •...
  • Page 282: 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).
  • Page 283 The server.xml File nice CDATA #IMPLIED > ]> <SERVER legacyls="ls1"> <VARS accesslog="/nes60/https-server.example.com/logs/access"/> <LS id="ls1" ip="1.1.1.1" port="80" security="off" acceptorthreads="1"> <CONNECTIONGROUP id="group1" matchingip="default" servername="server.example.com" defaultvs="server.example.com"/> </LS> <LS id="ls2" ip="any" port="80" security="off" acceptorthreads="1"> <CONNECTIONGROUP id="group2" matchingip="default" servername="server2.example.com" defaultvs="server2.example.com"/> </LS> <MIME id="mime1" file="mime.types" /> <ACLFILE id="acl1"...
  • Page 284: Variables

    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.
  • Page 285: Format Of A Variable

    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.
  • Page 286: Using The Server Manager And Class Manager

    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>...
  • Page 287: Elements In Server.dtd And Server.xml

    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.
  • Page 288: Ls (Listen Socket)

    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...
  • Page 289: Connectiongroup

    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.
  • Page 290: Sslparams

    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.
  • Page 291: Mime

    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.
  • Page 292: Aclfile

    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.
  • Page 293: Vs (Virtual Server)

    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.
  • Page 294: Qosparams

    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.
  • Page 295: Userdb

    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.
  • Page 296: User Database Selection

    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.
  • Page 297: The Netscape Ldap Schema

    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...
  • Page 298: The Domain Component (Dc)Tree

    The Netscape LDAP Schema Underneath each organization, there must be two entries: organizationalUnit . A third, , can be present if device data is to ou=People ou=Groups ou=Devices be stored for the organization. Each user entry must have a unique value within a given organization.
  • Page 299: Appendix A Data Structure Reference

    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.
  • Page 300: Privatization Of Some Data Structures

    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.
  • Page 301: Pblock

    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;...
  • Page 302: Pb_Param

    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. •...
  • Page 303: Stat

    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;...
  • Page 304: Shmem_S

    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...
  • Page 307: Appendix B Mime Types

    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 •...
  • Page 308: Determining The Mime Type

    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 .
  • Page 309: What Does The Client Do With The Mime Type

    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...
  • Page 310: Syntax Of The Mime Types File

    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...
  • Page 313: Appendix C Wildcard Patterns

    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”) •...
  • Page 314: Wildcard Examples

    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...
  • Page 315: Appendix D Time Formats

    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.
  • Page 317: Appendix E Hypertext Transfer Protocol

    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.
  • Page 318: Requests

    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 •...
  • Page 319: Request Data

    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.
  • Page 321: Response Headers

    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.
  • Page 322: Buffered Streams

    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.
  • Page 326: Dr_Cache_Destroy

    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.
  • Page 328: Dr_Net_Write

    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 334 fc_close 145 fc_open 144 filebuf_buf2sd 145 filebuf_close 146 filebuf_getc 146 filebuf_open 147 filebuf_open_nostat 147 FREE 148 func_exec 149 func_find 149 log_error 150 magnus_atrestart 151 MALLOC 151 net_ip2host 152 net_read 153 net_write 153 netbuf_buf2sd 154 netbuf_close 154 netbuf_getc 154 Netscape Enterprise Server NSAPI Programmer’s Guide • November 2001...
  • Page 335 netbuf_grab 155 netbuf_open 156 param_create 156 param_free 156 pblock_copy 157 pblock_create 158 pblock_dup 158 pblock_find 158 pblock_findval 159 pblock_free 159 pblock_nninsert 160 pblock_nvinsert 160 pblock_pb2env 161 pblock_pblock2str 161 pblock_pinsert 162 pblock_remove 162 pblock_str2pblock 163 PERM_CALLOC 164 PERM_FREE 164 PERM_MALLOC 165 PERM_REALLOC 165 PERM_STRDUP 166 prepare_nsapi_thread 167...
  • Page 336 protocol_start_response 169 protocol_status 170 protocol_uri2url 171 protocol_uri2url_dynamic 171 REALLOC 172 request_get_vs 173 request_header 173 request_stat_path 174 request_translate_uri 175 session_dns 175 session_maxdns 176 shexp_casecmp 177 shexp_cmp 177 shexp_match 178 shexp_valid 179 STRDUP 179 system_errmsg 180 system_fclose 180 system_flock 181 system_fopenRO 181 system_fopenRW 182 system_fopenWA 182 Netscape Enterprise Server NSAPI Programmer’s Guide •...
  • Page 337 system_fread 183 system_fwrite 183 system_fwrite_atomic 184 system_gmtime 185 system_localtime 185 system_lseek 186 system_rename 187 system_ulock 187 system_unix2local 187 systhread_attach 188 systhread_current 188 systhread_getdata 189 systhread_newkey 189 systhread_setdata 190 systhread_sleep 190 systhread_start 191 systhread_timerset 191 util_can_exec 192 util_chdir2path 193 util_cookie_find 193 util_env_find 194 util_env_free 194 util_env_replace 195...
  • Page 338 util_hostname 196 util_is_mozilla 197 util_is_url 197 util_itoa 198 util_later_than 198 util_sh_escape 199 util_snprintf 199 util_sprintf 200 util_strcasecmp 200 util_strftime 201 util_strncasecmp 202 util_uri_escape 202 util_uri_is_evil 203 util_uri_parse 203 util_uri_unescape 204 util_vsnprintf 204 util_vsprintf 205 vs_alloc_slot 206 vs_get_data 206 vs_get_default_httpd_object 207 vs_get_doc_root 207 vs_get_httpd_objset 208 vs_get_id 208...
  • Page 339 vs_register_cb 210 vs_set_data 210 vs_translate_uri 211 Appendix G Alphabetical List of NSAPI Functions and Macros...
  • Page 340 Netscape Enterprise Server NSAPI Programmer’s Guide • November 2001...
  • Page 341 Appendix H Alphabetical List of Directives in magnus.conf ACLCacheLifetime 276 ACLGroupCacheSize 277 ACLUserCacheSize 277 AdminLanguage 263 AsyncDNS 264 CGIExpirationTimeout 272 CGIStubIdleTimeout 273 CGIWaitPid (UNIX Only) 273 ChildRestartCallback 281 ChunkedRequestBufferSize 280 ChunkedRequestTimeout 280 cindex-init 241 ClientLanguage 263 ConnQueueSize 266...
  • Page 342 DefaultCharSet 263 DefaultLanguage 263 define-perf-bucket 243 DNS 264 dns-cache-init 244 EarlyInit 246 ErrorLog 276 ErrorLogDateFormat 275 ExtraPath 260 flex-init 244 flex-rotate-init 249 HeaderBufferSize 266 HTTPVersion 281 Netscape Enterprise Server NSAPI Programmer’s Guide • November 2001...
  • Page 343 init-cgi 250 init-clf 251 init-uhome 253 IOTimeout 266 KeepAliveThreads 267 KeepAliveTimeout 267 KernelThreads 267 LateInit 255 ListenQ 268 load-modules 253 LogFlushInterval 275 LogVerbose 275 LogVsId 275 MaxCGIStubs 273 MaxKeepAliveConnections 268 MaxProcs (UNIX Only) 268 MaxRqHeaders 281 MinCGIStubs 273 MtaHost 260 Appendix H Alphabetical List of Directives in magnus.conf...
  • Page 344 NativePoolMaxThreads 271 NativePoolMinThreads 271 NativePoolQueueSize 272 NativePoolStackSize 271 NetSiteRoot 260 nt-console-init 254 perf-init 255 PidLog 276 pool-init 255 PostThreadsEarly 268 RcvBufSize 269 register-http-method 256 RqThrottle 269 RqThrottleMin 269 Security 278 ServerConfigurationFile 260 ServerID 260 ServerRoot 260 SndBufSize 269 Netscape Enterprise Server NSAPI Programmer’s Guide • November 2001...
  • Page 345 SSL3SessionTimeout 281 SSLCacheEntries 278 SSLClientAuthDataLimit 278 SSLClientAuthTimeout 279 SSLSessionTimeout 279 StackSize 269 stats-init 257 StrictHttpHeaders 270 TempDir 261 TempDirSecurity 261 TerminateTimeout 270 ThreadIncrement 270 thread-pool-init 258 Umask (UNIX only) 282 UseNativePoll (UNIX only) 270 UseOutputStreamSize 280 User 261 WincgiTimeout 274 Appendix H Alphabetical List of Directives in magnus.conf...
  • Page 346 Netscape Enterprise Server NSAPI Programmer’s Guide • November 2001...
  • Page 347 Appendix I Alphabetical List of Pre-defined SAFs SAFs, see Appendix H, “Alphabetical List of Directives in magnus.conf.” Init add-footer 85 add-header 86 append-trailer 87 assign-name 55 basic-auth 51 basic-ncsa 52 check-acl 64 common-log 107...
  • Page 348 deny-existence 65 document-root 57 find-index 66 find-links 67 find-pathinfo 67 flex-log 108 force-type 78 get-client-cert 68 get-sslid 54 home-page 58 imagemap 88 index-common 89 index-simple 91 Netscape Enterprise Server NSAPI Programmer’s Guide • November 2001...
  • Page 349 key-toosmall 91 list-dir 92 load-config 70 make-dir 93 nt-uri-clean 73 ntcgicheck 73 pfx2dir 58 qos-error 111 qos-handler 54 query-handler 95 Appendix I Alphabetical List of Pre-defined SAFs...
  • Page 350 record-useragent 109 redirect 60 remove-dir 96 remove-file 97 rename-file 97 require-auth 74 send-cgi 98 send-error 110 send-file 100 send-range 102 send-shellcgi 103 send-wincgi 103 service-dump 104 set-default-type 79 set-virtual-index 75 shtml-hacktype 80 shtml_send 103 ssl-check 75 ssl-logout 76 stats-xml 105 strip-params 61 Netscape Enterprise Server NSAPI Programmer’s Guide •...
  • Page 351 type-by-exp 80 type-by-extension 81 unix-home 61 unix-uri-clean 76 upload-file 106 Appendix I Alphabetical List of Pre-defined SAFs...
  • Page 352 Netscape Enterprise Server NSAPI Programmer’s Guide • November 2001...
  • Page 353 Index alphabetical reference magnus.conf variables 341 about this book 15 NSAPI functions 135 acceptlanguage attribute 293, 294 SAFs 347 acceptorthreads attribute 289 API functions CALLOC 136 accesslog variable 285 cinfo_find 136 condvar_init 137 magnus.conf directives 274 condvar_notify 138 related to USERDB object 296 condvar_terminate 138 acl parameter 62 condvar_wait 139...
  • Page 354 MALLOC 149 system_flock 179 net_ip2host 150 system_fopenRO 179 net_read 150 system_fopenRW 180 net_write 151 system_fopenWA 180 netbuf_buf2sd 151 system_fread 181 netbuf_close 152 system_fwrite 181 netbuf_getc 152 system_fwrite_atomic 182 netbuf_grab 153 system_gmtime 183 netbuf_open 153 system_localtime 183 param_create 154 system_lseek 184 param_free 154 system_rename 185 pblock_copy 155...
  • 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 364 HTTP 318 result codes 115 methods 20 return values 115 steps in handling 22 signature 112 writing new 23 require parameter 66 SCRIPT_NAME environment variable 132 require-auth function 71 search patterns 313 responses, HTTP 319 secret-keysize parameter 73 result codes 115 Secuity results caching plugin 325 magnus.conf directive 275...
  • 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...

This manual is also suitable for:

Enterprise server 6.0

Table of Contents