Brought to you by the

The WWW Common Gateway Interface Version 1.1

31st May 1995.

David Robinson, drtr@ast.cam.ac.uk
Note: This is an attempt to define the de facto CGI standard. I have tried to be consistent with the available documentation and the behaviour of existing software (in fact, only NCSA httpd.)

What is CGI?

The Common Gateway Interface, or CGI, is an interface for running external programs, or gateways, under an information server. Currently, the supported information servers are HTTP servers.

Together the HTTP server (httpd) and the CGI programs are responsible for servicing a client request by sending back responses. The client request comprises a Universal Resource Identifier (URI) [1], a request method, and various ancillary information about the request provided by the transport mechanism.

Notational Conventions and Generic Grammar

All of the mechanisms specified in this document are described in both prose and an augmented Backus-Naur Form described in section 2.1 of the HTTP/1.0 specification [2].

The following rules are used throughout this specification to describe basic parsing constructs.

alpha = lowalpha | hialpha
lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"
hialpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"
digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"

OCTET = <any 8-bit byte>
CHAR = <any character>
CTL = <any control character>
SP = <space character>
NL = <newline>
LWSP = SP | NL | <horizontal-tab>
tspecial = "(" | ")" | "@" | "," | ";" | ":" | "\" | <"> | "/" | "[" | "]" | "?" | SP
token = 1*<any CHAR except CTLs or tspecials>
quoted-string = ( <"> *qdtext <"> ) | ( "<" *qatext ">")
qdtext = <any CHAR except <"> and CTLs but including LWSP>
qatext = <any CHAR except "<", ">" and CTLs but including LWSP>
Note that newline (NL) need not be a single character, but can be a character sequence.

Environment variables

Environment variables are used to pass data about the request from the server to the script. They are accessed by the script in a system specific manner. In all cases, a missing environment variable is equivalent to a zero-length (NULL) value, and vice versa. The representation of the characters in the environment variables is implementation defined.

Case is not signifcant in the names, in that there cannot be two different variable whose names differ in case only. Here they are shown using capitals plus underscore ("_"). The actual representation of the names is system specific; for a particular system (e.g. Unix) the representation will be well defined (e.g. uppercase).

The standard variables are:

AUTH_TYPE
CONTENT_LENGTH
CONTENT_TYPE
GATEWAY_INTERFACE
HTTP_*
PATH_INFO
PATH_TRANSLATED
QUERY_STRING
REMOTE_ADDR
REMOTE_HOST
REMOTE_IDENT
REMOTE_USER
REQUEST_METHOD
SCRIPT_NAME
SERVER_NAME
SERVER_PORT
SERVER_PROTOCOL
SERVER_SOFTWARE
AUTH_TYPE
The variable is specific to requests made with HTTP.

If the script URI would require access authentication for external access, then this variable is found from the `auth-scheme' token in the request, otherwise NULL.

AUTH_TYPE = "" | auth-scheme
auth-scheme = "Basic" | token
HHTP access authentication schemes are described in section 10 of the HTTP/1.0 specification [2].
Notes: for httpd, replace `script URI' with `client URI'.
Are other auth schemes case insensitive? The HTTP spec does not say so.
CONTENT_LENGTH
The size of the attached entity, if any, in decimal number of octets. If no data is attached, then NULL. The syntax is the same as the HTTP Content-Length header (§7.2.4, HTTP/1.0 spec [2]).
CONTENT_LENGTH = "" | [ 1*digit ]
CONTENT_TYPE
The Internet Media Type [6] of the attached entity. The syntax is the same as the HTTP Content-Type header.
CONTENT_TYPE = "" | media-type
media-type = type "/" subtype *( ";" parameter)
type = token
subtype = token
parameter = attribute "=" value
attribute = token
value = token | quoted-string
The type, subtype and parameter attribute names are not case-sensitive. Parameter values may be case sensitive. Media types and their use in HTTP are described section 8.1 of the HTTP/1.0 specification [2]. Example:
application/x-www-form-urlencoded
There is no default value for this variable. If (and only if) it is unset, then the script may attempt to determine the media type from the data received. If the type remains unknown, then application/octet-stream should be assumed.

GATEWAY_INTERFACE
The version of the CGI specification to which this server complies. Syntax:
GATEWAY_INTERFACE = "CGI" "/" 1*digit "." 1*digit
Note that the major and minor numbers should be treated as separate integers and that each may be incremented higher than a single digit. Thus CGI/2.4 is a lower version than CGI/2.13 which in turn is lower than CGI/12.3. Leading zeros should be ignored by scripts and never generated by servers.

This document defines the 1.1 version of the CGI interface.

Notes: the server needs to be able to identify any OS specific parts of the interface, and also any extensions that it provides.
HTTP_*
These variables are specific to requests made with HTTP.

