when doing so.
The server MAY decide that some methods are not appropriate or
permitted for a script, and may handle the methods itself or return
an error to the client.
4.4. The Script Command Line
Some systems support a method for supplying an array of strings to
the CGI script. This is only used in the case of an ’indexed’ HTTP
query, which is identified by a ’GET’ or ’HEAD’ request with a URI
query string that does not contain any unencoded "=" characters. For
such a request, the server SHOULD treat the query-string as a
search-string and parse it into words, using the rules
search-string = search-word *( "+" search-word )
search-word = 1*schar
schar = unreserved | escaped | xreserved
xreserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "," |
"$"
After parsing, each search-word is URL-decoded, optionally encoded in
a system-defined manner and then added to the command line argument
list.
If the server cannot create any part of the argument list, then the
server MUST NOT generate any command line information. For example,
the number of arguments may be greater than operating system or
server limits, or one of the words may not be representable as an
argument.
The script SHOULD check to see if the QUERY_STRING value contains an
unencoded "=" character, and SHOULD NOT use the command line
arguments if it does.
5. NPH Scripts
5.1. Identification
The server MAY support NPH (Non-Parsed Header) scripts; these are
scripts to which the server passes all responsibility for response
processing.
This specification provides no mechanism for an NPH script to be
identified on the basis of its output data alone. By convention,
therefore, any particular script can only ever provide output of one
type (NPH or CGI) and hence the script itself is described as an ’NPH
script’. A server with NPH support MUST provide an implementation-
defined mechanism for identifying NPH scripts, perhaps based on the
name or location of the script.
5.2. NPH Response
There MUST be a system-defined method for the script to send data
back to the server or client; a script MUST always return some data.
Unless defined otherwise, this will be the same as for conventional
CGI scripts.
Currently, NPH scripts are only defined for HTTP client requests. An
(HTTP) NPH script MUST return a complete HTTP response message,
currently described in section 6 of the HTTP specifications [1], [4].
The script MUST use the SERVER_PROTOCOL variable to determine the
appropriate format for a response. It MUST also take account of any
generic or protocol-specific meta-variables in the request as might
be mandated by the particular protocol specification.
The server MUST ensure that the script output is sent to the client
unmodified. Note that this requires the script to use the correct
character set (US-ASCII [9] and ISO 8859-1 [10] for HTTP) in the
header fields. The server SHOULD attempt to ensure that the script
output is sent directly to the client, with minimal internal and no
transport-visible buffering.
Unless the implementation defines otherwise, the script MUST NOT
indicate in its response that the client can send further requests
over the same connection.
6. CGI Response
6.1. Response Handling
A script MUST always provide a non-empty response, and so there is a
system-defined method for it to send this data back to the server.
Unless defined otherwise, this will be via the ’standard output’ file
descriptor.
The script MUST check the REQUEST_METHOD variable when processing the
request and preparing its response.
The server MAY implement a timeout period within which data must be
received from the script. If a server implementation defines such a
timeout and receives no data from a script within the timeout period,
the server MAY terminate the script process.
6.2. Response Types
The response comprises a message-header and a message-body, separated
by a blank line. The message-header contains one or more header
fields. The body may be NULL.
generic-response = 1*header-field NL [ response-body ]
The script MUST return one of either a document response, a local
redirect response or a client redirect (with optional document)
response. In the response definitions below, the order of header
fields in a response is not significant (despite appearing so in the
BNF). The header fields are defined in section 6.3.
CGI-Response = document-response | local-redir-response |
client-redir-response | client-redirdoc-response
6.2.1. Document Response
The CGI script can return a document to the user in a document
response, with an optional error code indicating the success status
of the response.
document-response = Content-Type [ Status ] *other-field NL
response-body
The script MUST return a Content-Type header field. A Status header
field is optional, and status 200 ’OK’ is assumed if it is omitted.
The server MUST make any appropriate modifications to the script’s
output to ensure that the response to the client complies with the
response protocol version.
6.2.2. Local Redirect Response
The CGI script can return a URI path and query-string
(’local-pathquery’) for a local resource in a Location header field.
This indicates to the server that it should reprocess the request
using the path specified.
local-redir-response = local-Location NL
The script MUST NOT return any other header fields or a message-body,
and the server MUST generate the response that it would have produced
in response to a request containing the URL
scheme "://" server-name ":" server-port local-pathquery
6.2.3. Client Redirect Response
The CGI script can return an absolute URI path in a Location header
field, to indicate to the client that it should reprocess the request
using the URI specified.
client-redir-response = client-Location *extension-field NL
The script MUST not provide any other header fields, except for
server-defined CGI extension fields. For an HTTP client request, the
server MUST generate a 302 ’Found’ HTTP response message.
6.2.4. Client Redirect Response with Document
The CGI script can return an absolute URI path in a Location header
field together with an attached document, to indicate to the client
that it should reprocess the request using the URI specified.
client-redirdoc-response = client-Location Status Content-Type
*other-field NL response-body
The Status header field MUST be supplied and MUST contain a status
value of 302 ’Found’, or it MAY contain an extension-code, that is,
another valid status code that means client redirection. The server
MUST make any appropriate modifications to the script’s output to
ensure that the response to the client complies with the response
protocol version.
6.3. Response Header Fields
The response header fields are either CGI or extension header fields
to be interpreted by the server, or protocol-specific header fields
to be included in the response returned to the client. At least one
CGI field MUST be supplied; each CGI field MUST NOT appear more than
once in the response. The response header fields have the syntax:
header-field = CGI-field | other-field
CGI-field = Content-Type | Location | Status
other-field = protocol-field | extension-field
protocol-field = generic-field
extension-field = generic-field
generic-field = field-name ":" [ field-value ] NL
field-name = token
field-value = *( field-content | LWSP )
field-content = *( token | separator | quoted-string )
The field-name is not case sensitive. A NULL field value is
equivalent to a field not being sent. Note that each header field in
a CGI-Response MUST be specified on a single line; CGI/1.1 does not
support continuation lines. Whitespace is permitted between the ":"
and the field-value (but not between the field-name and the ":"), and
also between tokens in the field-value.
6.3.1. Content-Type
The Content-Type response field sets the Internet Media Type [6] of
the entity body.
Content-Type = "Content-Type:" media-type NL
If an entity body is returned, the script MUST supply a Content-Type
field in the response. If it fails to do so, the server SHOULD NOT
attempt to determine the correct content type. The value SHOULD be
sent unmodified to the client, except for any charset parameter
changes.
Unless it is otherwise system-defined, the default charset assumed by
the client for text media-types is ISO-8859-1 if the protocol is HTTP
and US-ASCII otherwise. Hence the script SHOULD include a charset
parameter. See section 3.4.1 of the HTTP/1.1 specification [4] for a
discussion of this issue.
6.3.2. Location
The Location header field is used to specify to the server that the
script is returning a reference to a document rather than an actual
document (see sections 6.2.3 and 6.2.4). It is either an absolute
URI (optionally with a fragment identifier), indicating that the
client is to fetch the referenced document, or a local URI path
(optionally with a query string), indicating that the server is to
fetch the referenced document and return it to the client as the
response.
Location = local-Location | client-Location
client-Location = "Location:" fragment-URI NL
local-Location = "Location:" local-pathquery NL
fragment-URI = absoluteURI [ "#" fragment ]
fragment = *uric
local-pathquery = abs-path [ "?" query-string ]
abs-path = "/" path-segments
path-segments = segment *( "/" segment )
segment = *pchar
pchar = unreserved | escaped | extra
extra = ":" | "@" | "&" | "=" | "+" | "$" | ","
The syntax of an absoluteURI is incorporated into this document from
that specified in RFC 2396 [2] and RFC 2732 [7]. A valid absoluteURI
always starts with the name of scheme followed by ":"; scheme names
start with a letter and continue with alphanumerics, "+", "-" or ".".
The local URI path and query must be an absolute path, and not a
relative path or NULL, and hence must start with a "/".
Note that any message-body attached to the request (such as for a
POST request) may not be available to the resource that is the target
of the redirect.
6.3.3. Status
The Status header field contains a 3-digit integer result code that
indicates the level of success of the script’s attempt to handle the
request.
Status = "Status:" status-code SP reason-phrase NL
status-code = "200" | "302" | "400" | "501" | extension-code
extension-code = 3digit
reason-phrase = *TEXT
Status code 200 ’OK’ indicates success, and is the default value
assumed for a document response. Status code 302 ’Found’ is used
with a Location header field and response message-body. Status code
400 ’Bad Request’ may be used for an unknown request format, such as
a missing CONTENT_TYPE. Status code 501 ’Not Implemented’ may be
returned by a script if it receives an unsupported REQUEST_METHOD.
Other valid status codes are listed in section 6.1.1 of the HTTP
specifications [1], [4], and also the IANA HTTP Status Code Registry
[8] and MAY be used in addition to or instead of the ones listed
above. The script SHOULD check the value of SERVER_PROTOCOL before
using HTTP/1.1 status codes. The script MAY reject with error 405
’Method Not Allowed’ HTTP/1.1 requests made using a method it does
not support.
Note that returning an error status code does not have to mean an
error condition with the script itself. For example, a script that
is invoked as an error handler by the server should return the code
appropriate to the server’s error condition.
The reason-phrase is a textual description of the error to be
returned to the client for human consumption.
6.3.4. Protocol-Specific Header Fields
The script MAY return any other header fields that relate to the
response message defined by the specification for the SERVER_PROTOCOL
(HTTP/1.0 [1] or HTTP/1.1 [4]). The server MUST translate the header
data from the CGI header syntax to the HTTP header syntax if these
differ. For example, the character sequence for newline (such as
UNIX’s US-ASCII LF) used by CGI scripts may not be the same as that
used by HTTP (US-ASCII CR followed by LF).
The script MUST NOT return any header fields that relate to
client-side communication issues and could affect the server’s
ability to send the response to the client. The server MAY remove
any such header fields returned by the client. It SHOULD resolve any
conflicts between header fields returned by the script and header
fields that it would otherwise send itself.
6.3.5. Extension Header Fields
There may be additional implementation-defined CGI header fields,
whose field names SHOULD begin with "X-CGI-". The server MAY ignore
(and delete) any unrecognised header fields with names beginning "X-
CGI-" that are received from the script.
6.4. Response Message-Body
The response message-body is an attached document to be returned to
the client by the server. The server MUST read all the data provided
by the script, until the script signals the end of the message-body
by way of an end-of-file condition. The message-body SHOULD be sent
unmodified to the client, except for HEAD requests or any required
transfer-codings, content-codings or charset conversions.
response-body = *OCTET
7. System Specifications
7.1. AmigaDOS
Meta-Variables
Meta-variables are passed to the script in identically named
environment variables. These are accessed by the DOS library
routine GetVar(). The flags argument SHOULD be 0. Case is
ignored, but upper case is recommended for compatibility with
case-sensitive systems.
The current working directory
The current working directory for the script is set to the
directory containing the script.
Character set
The US-ASCII character set [9] is used for the definition of
meta-variables, header fields and values; the newline (NL)
sequence is LF; servers SHOULD also accept CR LF as a newline.
7.2. UNIX
For UNIX compatible operating systems, the following are defined:
Meta-Variables
Meta-variables are passed to the script in identically named
environment variables. These are accessed by the C library
routine getenv() or variable environ.
The command line
This is accessed using the argc and argv arguments to main(). The
words have any characters which are ’active’ in the Bourne shell
escaped with a backslash.
The current working directory
The current working directory for the script SHOULD be set to the
directory containing the script.
Character set
The US-ASCII character set [9], excluding NUL, is used for the
definition of meta-variables, header fields and CHAR values; TEXT
values use ISO-8859-1. The PATH_TRANSLATED value can contain any
8-bit byte except NUL. The newline (NL) sequence is LF; servers
should also accept CR LF as a newline.
7.3. EBCDIC/POSIX
For POSIX compatible operating systems using the EBCDIC character
set, the following are defined:
Meta-Variables
Meta-variables are passed to the script in identically named
environment variables. These are accessed by the C library
routine getenv().
The command line
This is accessed using the argc and argv arguments to main(). The
words have any characters which are ’active’ in the Bourne shell
escaped with a backslash.
The current working directory
The current working directory for the script SHOULD be set to the
directory containing the script.
Character set
The IBM1047 character set [21], excluding NUL, is used for the
definition of meta-variables, header fields, values, TEXT strings
and the PATH_TRANSLATED value. The newline (NL) sequence is LF;
servers should also accept CR LF as a newline.
media-type charset default
The default charset value for text (and other implementation-
defined) media types is IBM1047.
8. Implementation
8.1. Recommendations for Servers
Although the server and the CGI script need not be consistent in
their handling of URL paths (client URLs and the PATH_INFO data,
respectively), server authors may wish to impose consistency. So the
server implementation should specify its behaviour for the following
cases:
1. define any restrictions on allowed path segments, in particular
whether non-terminal NULL segments are permitted;
2. define the behaviour for "." or ".." path segments; i.e.,
whether they are prohibited, treated as ordinary path segments
or interpreted in accordance with the relative URL
specification [2];
3. define any limits of the implementation, including limits on
path or search string lengths, and limits on the volume of
header fields the server will parse.
8.2. Recommendations for Scripts
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" [18] or "multipart/form-data"
[16]. If CONTENT_TYPE is blank, the script can reject the request
with a 415 ’Unsupported Media Type’ error, where supported by the
protocol.
When parsing PATH_INFO, PATH_TRANSLATED or SCRIPT_NAME the script
should 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’.
When returning header fields, the script should try to send the CGI
header fields as soon as possible, and should send them before any
HTTP header fields. This may help reduce the server’s memory
requirements.
Script authors should be aware that the REMOTE_ADDR and REMOTE_HOST
meta-variables (see sections 4.1.8 and 4.1.9) may not identify the
ultimate source of the request. They identify the client for the
immediate request to the server; that client may be a proxy, gateway,
or other intermediary acting on behalf of the actual source client.
9. Security Considerations
9.1. Safe Methods
As discussed in the security considerations of the HTTP
specifications [1], [4], the convention has been established that the
GET and HEAD methods should be ’safe’ and ’idempotent’ (repeated
requests have the same effect as a single request). See section 9.1
of RFC 2616 [4] for a full discussion.
9.2. Header Fields Containing Sensitive Information
Some HTTP header fields may carry sensitive information which the
server should not pass on to the script unless explicitly configured
to do so. For example, if the server protects the script by using
the Basic authentication scheme, then the client will send an
Authorization header field containing a username and password. The
server validates this information and so it should not pass on the
password via the HTTP_AUTHORIZATION meta-variable without careful
consideration. This also applies to the Proxy-Authorization header
field and the corresponding HTTP_PROXY_AUTHORIZATION meta-variable.
9.3. Data Privacy
Confidential data in a request should be placed in a message-body as
part of a POST request, and not placed in the URI or message headers.
On some systems, the environment used to pass meta-variables to a
script may be visible to other scripts or users. In addition, many
existing servers, proxies and clients will permanently record the URI
where it might be visible to third parties.
9.4. Information Security Model
For a client connection using TLS, the security model applies between
the client and the server, and not between the client and the script.
It is the server’s responsibility to handle the TLS session, and thus
it is the server which is authenticated to the client, not the CGI
script.
This specification provides no mechanism for the script to
authenticate the server which invoked it. There is no enforced
integrity on the CGI request and response messages.
9.5. Script Interference with the Server
The most common implementation of CGI invokes the script as a child
process using the same user and group as the server process. It
should therefore be ensured that the script cannot interfere with the
server process, its configuration, documents or log files.
If the script is executed by calling a function linked in to the
server software (either at compile-time or run-time) then precautions
should be taken to protect the core memory of the server, or to
ensure that untrusted code cannot be executed.
9.6. Data Length and Buffering Considerations
This specification places no limits on the length of the message-body
presented to the script. The script should not assume that
statically allocated buffers of any size are sufficient to contain
the entire submission at one time. Use of a fixed length buffer
without careful overflow checking may result in an attacker
exploiting ’stack-smashing’ or ’stack-overflow’ vulnerabilities of
the operating system. The script may spool large submissions to disk
or other buffering media, but a rapid succession of large submissions
may result in denial of service conditions. If the CONTENT_LENGTH of
a message-body is larger than resource considerations allow, scripts
should respond with an error status appropriate for the protocol
version; potentially applicable status codes include 503 ’Service
Unavailable’ (HTTP/1.0 and HTTP/1.1), 413 ’Request Entity Too Large’
(HTTP/1.1), and 414 ’Request-URI Too Large’ (HTTP/1.1).
Similar considerations apply to the server’s handling of the CGI
response from the script. There is no limit on the length of the
header or message-body returned by the script; the server should not
assume that statically allocated buffers of any size are sufficient
to contain the entire response.
9.7. Stateless Processing
The stateless nature of the Web makes each script execution and
resource retrieval independent of all others even when multiple
requests constitute a single conceptual Web transaction. Because of
this, a script should not make any assumptions about the context of
the user-agent submitting a request. In particular, scripts should
examine data obtained from the client and verify that they are valid,
both in form and content, before allowing them to be used for
sensitive purposes such as input to other applications, commands, or
operating system services. These uses include (but are not limited
to) system call arguments, database writes, dynamically evaluated
source code, and input to billing or other secure processes. It is
important that applications be protected from invalid input
regardless of whether the invalidity is the result of user error,
logic error, or malicious action.
Authors of scripts involved in multi-request transactions should be
particularly cautious about validating the state information;
undesirable effects may result from the substitution of dangerous
values for portions of the submission which might otherwise be
presumed safe. Subversion of this type occurs when alterations are
made to data from a prior stage of the transaction that were not
meant to be controlled by the client (e.g., hidden HTML form
elements, cookies, embedded URLs, etc.).