Apache module mod_fastcgi

# Module mod_fastcgi

This 3rd party module provides support for the FastCGI protocol. FastCGI is a language independent, scalable, open extension to CGI that provides high performance and persistence without the limitations of server specific APIs.

FastCGI applications are not limited to a particular development language (the protocol is open). FastCGI application libraries currently exist for Perl, C, Java, Python, and TCL.

FastCGI applications use (TCP or Unix) sockets to communicate with the web server. This scalable architecture allows applications to run on the same platform as the web server or on many machines scattered across an enterprise network.

FastCGI applications are portable to other web server platforms. FastCGI is supported either directly or through commercial extensions by most popular web servers.

FastCGI applications are fast because they're persistent. There is no per-request startup and initialization overhead. This makes possible the development of applications which would otherwise be impractical within the CGI paradigm (e.g. a huge Perl script, or an application which requires a connection to one or more databases).

For more information on FastCGI, go to the FastCGI website. To receive FastCGI related announcements and notifications of module updates, send mail to fastcgi-announce-request@idle.com with "subscribe" in the Subject field. To participate in the discussion of `mod_fastcgi` and FastCGI application development, send mail to fastcgi-developers-request@idle.com with "subscribe" in the Subject field.

## Summary

For information about building and installing the module, see the INSTALL document that came with the distribution.

FastCGI applications under `mod_fastcgi` are defined as one of three types: static, dynamic, or external. They're configured using the FastCgiServer, FastCgiConfig, and FastCgiExternalServer directives respectively.

FastCGI static and dynamic applications are spawned and managed by the FastCGI Process Manager, fcgi-pm. The process manager is spawned by Apache at server initialization. External applications are presumed to be started and managed independently.

Apache must be configured to identify requests for FastCGI URIs. `mod_fastcgi` registers (with Apache) a handler type of `fastcgi-script` for this purpose.

To configure Apache to handle all files (within the scope of the directive) as FastCGI applications (e.g. for a fcgi-bin directory):

> `SetHandler fastcgi-script`

To configure Apache to handle all files (within the scope of the directive) with the specified extension(s) as FastCGI applications:

> `AddHandler fastcgi-script .fcg .fcgi .fpl`