Environment variables with names beginning with "HTTP_" contain header data read from the client, if the protocol used was HTTP. The HTTP header name is converted to upper case, has all occurrences of "-" replaced with "_" and has "HTTP_" prepended to give the environment variable name. The header data may be presented as sent by the client, or may be rewritten in ways which do not change its semantics. For example, the sever may remove comments from the header. The server must, if necessary, change the representation of the data to be appropriate for a CGI environment variable.

The server is not required to create environment variables for all the headers that it receives. In particular, it might remove any headers carrying authentication information, such as `Authorization'.

Notes: should there be a requirement not to pass on certain data?
Should the server be required to remove CRLF from folded headers?
PATH_INFO
A path to be interpreted by the CGI script. It identifies the resource or sub-resource to be returned by the CGI script. The syntax and semantics are similar to a decoded HTTP URL `hpath' token (defined in RFC 1738 [3]), with the exception that a PATH_INFO of "/" represents a single void path segment. Otherwise, the leading "/" character is not part of the path.
PATH_INFO = "" | "/" path
path = segment *( "/" segment )
segment = *pchar
pchar = <any CHAR except "/">

The PATH_INFO may be some trailing part of the client URI, some string specified to the server or even the entire client URI path. It is not possible for the CGI script to determine how PATH_INFO was chosen on the basis of the CGI environment variables alone. The programmer must use her knowledge of the context in which the script will be used.

Notes: I originally defined this to be the same as the path allowed in an HTTP request, but that is not sufficiently tied down.
The existing CGI documentation requires PATH_INFO to be derived from part of the client URI; this specification does not.
PATH_TRANSLATED
The OS path to the file that httpd would attempt to access were the client to request the absolute URI containing the path PATH_INFO. i.e for a request of
protocol "://" SERVER_NAME ":" SERVER_PORT enc-path
where `enc-path' is a URL-encoded version of PATH_INFO. If PATH_INFO is NULL then PATH_TRANSLATED is set to NULL.
PATH_TRANSLATED = *CHAR

PATH_TRANSLATED need not be supported by the server. The server may choose to set PATH_TRANSLATED to NULL for reasons of security, or because the path would not be interpretable by a CGI script; such as the object it represented was internal to the server and not visible in the filesystem; or for any other reason.

The algorithm httpd uses to derive PATH_TRANSLATED is obviously system dependent; CGI scripts which use this variable may suffer limited portability.

Notes: httpd gets it `wrong' if the translated URI would invoke a CGI script, or use multiviews etc., or if the translated URI would require authentication.
QUERY_STRING
A URL-encoded search string.
QUERY_STRING = query-string
query-string = *qchar
qchar = unreserved | escape | ";" | ":" | "@" | "&" | "="
unreserved = alpha | digit | safe | extra
safe = "$" | "-" | "_" | "." | "+"
extra = "!" | "*" | "'" | "(" | ")" | ","
escape = "%" hex hex
hex = digit | "A" | "B" | "C" | "D" | "E" | "F" | "a" | "b" | "c" | "d" | "e" | "f"
The URI syntax for a search string is described in RFC 1630 [1].

REMOTE_ADDR
The IP address of the agent sending the request to the server. Not necessarily that of the client.
REMOTE_ADDR = hostnumber
hostnumber = digits "." digits "." digits "." digits
digits = 1*digit
REMOTE_HOST
The fully qualified domain name of the agent sending the request to the server, if available, otherwise NULL. Not necessarily that of the client. Fully qualified domain names take the form as described in section 3.5 of RFC 1034 [5] and section 2.1 of RFC 1123 [4]; a sequence of domain labels separated by ".", each domain label starting and ending with an alphanumerical character and possibly also containing "-" characters. The rightmost domain label will never start with a digit. Domain names are not case sensitive.
REMOTE_HOST = "" | hostname
hostname = *( domainlabel ".") toplabel
domainlabel = alphadigit [ *alphahypdigit alphadigit ]
toplabel = alpha [ *alphahypdigit alphadigit ]
alphahypdigit = alphadigit | "-"
alphadigit = alpha | digit
Note: the current documentation only requires this to be the `hostname', rather than the FQDN.
REMOTE_IDENT
The identity information reported about the connection by a RFC 931 [7] request to the remote agent, if available. The server may choose not to support this feature, or not to request the data for efficiency reasons.
REMOTE_IDENT = *CHAR
The data returned is not appropriate for use as authentication information.

REMOTE_USER
This variable is specific to requests made with HTTP.

If AUTH_TPYE is "Basic", then the user-ID sent by the client. If AUTH_TYPE is NULL, then NULL, otherwise undefined.

REMOTE_USER = "" | userid | *OCTET
userid = token
REQUEST_METHOD
This variable is specific to requests made with HTTP.

The method with which the request was made, as described in section 5.2 of the HTTP/1.0 specification [2].

REQUEST_METHOD = http-method
http-method = "GET" | "HEAD" | "PUT" | "POST" | "DELETE" | "LINK" | "UNLINK" | extension-method
extension-method = token
The method is case sensitive.

SCRIPT_NAME
A URI path that could identify the CGI script (rather then the particular CGI output). The syntax is identical to the HTTP URL `hpath' token [3].
SCRIPT_NAME = "" | "/" [ path ]
The leading "/" is not part of the path. It is optional if the path is NULL.
Note: again, this is slightly different to the current HTTP/1.0 specification [2] of Request-URI.
SERVER_NAME
A name for this server; appropriate as the host part of a URI. Thus either a fully qualified domain name, or an IP address.
SERVER_NAME = hostname | hostnumber
This name need not be the name used in the client URI.

