# NOTE: the above "/usr/local/bin/python" is NOT a mistake. It is
# intentionally NOT "/usr/bin/env python". On many systems
# (e.g. Solaris), /usr/local/bin is not in $PATH as passed to CGI
# scripts, and /usr/local/bin is the default directory where Python is
# installed, so /usr/bin/env would be unable to find python. Granted,
# binary installations by Linux vendors often install Python in
# /usr/bin. So let those vendors patch cgi.py to match their choice
"""Support module for CGI (Common Gateway Interface) scripts.
This module defines a number of utilities for use by CGI scripts
# XXX Perhaps there should be a slimmed version that doesn't contain
# all those backwards compatible and debugging classes and functions?
# Michael McLay started this module. Steve Majewski changed the
# interface to SvFormContentDict and FormContentDict. The multipart
# parsing was inspired by code submitted by Andreas Paepcke. Guido van
# Rossum rewrote, reformatted and documented the module and is currently
# responsible for its maintenance.
from StringIO
import StringIO
__all__
= ["MiniFieldStorage", "FieldStorage", "FormContentDict",
"SvFormContentDict", "InterpFormContentDict", "FormContent",
"parse", "parse_qs", "parse_qsl", "parse_multipart",
"parse_header", "print_exception", "print_environ",
"print_form", "print_directory", "print_arguments",
"print_environ_usage", "escape"]
logfile
= "" # Filename to log to, if not empty
logfp
= None # File object to log to, if not None
"""Write a log message, if there is a log file.
Even though this function is called initlog(), you should always
use log(); log is a variable that is set either to initlog
(initially), to dolog (once the log file has been opened), or to
nolog (when logging is disabled).
The first argument is a format string; the remaining arguments (if
any) are arguments to the % operator, so e.g.
will write "a: b" to the log file, followed by a newline.
If the global logfp is not None, it should be a file object to
which log data is written.
If the global logfp is None, the global logfile may be a string
giving a filename to open, in append mode. This file should be
world writable!!! If the file can't be opened, logging is
silently disabled (since there is no safe place where we could
if logfile
and not logfp
:
logfp
= open(logfile
, "a")
"""Write a log message to the log file. See initlog() for docs."""
logfp
.write(fmt
%args
+ "\n")
"""Dummy function, assigned to log when logging is disabled."""
log
= initlog
# The current logging function
# Maximum input we will accept when REQUEST_METHOD is POST
def parse(fp
=None, environ
=os
.environ
, keep_blank_values
=0, strict_parsing
=0):
"""Parse a query in the environment or from a file (default stdin)
fp : file pointer; default: sys.stdin
environ : environment dictionary; default: os.environ
keep_blank_values: flag indicating whether blank values in
URL encoded forms should be treated as blank strings.
A true value indicates that blanks should be retained as
blank strings. The default false value indicates that
blank values are to be ignored and treated as if they were
strict_parsing: flag indicating what to do with parsing errors.
If false (the default), errors are silently ignored.
If true, errors raise a ValueError exception.
if not 'REQUEST_METHOD' in environ
:
environ
['REQUEST_METHOD'] = 'GET' # For testing stand-alone
if environ
['REQUEST_METHOD'] == 'POST':
ctype
, pdict
= parse_header(environ
['CONTENT_TYPE'])
if ctype
== 'multipart/form-data':
return parse_multipart(fp
, pdict
)
elif ctype
== 'application/x-www-form-urlencoded':
clength
= int(environ
['CONTENT_LENGTH'])
if maxlen
and clength
> maxlen
:
raise ValueError, 'Maximum content length exceeded'
qs
= '' # Unknown content-type
if 'QUERY_STRING' in environ
:
qs
= qs
+ environ
['QUERY_STRING']
environ
['QUERY_STRING'] = qs
# XXX Shouldn't, really
elif 'QUERY_STRING' in environ
:
qs
= environ
['QUERY_STRING']
environ
['QUERY_STRING'] = qs
# XXX Shouldn't, really
return parse_qs(qs
, keep_blank_values
, strict_parsing
)
def parse_qs(qs
, keep_blank_values
=0, strict_parsing
=0):
"""Parse a query given as a string argument.
qs: URL-encoded query string to be parsed
keep_blank_values: flag indicating whether blank values in
URL encoded queries should be treated as blank strings.
A true value indicates that blanks should be retained as
blank strings. The default false value indicates that
blank values are to be ignored and treated as if they were
strict_parsing: flag indicating what to do with parsing errors.
If false (the default), errors are silently ignored.
If true, errors raise a ValueError exception.
for name
, value
in parse_qsl(qs
, keep_blank_values
, strict_parsing
):
def parse_qsl(qs
, keep_blank_values
=0, strict_parsing
=0):
"""Parse a query given as a string argument.
qs: URL-encoded query string to be parsed
keep_blank_values: flag indicating whether blank values in
URL encoded queries should be treated as blank strings. A
true value indicates that blanks should be retained as blank
strings. The default false value indicates that blank values
are to be ignored and treated as if they were not included.
strict_parsing: flag indicating what to do with parsing errors. If
false (the default), errors are silently ignored. If true,
errors raise a ValueError exception.
Returns a list, as G-d intended.
pairs
= [s2
for s1
in qs
.split('&') for s2
in s1
.split(';')]
if not name_value
and not strict_parsing
:
nv
= name_value
.split('=', 1)
raise ValueError, "bad query field: %r" % (name_value
,)
# Handle case of a control-name with no equal sign
if len(nv
[1]) or keep_blank_values
:
name
= urllib
.unquote(nv
[0].replace('+', ' '))
value
= urllib
.unquote(nv
[1].replace('+', ' '))
def parse_multipart(fp
, pdict
):
"""Parse multipart input.
pdict: dictionary containing other parameters of conten-type header
Returns a dictionary just like parse_qs(): keys are the field names, each
value is a list of values for that field. This is easy to use but not
much good if you are expecting megabytes to be uploaded -- in that case,
use the FieldStorage class instead which is much more flexible. Note
that content-type is the raw, unparsed contents of the content-type
XXX This does not parse nested multipart parts -- use FieldStorage for
XXX This should really be subsumed by FieldStorage altogether -- no
point in having two implementations of the same parsing algorithm.
boundary
= pdict
['boundary']
if not valid_boundary(boundary
):
raise ValueError, ('Invalid boundary in multipart form: %r'
nextpart
= "--" + boundary
lastpart
= "--" + boundary
+ "--"
while terminator
!= lastpart
:
# At start of next part. Read headers first.
headers
= mimetools
.Message(fp
)
clength
= headers
.getheader('content-length')
if maxlen
and bytes
> maxlen
:
raise ValueError, 'Maximum content length exceeded'
# Read lines until end of part.
terminator
= lastpart
# End outer loop
terminator
= line
.strip()
if terminator
in (nextpart
, lastpart
):
# Strip final line terminator
line
= headers
['content-disposition']
key
, params
= parse_header(line
)
partdict
[name
].append(data
)
"""Parse a Content-type like header.
Return the main content-type and a dictionary of options.
plist
= map(lambda x
: x
.strip(), line
.split(';'))
key
= plist
.pop(0).lower()
name
= p
[:i
].strip().lower()
if len(value
) >= 2 and value
[0] == value
[-1] == '"':
value
= value
.replace('\\\\', '\\').replace('\\"', '"')
# Classes for field storage
# =========================
"""Like FieldStorage, for use when no file uploads are possible."""
def __init__(self
, name
, value
):
"""Constructor from field name and value."""
# self.file = StringIO(value)
"""Return printable representation."""
return "MiniFieldStorage(%r, %r)" % (self
.name
, self
.value
)
"""Store a sequence of fields, reading multipart/form-data.
This class provides naming, typing, files stored on disk, and
more. At the top level, it is accessible like a dictionary, whose
keys are the field names. (Note: None can occur as a field name.)
The items are either a Python list (if there's multiple values) or
another FieldStorage or MiniFieldStorage object. If it's a single
object, it has the following attributes:
name: the field name, if specified; otherwise None
filename: the filename, if specified; otherwise None; this is the
client side filename, *not* the file name on which it is
stored (that's a temporary file you don't deal with)
value: the value as a *string*; for file uploads, this
transparently reads the file every time you request the value
file: the file(-like) object from which you can read the data;
None if the data is stored a simple string
type: the content-type, or None if not specified
type_options: dictionary of options specified on the content-type
disposition: content-disposition, or None if not specified
disposition_options: dictionary of corresponding options
headers: a dictionary(-like) object (sometimes rfc822.Message or a
subclass thereof) containing *all* headers
The class is subclassable, mostly for the purpose of overriding
the make_file() method, which is called internally to come up with
a file open for reading and writing. This makes it possible to
override the default choice of storing all files in a temporary
directory and unlinking them as soon as they have been opened.
def __init__(self
, fp
=None, headers
=None, outerboundary
="",
environ
=os
.environ
, keep_blank_values
=0, strict_parsing
=0):
"""Constructor. Read multipart/* until last part.
fp : file pointer; default: sys.stdin
(not used when the request method is GET)
headers : header dictionary-like object; default:
taken from environ as per CGI spec
outerboundary : terminating multipart boundary
environ : environment dictionary; default: os.environ
keep_blank_values: flag indicating whether blank values in
URL encoded forms should be treated as blank strings.
A true value indicates that blanks should be retained as
blank strings. The default false value indicates that
blank values are to be ignored and treated as if they were
strict_parsing: flag indicating what to do with parsing errors.
If false (the default), errors are silently ignored.
If true, errors raise a ValueError exception.
self
.keep_blank_values
= keep_blank_values
self
.strict_parsing
= strict_parsing
if 'REQUEST_METHOD' in environ
:
method
= environ
['REQUEST_METHOD'].upper()
if method
== 'GET' or method
== 'HEAD':
if 'QUERY_STRING' in environ
:
qs
= environ
['QUERY_STRING']
headers
= {'content-type':
"application/x-www-form-urlencoded"}
# Set default content-type for POST to what's traditional
headers
['content-type'] = "application/x-www-form-urlencoded"
if 'CONTENT_TYPE' in environ
:
headers
['content-type'] = environ
['CONTENT_TYPE']
if 'CONTENT_LENGTH' in environ
:
headers
['content-length'] = environ
['CONTENT_LENGTH']
self
.fp
= fp
or sys
.stdin
self
.outerboundary
= outerboundary
# Process content-disposition header
if 'content-disposition' in self
.headers
:
cdisp
, pdict
= parse_header(self
.headers
['content-disposition'])
self
.disposition_options
= pdict
self
.name
= pdict
['name']
self
.filename
= pdict
['filename']
# Process content-type header
# Honor any existing content-type header. But if there is no
# content-type header, use some sensible defaults. Assume
# outerboundary is "" at the outer level, but something non-false
# inside a multi-part. The default for an inner part is text/plain,
# but for an outer part it should be urlencoded. This should catch
# bogus clients which erroneously forget to include a content-type
# See below for what we do if there does exist a content-type header,
# but it happens to be something we don't understand.
if 'content-type' in self
.headers
:
ctype
, pdict
= parse_header(self
.headers
['content-type'])
elif self
.outerboundary
or method
!= 'POST':
ctype
, pdict
= "text/plain", {}
ctype
, pdict
= 'application/x-www-form-urlencoded', {}
self
.type_options
= pdict
self
.innerboundary
= pdict
['boundary']
if 'content-length' in self
.headers
:
clen
= int(self
.headers
['content-length'])
if maxlen
and clen
> maxlen
:
raise ValueError, 'Maximum content length exceeded'
self
.list = self
.file = None
if ctype
== 'application/x-www-form-urlencoded':
elif ctype
[:10] == 'multipart/':
self
.read_multi(environ
, keep_blank_values
, strict_parsing
)
"""Return a printable representation."""
return "FieldStorage(%r, %r, %r)" % (
self
.name
, self
.filename
, self
.value
)
def __getattr__(self
, name
):
raise AttributeError, name
elif self
.list is not None:
def __getitem__(self
, key
):
"""Dictionary style indexing."""
raise TypeError, "not indexable"
if item
.name
== key
: found
.append(item
)
def getvalue(self
, key
, default
=None):
"""Dictionary style get() method, including 'value' lookup."""
if type(value
) is type([]):
return map(lambda v
: v
.value
, value
)
def getfirst(self
, key
, default
=None):
""" Return the first value received."""
if type(value
) is type([]):
""" Return list of received values."""
if type(value
) is type([]):
return map(lambda v
: v
.value
, value
)
"""Dictionary style keys() method."""
raise TypeError, "not indexable"
if item
.name
not in keys
: keys
.append(item
.name
)
"""Dictionary style has_key() method."""
raise TypeError, "not indexable"
if item
.name
== key
: return True
def __contains__(self
, key
):
"""Dictionary style __contains__ method."""
raise TypeError, "not indexable"
if item
.name
== key
: return True
"""Dictionary style len(x) support."""
def read_urlencoded(self
):
"""Internal: read data in query string format."""
qs
= self
.fp
.read(self
.length
)
for key
, value
in parse_qsl(qs
, self
.keep_blank_values
,
list.append(MiniFieldStorage(key
, value
))
def read_multi(self
, environ
, keep_blank_values
, strict_parsing
):
"""Internal: read a part that is itself multipart."""
if not valid_boundary(ib
):
raise ValueError, 'Invalid boundary in multipart form: %r' % (ib
,)
klass
= self
.FieldStorageClass
or self
.__class
__
part
= klass(self
.fp
, {}, ib
,
environ
, keep_blank_values
, strict_parsing
)
headers
= rfc822
.Message(self
.fp
)
part
= klass(self
.fp
, headers
, ib
,
environ
, keep_blank_values
, strict_parsing
)
"""Internal: read an atomic part."""
bufsize
= 8*1024 # I/O buffering size for copy to file
"""Internal: read binary data."""
self
.file = self
.make_file('b')
data
= self
.fp
.read(min(todo
, self
.bufsize
))
"""Internal: read lines until EOF or outerboundary."""
self
.file = self
.__file
= StringIO()
self
.read_lines_to_outerboundary()
if self
.__file
is not None:
if self
.__file
.tell() + len(line
) > 1000:
self
.file = self
.make_file('')
self
.file.write(self
.__file
.getvalue())
def read_lines_to_eof(self
):
"""Internal: read lines until EOF."""
line
= self
.fp
.readline()
def read_lines_to_outerboundary(self
):
"""Internal: read lines until outerboundary."""
next
= "--" + self
.outerboundary
line
= self
.fp
.readline()
strippedline
= line
.strip()
self
.__write
(odelim
+ line
)
"""Internal: skip lines until outer boundary if defined."""
if not self
.outerboundary
or self
.done
:
next
= "--" + self
.outerboundary
line
= self
.fp
.readline()
strippedline
= line
.strip()
def make_file(self
, binary
=None):
"""Overridable: return a readable & writable file.
The file will be used as follows:
The 'binary' argument is unused -- the file is always opened
This version opens a temporary file for reading and writing,
and immediately deletes (unlinks) it. The trick (on Unix!) is
that the file can still be used, but it can't be opened by
another process, and it will automatically be deleted when it
is closed or when the current process terminates.
If you want a more permanent file, you derive a class which
overrides this method. If you want a visible temporary file
that is nevertheless automatically deleted when the script
terminates, try defining a __del__ method in a derived class
which unlinks the temporary files you have created.
return tempfile
.TemporaryFile("w+b")
# Backwards Compatibility Classes
# ===============================
class FormContentDict(UserDict
.UserDict
):
"""Form content as dictionary with a list of values per field.
form[key] -> [value, value, ...]
form.keys() -> [key, key, ...]
form.values() -> [[val, val, ...], [val, val, ...], ...]
form.items() -> [(key, [val, val, ...]), (key, [val, val, ...]), ...]
form.dict == {key: [val, val, ...], ...}
def __init__(self
, environ
=os
.environ
):
self
.dict = self
.data
= parse(environ
=environ
)
self
.query_string
= environ
['QUERY_STRING']
class SvFormContentDict(FormContentDict
):
"""Form content as dictionary expecting a single value per field.
If you only expect a single value for each field, then form[key]
will return that single value. It will raise an IndexError if
that expectation is not true. If you expect a field to have
possible multiple values, than you can use form.getlist(key) to
get all of the values. values() and items() are a compromise:
they return single strings where there is a single value, and
lists of strings otherwise.
def __getitem__(self
, key
):
if len(self
.dict[key
]) > 1:
raise IndexError, 'expecting a single value'
for value
in self
.dict.values():
else: result
.append(value
)
for key
, value
in self
.dict.items():
result
.append((key
, value
[0]))
else: result
.append((key
, value
))
class InterpFormContentDict(SvFormContentDict
):
"""This class is present for backwards compatibility only."""
def __getitem__(self
, key
):
v
= SvFormContentDict
.__getitem
__(self
, key
)
if v
[0] in '0123456789+-.':
result
.append(self
.dict[key
])
result
.append((key
, self
[key
]))
result
.append((key
, self
.dict[key
]))
class FormContent(FormContentDict
):
"""This class is present for backwards compatibility only."""
if key
in self
.dict :return self
.dict[key
]
def indexed_value(self
, key
, location
):
if len(self
.dict[key
]) > location
:
return self
.dict[key
][location
]
if key
in self
.dict: return self
.dict[key
][0]
return len(self
.dict[key
])
if key
in self
.dict: return self
.dict[key
][0].strip()
def test(environ
=os
.environ
):
"""Robust test CGI script, usable as main program.
Write minimal HTTP headers and dump all information provided to
print "Content-type: text/html"
form
= FieldStorage() # Replace with other classes to test those
exec "testing print_exception() -- <I>italics?</I>"
print "<H3>What follows is a test, not an actual exception:</H3>"
print "<H1>Second try with a small maxlen...</H1>"
form
= FieldStorage() # Replace with other classes to test those
def print_exception(type=None, value
=None, tb
=None, limit
=None):
type, value
, tb
= sys
.exc_info()
print "<H3>Traceback (most recent call last):</H3>"
list = traceback
.format_tb(tb
, limit
) + \
traceback
.format_exception_only(type, value
)
print "<PRE>%s<B>%s</B></PRE>" % (
escape("".join(list[:-1])),
def print_environ(environ
=os
.environ
):
"""Dump the shell environment as HTML."""
print "<H3>Shell Environment:</H3>"
print "<DT>", escape(key
), "<DD>", escape(environ
[key
])
"""Dump the contents of a form as HTML."""
print "<H3>Form Contents:</H3>"
print "<P>No form fields."
print "<DT>" + escape(key
) + ":",
print "<i>" + escape(repr(type(value
))) + "</i>"
print "<DD>" + escape(repr(value
))
"""Dump the current directory as HTML."""
print "<H3>Current Working Directory:</H3>"
print "os.error:", escape(str(msg
))
print "<H3>Command Line Arguments:</H3>"
def print_environ_usage():
"""Dump a list of environment variables used by CGI as HTML."""
<H3>These environment variables could have been set:</H3>
In addition, HTTP headers sent by the server may be passed in the
environment as well. Here are some common variable names:
def escape(s
, quote
=None):
"""Replace special characters '&', '<' and '>' by SGML entities."""
s
= s
.replace("&", "&") # Must be done first!
s
= s
.replace("<", "<")
s
= s
.replace(">", ">")
s
= s
.replace('"', """)
def valid_boundary(s
, _vb_pattern
="^[ -~]{0,200}[!-~]$"):
return re
.match(_vb_pattern
, s
)
# Call test() when this file is run as a script (not imported as a module)
if __name__
== '__main__':