Consult the Apache documentation for more information regarding these and other directives which affect request handling (such as `Action).`

Dynamic FastCGI applications require the `ExecCGI` option be enabled in the application's directory. `ExecCGI` can be enabled using either the `Options` or `ScriptAlias` directives.

## Notes

`mod_fastcgi` logs FastCGI application error (stderr) output to the server log associated with the request. Errors reported by the FastCGI process manager, fcgi-pm, are reported to the main server log (typically, logs/error_log).

To pass per-request environment variables to FastCGI applications, have a look at: `mod_env` (`SetEnv`, `PassEnv`, `UnSetEnv`), `mod_setenvif` (`BrowserMatch`, `BrowserMatchNoCase`, `SetEnvIf`, `SetEnvIfNoCase`), and `mod_rewrite` (if your feeling adventurous).

FastCGI application output is buffered by default. This is not the case for CGI scripts (under Apache 1.3). To override the default behavior, use the -flush option. Non-parsed header (nph-) scripts will be rejected by FastCGI simply as warning the behavior is different (create a symbolic link to the script without the "nph-" prefix if this poses a problem).

Redirects are handled similar to CGI. Location headers with values that begin with "/" are treated as internal-redirects; otherwise, they are treated as external redirects (302).

Session affinity (as well as distribution) should be achievable outside of `mod_fastcgi` using `mod_rewrite`. If you get this working, please post the details to fastcgi-developers@idle.com so they can be included here.

## FastCGI Specification Compliance

The FastCGI specification is not implemented in its entirety and I've deviated a bit as well resulting in some Apache specific features.

The Filter and Log Roles are not supported. The Filter Role has no place in Apache until the output of one handler can be piped into another (Apache 2.0 is expected to support this). The Log Role has some value, but I just haven't implemented it (if you have interest in it speak up).

Multiplexed requests are not supported. The FastCGI application library which provides the FastCGI protocol support within FastCGI applications does not currently support it (and thus doesn't have to be supported here). This may become a higher priority when `mod_fastcgi` is ported to NT (Apache is threaded on NT).

I don't believe any other existing FastCGI server implementation supports these features.

The Authorizer Role has three variations corresponding to each three related Apache specific request handling phases: Authentication, Authorization, and Access Control. `mod_fastcgi` sets up the (Apache specific) environment variable "FCGI_APACHE_ROLE" to indicate which Apache authorizer phase is being performed.

`mod_fastcgi` sends nearly all of the standard environment variables typically available to CGI/FastCGI request handlers including some explicitly precluded by the FastCGI specification; I didn't see the point to leaving them out. All headers returned by a FastCGI authentication application in a successful response (Status: 200) are passed to subprocesses (CGI/FastCGI invocations) as environment variables rather than just those prefixed by "`Variable-`" as the FastCGI specification calls for; I didn't see the point in leaving them out either. FastCGI specification compliant authorizer behaviour can be obtained by using the "`-compat`" option to the Auth server directives.

Custom failure responses from FastCGI authorizer applications are not (yet?) supported. See the ErrorDocument directive for a workaround (a FastCGI application can serve the document).

## Directives

- `FastCgiServer`
- `FastCgiConfig`
- `FastCgiExternalServer`
- `FastCgiIpcDir`
- `FastCgiSuexec`
- `FastCgiAuthenticator`
- `FastCgiAuthenticatorAuthoritative`
- `FastCgiAuthorizer`
- `FastCgiAuthorizerAuthoritative`
- `FastCgiAccessChecker`
- `FastCgiAccessCheckerAuthoritative`

## FastCgiServer

Syntax: | `FastCgiServer filename option option ...`
Context: | server config

The `FastCgiServer` directive defines filename as a static FastCGI application. If the filename does not begin with a slash (/) then it is assumed to be relative to the ServerRoot.

By default, the Process Manager will start one instance of the application with the default configuration specified (in parenthesis) below. Should a static application instance die for any reason `mod_fastcgi` will spawn another to replace it and log the event.

Option can be one of (case insensitive):

`-appConnTimeout n (15 seconds)`
  The number of seconds to wait for a connection to the FastCGI application to complete. If the timeout expires, a SERVER_ERROR results. This is the amount of time used in a `select()` to write to the file descriptor returned by a non-blocking `connect().` Unix sockets appear to be handled differently than TCP sockets on many platforms. TCP sockets will become writeable as soon as a slot in the listen-queue is obtained (the three-way handshake completes), but before the connection is `accept()`ed by the application. Unix sockets appear to need the connection to be `accept()`ed before becoming writeable. If set to 0, a blocking `connect()` is used and the timeout is OS dependent. Non-blocking `connect()`s can be troublesome and will likely become optional rather than the default in the next release.
`-initial-env name[=value] none`
  A name-value pair to be passed in the initial environment when instances of the application are spawned. To pass a variable from the Apache environment, don't provide the "=" (if the variable isn't actually in the environment, it will be defined without a value). To define a variable without a value, provide the "=" without any value. The option can be used repeatedly.
`-init-start-delay n (1 second)`
  The minimum number of seconds between the spawning of instances of this application. This delay decreases the demand placed on the system at server initialization.
`-flush none`
  Force a write to the client as data is received from the application. By default, `mod_fastcgi` buffers data in order to free the application as quickly as possible.
`-listen-queue-depth n (100)`
  The depth of listen() queue (also known as the backlog) shared by all of the instances of this application. A deeper listen queue allows the server to cope with transient load fluctuations without rejecting requests; it does not increase throughput. Adding additional application instances may increase throughput/performance, depending upon the application and the host.
`-processes n (1)`
  The number of instances of the application to spawn at server initialization.
`-priority n (0)`
  The process priority to be assigned to the application instances (using `setpriority()`).
`-port n none`
  The TCP port number (1-65535) the application will use for communication with the web server. This option makes the application accessible from other machines on the network (as well as this one). The `-socket` and `-port` options are mutually exclusive.
`-restart-delay n (5 seconds)`
  The minimum number of seconds between the respawning of failed instances of this application. This delay prevents a broken application from soaking up too much of the system.
`-socket filename gen'd`
  The filename of the Unix domain socket that the application will use for communication with the web server. The module creates the socket within the directory specified by `FastCgiIpcDir`. This option makes the application accessible to other applications (e.g. `cgi-fcgi`) on the same machine or via an external FastCGI application definition (`FastCgiExternalServer`). If neither the `-socket` nor the `-port` options are given, the module generates a Unix domain socket filename. The `-socket` and `-port` options are mutually exclusive.

## FastCgiConfig

Syntax: | `FastCgiConfig option option ...`
Context: | server config

The `FastCgiConfig` directive defines the default parameters for dynamic FastCGI applications. It currently has a "server config" context, which means there can be only one FastCgiConfig directive. Eventually it will have a "directory" context. This directive does not affect static or external applications in any way.

Dynamic applications are not started at server initialization, but upon demand. If the demand is heavy, additional application instances are started. As the demand fades, application instances are killed off. Many of the options govern this process.

Option can be one of (case insensitive):

`-appConnTimeout n (15 seconds)`
  The number of seconds to wait for a connection to the FastCGI application to complete. If the timeout expires, a SERVER_ERROR results. The `startDelay` must be smaller than `appConnTimeout` to be effective. This is the amount of time used in a `select()` to write to the file descriptor returned by a non-blocking `connect().` Unix sockets appear to be handled differently than TCP sockets on many platforms. TCP sockets will become writeable as soon as a slot in the listen-queue is obtained (the three-way handshake completes), but before the connection is `accept()`ed by the application. Unix sockets appear to need the connection to be `accept()`ed before becoming writeable. If set to 0, a blocking `connect()` is used and the timeout is OS dependent. Non-blocking `connect()`s can be troublesome and will likely become optional rather than the default in the next release.
`-autoUpdate none`
  This option causes mod_fastcgi to check the age of the application on disk before processing each request. If the application is more recent, the process manager is notified and all running instances of the application are killed off. In general, its preferred that this type of functionality be built-in to the application (e.g. every 100th request it checks to see if there's a newer version on disk and exits if so). There may be an outstanding problem (bug) when this option is used with `-restart`.
`-gainValue n (0.5)`
  A floating point value between 0 and 1 that is used as an exponent in the computation of the exponentially decayed connection times load factor of the currently running dynamic FastCGI applications. Old values are scaled by (1 -`gainValue`), so making it smaller weights them more heavily compared to the current value, which is scaled by `gainValue`.
`-initial-env name[=value] none`
  A name-value pair to be passed in the initial environment when instances of the application are spawned. To pass a variable from the Apache environment, don't provide the "=" (if the variable isn't actually in the environment, it will be defined without a value). To define a variable without a value, provide the "=" without any value. The option can be used repeatedly.
`-init-start-delay n (1 second)`
  The minimum number of seconds between the spawning of instances of this application. This delay decreases the demand placed on the system at server initialization.
`-killInterval n (300 seconds)`
  The killInterval determines how often the dynamic application instance killing policy is implemented within the process manager. Lower numbers result in a more aggressive policy, higher numbers a less aggressive policy.
`-listen-queue-depth n (100)`
  The depth of listen() queue (also known as the backlog) shared by all of the instances of this application. A deeper listen queue allows the server to cope with transient load fluctuations without rejecting requests; it does not increase throughput. Adding additional application instances may increase throughput/performance, depending upon the application and the host.
`-maxClassProcesses n (10)`
  The maximum number of dynamic FastCGI application instances allowed to run for any one FastCGI application.
`-maxProcesses n (50)`
  The maximum total number of dynamic FastCGI application instances allowed to run at any one time.
`-minProcesses n (5)`
  The minimum total number of dynamic FastCGI application instances allowed to run at any one time without being killed off by the process manager (due to lack of demand).
`-multiThreshhold n (50)`
  An integer between 1 and 100 used to determine whether any one instance of a FastCGI application should be terminated. If the application has more than one instance currently running, this attribute will be used to decide whether one of them should be terminated. If only one instance remains, `singleTHreshhold` is used instead.
`-priority n (0)`
  The process priority to be assigned to the application instances (using `setpriority()`).
`-processSlack n (5 seconds)`
  If the sum of all currently running dynamic FastCGI applications and exceeds `maxProcesses - processSlack`, the process manager invokes the killing policy. This is to improve performance at higher loads by killing the some of the most inactive application instances before reaching `maxProcesses`.
`-restart none`
  This option causes the process manager to restart dynamic applications upon failure (similar to static applications).
`-restart-delay n (5 seconds)`
  The minimum number of seconds between the respawning of failed instances of this application. This delay prevents a broken application from soaking up too much of the system.
`-singleThreshhold n (10)`
  An integer between 1 and 100 used to determine whether the last instance of a FastCGI application can be terminated. If the process manager computed load factor for the application is lower than the specified threshold, the last instance is terminated. In order to make your executables run in the "idle" mode for the long time, you would specify value closer to 1, however if memory or CPU time is of primary concern, a value closer to 100 would be more applicable.
`-startDelay n (3 seconds)`
  The number of seconds the web server waits patiently while trying to connect to a dynamic FastCGI application. If the interval expires, the process manager is notified with hope it will start another instance of the application. The `startDelay` must be smaller than `appConnTimeout` to be effective.
`-updateInterval n (300 seconds)`
  The updateInterval determines how often statistical analysis is performed to determine the fate of dynamic FastCGI applications.

## FastCgiExternalServer

Syntax: | `FastCgiExternalServer filename -host hostname:port [-appConnTimeout n]`
| `FastCgiExternalServer filename -socket filename [-appConnTimeout n]`
Context: | server config

The `FastCgiExternalServer` directive defines filename as an external FastCGI application. If the filename does not begin with a slash (/) then it is assumed to be relative to the ServerRoot.

External FastCGI applications are not started by the process manager, they are presumed to be started and managed "external" to Apache and mod_fastcgi. The FastCGI devkit provides a simple tool for starting FastCGI applications independent of the server.

`-appConnTimeout n (15 seconds)`
  The number of seconds to wait for a connection to the FastCGI application to complete. If the timeout expires, a SERVER_ERROR results. This is the amount of time used in a `select()` to write to the file descriptor returned by a non-blocking `connect().` Unix sockets appear to be handled differently than TCP sockets on many platforms. TCP sockets will become writeable as soon as a slot in the listen-queue is obtained (the three-way handshake completes), but before the connection is `accept()`ed by the application. Unix sockets appear to need the connection to be `accept()`ed before becoming writeable.
`-flush none`
  Force a write to the client as data is received from the application. By default, `mod_fastcgi` buffers data in order to free the application as quickly as possible.
`-host hostname:port none`
  The hostname or IP address and TCP port number (1-65535) the application uses for communication with the web server. The `-socket` and `-host` options are mutually exclusive.
`-socket filename none`
  The filename of the Unix domain socket the application uses for communication with the web server. The filename is relative to the `FastCgiIpcDir`. The `-socket` and `-port` options are mutually exclusive.

## FastCgiIpcDir

Syntax: | `FastCgiIpcDir directory`
Default: | `FastCgiIpcDir /tmp/fcgi`
Context: | server config

The `FastCgiIpcDir` directive specifies directory as the place to store (and find, in the case of external FastCGI applications) the Unix socket files used for communication between the applications and the web server. If the directory does not begin with a slash (/) then it is assumed to be relative to the ServerRoot. If the directory doesn't exist, an attempt is made to create it with appropriate permissions. Do not specify a directory that is not on a local filesystem! If you use the default directory (or another directory within `/tmp`), `mod_fastcgi` will break if your system periodically deletes files from `/tmp`.

The `FastCgiIpcDir` directive must precede any `FastCgiServer` or `FastCgiExternalServer` directives (which make use of Unix sockets). The directory must be readable, writeable, and executable (searchable) by the web server, but otherwise should not be accessible to anyone.

## FastCgiSuexec

Syntax: | `FastCgiSuexec On | Off | filename`
Default: | `FastCgiSuexec Off`
Context: | server config

The `FastCgiSuexec` directive is used to enable support for an suexec-wrapper. `FastCgiSuexec` requires suexec be enabled in Apache (for CGI). To use the same suexec-wrapper in use by Apache, set `FastCgiSuexec` to On. To use a different suexec-wrapper, specify the filename of the suexec-wrapper. If the filename does not begin with a slash (/) then it is assumed to be relative to the ServerRoot.

When `FastCgiSuexec` is enabled, the location of static or external FastCGI application definitions is important. They inherit their user and group from the `User` and `Group` directives in the virtual server in which they were defined. `User` and `Group` directives should precede FastCGI application definitions. Note that this does not limit the FastCGI application to the virtual server in which they were defined, the application is allowed to service requests from any virtual server with the same user and group. If a request is received for a FastCGI application without an existing matching definition running with the correct user and group, a dynamic instance of the application is started with the correct user and group. This can lead to multiple copies of the same application running with different user/group. If this is a problem, preclude navigation to the application from other virtual servers or configure the virtual servers with the same User and Group.

See the Apache documentation for more information about suexec (make sure you fully understand the security implications).

## FastCgiAuthenticator

Syntax: | `FastCgiAuthenticator filename [-compat]`
Context: | directory

The `FastCgiAuthenticator` directive is used to define a FastCGI application as a per-directory authenticator. Authenticators verify the requestor is who he says he is by matching the provided username and password against a list or database of known users and passwords. FastCGI based authenticators are useful primarily when the user database is maintained within an existing independent program or resides on a machine other than the web server.

If the FastCGI application filename does not have a corresponding static or external server definition, it is started as a dynamic FastCGI application. If the filename does not begin with a slash (/) then it is assumed to be relative to the ServerRoot.

`FastCgiAuthenticator` is used within `Directory` or `Location` containers and must include an `AuthType` and `AuthName` directive. Only the `Basic` user authentication type is supported. It must be accompanied by a `require` or `FastCgiAuthorizer` directive in order to work correctly.

> `

> <Directory htdocs/protected>
> AuthType Basic
> AuthName ProtectedRealm
> FastCgiAuthenticator fcgi-bin/authenticator
> require valid-user
> </Directory>

> `

`mod_fastcgi` sends nearly all of the standard environment variables typically available to CGI/FastCGI request handlers. All headers returned by a FastCGI authentication application in a successful response (Status: 200) are passed to subprocesses (CGI/FastCGI invocations) as environment variables. All headers returned in an unsuccessful response are passed on to the client. FastCGI specification compliant behaviour can be obtained by using the "`-compat`" option.

`mod_fastcgi` sets the environment variable "FCGI_APACHE_ROLE" to "AUTHENTICATOR" to indicate which (Apache specific) authorizer phase is being performed.

## FastCgiAuthenticatorAuthoritative

Syntax: | `FastCgiAuthenticatorAuthoritative On | Off`
Default: | `FastCgiAuthenticatorAuthoritative On`
Context: | directory

Setting the `FastCgiAuthenticatorAuthoritative` directive explicitly to Off allows authentication to be passed on to lower level modules (as defined in the `Configuration` and `modules.c` files) if the FastCGI application fails to authenticate the user.

A common use for this is in conjunction with a well protected `AuthUserFile` containing a few (administration related) users.

By default, control is not passed on and an unknown user will result in an Authorization Required reply. Disabling the default should be carefully considered.

## FastCgiAuthorizer

Syntax: | `FastCgiAuthorizer filename [-compat]`
Context: | directory

The `FastCgiAuthorizer` directive is used to define a FastCGI application as a per-directory authorizer. Authorizers validate whether an authenticated requestor is allowed access to the requested resource. FastCGI based authorizers are useful primarily when there is a dynamic component to the authorization decision such as a time of day or whether or not the user has paid his bills.

If the FastCGI application filename does not have a corresponding static or external server definition, it is started as a dynamic FastCGI application. If the filename does not begin with a slash (/) then it is assumed to be relative to the ServerRoot.

`FastCgiAuthorizer` is used within `Directory` or `Location` containers and must include an `AuthType` and `AuthName` directive. It must be accompanied by an authentication directive such as `FastCgiAuthenticator`, `AuthUserFile`, `AuthDBUserFile` or `AuthDBMUserFile` in order to work correctly.

> `

> <Directory htdocs/protected>
> AuthType Basic
> AuthName ProtectedRealm
> AuthDBMUserFile conf/authentication-database
> FastCgiAuthorizer fcgi-bin/authorizer
> </Directory>

> `

`mod_fastcgi` sends nearly all of the standard environment variables typically available to CGI/FastCGI request handlers. All headers returned by a FastCGI authorizer application in a successful response (Status: 200) are passed to subprocesses (CGI/FastCGI invocations) as environment variables. All headers returned in an unsuccessful response are passed on to the client. FastCGI specification compliant behaviour can be obtained by using the "`-compat`" option.

`mod_fastcgi` sets the environment variable "FCGI_APACHE_ROLE" to "AUTHORIZER" to indicate which (Apache specific) authorizer phase is being performed.

## FastCgiAuthorizerAuthoritative

Syntax: | `FastCgiAuthorizerAuthoritative On | Off`
Default: | `FastCgiAuthorizerAuthoritative On`
Context: | directory

Setting the `FastCgiAuthorizerAuthoritative` directive explicitly to Off allows authorization to be passed on to lower level modules (as defined in the `Configuration` and `modules.c` files) if the FastCGI application fails to authorize the user.

By default, control is not passed on and an unauthorized user will result in an Authorization Required reply. Disabling the default should be carefully considered.

## FastCgiAccessChecker

Syntax: | `FastCgiAccessChecker filename [-compat]`
Context: | directory

The `FastCgiAccessChecker` (suggestions for a better name are welcome) directive is used to define a FastCGI application as a per-directory access validator. The Apache Access phase precede user authentication and thus the decision to (dis)allow access to the requested resource is based on the HTTP headers submitted with the request. FastCGI based authorizers are useful primarily when there is a dynamic component to the access validation decision such as a time of day or whether or not a domain has paid his bills.

If the FastCGI application filename does not have a corresponding static or external server definition, it is started as a dynamic FastCGI application. If the filename does not begin with a slash (/) then it is assumed to be relative to the ServerRoot.

`FastCgiAccessChecker` is used within `Directory` or `Location` containers.

> `

> <Directory htdocs/protected>
> FastCgiAccessChecker fcgi-bin/access-checker
> </Directory>

> `

`mod_fastcgi` sends nearly all of the standard environment variables typically available to CGI/FastCGI request handlers. All headers returned by a FastCGI access-checker application in a successful response (Status: 200) are passed to subprocesses (CGI/FastCGI invocations) as environment variables. All headers returned in an unsuccessful response are passed on to the client. FastCGI specification compliant behaviour can be obtained by using the "`-compat`" option.

`mod_fastcgi` sets the environment variable "FCGI_APACHE_ROLE" to "ACCESS_CHECKER" to indicate which (Apache specific) authorizer phase is being performed.

## FastCgiAccessCheckerAuthoritative

Syntax: | `FastCgiAccessCheckerAuthoritative On | Off`
Default: | `FastCgiAccessCheckerAuthoritative On`
Context: | directory

Setting the `FastCgiAccessCheckerAuthoritative` directive explicitly to Off allows access checking to be passed on to lower level modules (as defined in the `Configuration` and `modules.c` files) if the FastCGI application fails to allow access.

By default, control is not passed on and a failed access check will result in a Forbidden reply. Disabling the default should be carefully considered.

### www.FastCGI.com