SERVER_PORT
The port on which this request was received; appropriate as the port part of a URI.
SERVER_PORT = 1*digit
SERVER_PROTOCOL
The name and revision of the information protocol this request came in with.
SERVER_PROTOCOL = HTTP-Version | extension-version
HTTP-Version = "HTTP" "/" 1*digit "." 1*digit
extension-version = protocol "/" 1*digit "." 1*digit
protocol = 1*( alpha | digit | "+" | "-" | "." )
`protocol' is a version of the URL scheme used by the client, and is not case sensitive. By convention, `protocol' is in upper case.
Note: the current documentation does not define a syntax for protocol.
SERVER_SOFTWARE
The name and version of the information server software answering the request (and running the gateway).
SERVER_SOFTWARE = *CHAR

Defining a script URI

It is possible to define a URI which represents the output of the CGI script for a "GET" request. This `script URI' is not necessarily the URI used by the client to initiate the request; for example, the server may internally `redirect' the request to a new URI. The script URI is given by
script-uri = protocol "://" SERVER_NAME ":" SERVER_PORT enc-script enc-path "?" QUERY_STRING
where `protocol' is found from SERVER_PROTOCOL, `enc-script' is A URL-encoded version of SCRIPT_NAME and `enc-path' is a URL-encoded version of PATH_INFO.

This URI does not necessarily have any meaning outside the context of the server and CGI script. Hence we do not define the environment variables in terms of this URI, but instead use this URI as a convenient representation of the environment variables.

The CGI script command line

Some operating systems support a method for supplying a array of strings to the CGI script. This is only used in the case of an `ISINDEX' query. This is identified by a "GET" HTTP request with a URI search string not containing any unencoded "=" characters. For such a request, the server should parse the search string into words, using the rule:
search-string = search-word *( "+" search-word )
search-word = 1*schar
schar = xunreserved | escape | ";" | ":" | "@" | "&"
xunreserved = alpha | digit | xsafe | extra
xsafe = "$" | "-" | "_" | "."
After parsing, each word is URL-decoded, optionally encoded in a system specific manner and then the argument list is set to the list of words.

If the server cannot create any part of the argument list, then the server should generate no command line information. For example, the number of arguments may greater than operating system or server limitations, or one of the words may not be representable as an argument.

Note: the original documentation did not limit this to a GET request

Data input to the CGI script

As there may be a data entity attached to the request, then there must be an implementation defined method for the script to read this data. For example, for most operating systems, this will be via the `standard input' file descriptor.

There will be at least CONTENT_LENGTH bytes available for the script to read. The script is not obliged to read the data, but it must not attempt to read more than CONTENT_LENGTH bytes, even if more data is available.

Data output from the CGI script

There must be an implementation defined method for the script to send data back to the server or client; a script will always return some data. There are two forms of output that the script can give; non-parsed header (NPH) output, and parsed header output. A server is only required to support the latter; distinguishing between the two types of output (or scripts) is implementation defined.

The format of the data output is only defined if the request protocol is HTTP.

Non-Parsed Header Output

The script must return a complete HTTP response message, as described in Section 6 of the HTTP specification [2]. Note that this allows an HTTP/0.9 response to an HTTP/1.0 request.

Parsed Header Output

The script returns a CGI response message.
CGI-Response = 1*CGI-Header *( HTTP-Header ) NL [ Entity-Body ]
CGI-Header = Content-type
| Location
| Status
| extension-header
The response comprises headers and a body, separated by a blank line. The headers are either CGI headers to be interpreted by the server, or HTTP headers to be included in the response returned to the client. If a body is supplied, then a Content-type header is required, otherwise the script must send a Location or Status header.

Note: If the body is optional, then how can a zero-length body be detected?
The CGI headers have the generic syntax:
generic-header = field-name ":" [ field-value ] NL
field-name = 1*<any CHAR, excluding CTLs, SP and ":">
field-value = *( field-content | LWSP )
field-content = * ( token | tspecial | quoted-string)
The field-name is not case sensitive; a NULL field value is equivalent to the header not being sent.
Content-Type
The Internet Media Type [6] of the entity body.
Content-Type = "Content-Type" ":" media-type NL
Note: should this be optional? If so, what value should the server or client assume? And does the presence of the header imply the presence of a message body?
Location
This is used to specify to the server that the script is returning a reference to a document rather than an actual document.
Location = "Location" ":" fragment-URI | rel-URL-abs-path NL
fragment-URI = URI [ # fragmentid ]
rel-URL-abs-path = "/" [ URL-path ] [ "?" query-string ]
URL-path = psegment *( "/" psegment )
psegment = *qchar
The location value is either an absolute URI with optional fragment, as defined in RFC 1630 [1], or an absolute path and optional query-string. If an absolute URI is returned by the script, then the server will generate a redirect HTTP response message, and if no entity body is supplied by the script, then the server will produce one. If the Location value is a path, then the server will generate the response that it would have produced in response to a request containing the URI
protocol "://" SERVER_NAME ":" SERVER_PORT rel-URL-abs-path
Status
The Status header is used to indicate to the server what status code it should use in the response message. It should not be sent if the script returns a Location header.
Status = "Status" ":" 3digit NL
The valid status codes are listed in section 6.2 of the HTTP/1.0 specification [2].

HTTP headers
The script may return any other headers defined by the HTTP/1.0 specification [2]. The server must translate the header data from the CGI header syntax to the HTTP header syntax if these differ.

Requirements for servers

Servers must support the standard mechanism (described below) to allow the script author to determine what URI should be used for accessing the script. Specifically, what URI to use in order to achieve particular settings of the environment variables. This mechanism is as follows:

The value for SCRIPT_NAME is governed by the server configuration and the location of the script in the OS filesystem. Given this, any access to the partial URI

SCRIPT_NAME extra-path ? query-information
where extra-path is either NULL or begins with a "/" and satisfies any other server requirements, will cause the CGI script to be executed with PATH_INFO set to the decoded extra-path, and QUERY_STRING set to query-information (not decoded).

Servers should reject with error 404 any requests that would result in an encoded "/" being decoded into PATH_INFO or SCRIPT_NAME.

Note: this should be made a requirement.

Servers may impose arbitrary restrictions on paths to ensure consistency with the server's own treatment of paths, such as restrictions on allowed characters (e.g. disallow ASCII NULL), restriction on specific path segments (such as non-terminal NULL segments, or "." or "..") or restrictions on path or search string lengths.

Servers may generate the script URI in any way from the client URI, or from any other data (but the behaviour should be documented!).

Recommendations for scripts

Scripts should reject unexpected methods (such as DELETE etc.) with error 405 Method Not Allowed. If the script does not intend processing the PATH_INFO data, then it should reject the request with 404 Not Found if PATH_INFO is not NULL.

If the output of a form is being processed, check that CONTENT_TYPE is "application/x-www-form-urlencoded".

Note: presumably 400 is the appropriate error code in this case.
If parsing PATH_INFO, PATH_TRANSLATED or SCRIPT_NAME then be careful of void path segments ("//") and special path segments ("." and ".."). They should either be removed from the path before use in OS system calls, or the request should be rejected with 404 Not Found. It is very unlikely that any other use could be made of these.

As it is impossible for the script to determine the client URI that initiated this request, the script should not return text/html documents containing relative-URL links without including a <BASE> tag in the document.

System-specific standards

Unix

For Unix compatible operating systems, the following are defined:
Environment variables
These are accessed by the C library routine getenv and their names are in uppercase.
The command line
This is accessed using the the argc and argv arguments to main(). The words are have any characters which are `active' in the bourne shell escaped with a backslash.
Data input and output
The CGI script input is present on the stdin stream; output must be written on the stdout stream.

References

[1] Berners-Lee, T., `Universal Resource Identifiers in WWW: A Unifying Syntax for the Expression of Names and Addresses of Objects on the Network as used in the World-Wide Web', RFC 1630, CERN, June 1994.

[2] Berners-Lee, T., Fielding, R. T. and Frystyk Nielsen, H., `Hypertext Transfer Protocol - HTTP/1.0', Work in Progress, March 1995.

[3] Berners-Lee, T., Masinter, L. and McCahill, M., Editors, `Uniform Resource Locators (URL)', RFC 1738, CERN, Xerox Corporation, University of Minnesota, December 1994.

[4] Braden, R., Editor, `Requirements for Internet Hosts - Application and Support', STD 3, RFC 1123, IETF, October 1989.

[5] Mockapetris, P., `Domain Names - Concepts and Facilities', STD 13, RFC 1034, ISI, November 1987.

[6] Postel, J., `Media Type Registration Procedure', ISI, March 1994.

[7] StJohns, M., `Authentication Server', RFC 931, TPSC, January 1985.