| 1 |
|
| 2 |
# type: ignore |
| 3 |
|
| 4 |
# cgithb library imported from python 3.12 |
| 5 |
# Distributed under the PSF license |
| 6 |
# https://docs.python.org/3/license.html |
| 7 |
|
| 8 |
|
| 9 |
# NOTE: the above "/usr/local/bin/python" is NOT a mistake. It is |
| 10 |
# intentionally NOT "/usr/bin/env python". On many systems |
| 11 |
# (e.g. Solaris), /usr/local/bin is not in $PATH as passed to CGI |
| 12 |
# scripts, and /usr/local/bin is the default directory where Python is |
| 13 |
# installed, so /usr/bin/env would be unable to find python. Granted, |
| 14 |
# binary installations by Linux vendors often install Python in |
| 15 |
# /usr/bin. So let those vendors patch cgi.py to match their choice |
| 16 |
# of installation. |
| 17 |
|
| 18 |
"""Support module for CGI (Common Gateway Interface) scripts. |
| 19 |
|
| 20 |
This module defines a number of utilities for use by CGI scripts |
| 21 |
written in Python. |
| 22 |
|
| 23 |
The global variable maxlen can be set to an integer indicating the maximum size |
| 24 |
of a POST request. POST requests larger than this size will result in a |
| 25 |
ValueError being raised during parsing. The default value of this variable is 0, |
| 26 |
meaning the request size is unlimited. |
| 27 |
""" |
| 28 |
|
| 29 |
# History |
| 30 |
# ------- |
| 31 |
# |
| 32 |
# Michael McLay started this module. Steve Majewski changed the |
| 33 |
# interface to SvFormContentDict and FormContentDict. The multipart |
| 34 |
# parsing was inspired by code submitted by Andreas Paepcke. Guido van |
| 35 |
# Rossum rewrote, reformatted and documented the module and is currently |
| 36 |
# responsible for its maintenance. |
| 37 |
# |
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
__version__ = "2.6" |
| 42 |
|
| 43 |
|
| 44 |
# Imports |
| 45 |
# ======= |
| 46 |
|
| 47 |
import html |
| 48 |
import locale |
| 49 |
import os |
| 50 |
import sys |
| 51 |
import tempfile |
| 52 |
import urllib.parse |
| 53 |
import warnings |
| 54 |
from collections.abc import Mapping |
| 55 |
from email.message import Message |
| 56 |
from email.parser import FeedParser |
| 57 |
from io import BytesIO, StringIO, TextIOWrapper |
| 58 |
|
| 59 |
__all__ = [ |
| 60 |
"MiniFieldStorage", |
| 61 |
"FieldStorage", |
| 62 |
"parse", |
| 63 |
"parse_multipart", |
| 64 |
"parse_header", |
| 65 |
"test", |
| 66 |
"print_exception", |
| 67 |
"print_environ", |
| 68 |
"print_form", |
| 69 |
"print_directory", |
| 70 |
"print_arguments", |
| 71 |
"print_environ_usage", |
| 72 |
] |
| 73 |
|
| 74 |
|
| 75 |
# warnings._deprecated(__name__, remove=(3, 13)) |
| 76 |
|
| 77 |
# Logging support |
| 78 |
# =============== |
| 79 |
|
| 80 |
logfile = "" # Filename to log to, if not empty |
| 81 |
logfp = None # File object to log to, if not None |
| 82 |
|
| 83 |
|
| 84 |
def initlog(*allargs): |
| 85 |
"""Write a log message, if there is a log file. |
| 86 |
|
| 87 |
Even though this function is called initlog(), you should always |
| 88 |
use log(); log is a variable that is set either to initlog |
| 89 |
(initially), to dolog (once the log file has been opened), or to |
| 90 |
nolog (when logging is disabled). |
| 91 |
|
| 92 |
The first argument is a format string; the remaining arguments (if |
| 93 |
any) are arguments to the % operator, so e.g. |
| 94 |
log("%s: %s", "a", "b") |
| 95 |
will write "a: b" to the log file, followed by a newline. |
| 96 |
|
| 97 |
If the global logfp is not None, it should be a file object to |
| 98 |
which log data is written. |
| 99 |
|
| 100 |
If the global logfp is None, the global logfile may be a string |
| 101 |
giving a filename to open, in append mode. This file should be |
| 102 |
world writable!!! If the file can't be opened, logging is |
| 103 |
silently disabled (since there is no safe place where we could |
| 104 |
send an error message). |
| 105 |
|
| 106 |
""" |
| 107 |
global log, logfile, logfp |
| 108 |
warnings.warn( |
| 109 |
"cgi.log() is deprecated as of 3.10. Use logging instead", |
| 110 |
DeprecationWarning, |
| 111 |
stacklevel=2, |
| 112 |
) |
| 113 |
if logfile and not logfp: |
| 114 |
try: |
| 115 |
logfp = open(logfile, "a", encoding="locale") |
| 116 |
except OSError: |
| 117 |
pass |
| 118 |
if not logfp: |
| 119 |
log = nolog |
| 120 |
else: |
| 121 |
log = dolog |
| 122 |
log(*allargs) |
| 123 |
|
| 124 |
|
| 125 |
def dolog(fmt, *args): |
| 126 |
"""Write a log message to the log file. See initlog() for docs.""" |
| 127 |
logfp.write(fmt % args + "\n") |
| 128 |
|
| 129 |
|
| 130 |
def nolog(*allargs): |
| 131 |
"""Dummy function, assigned to log when logging is disabled.""" |
| 132 |
pass |
| 133 |
|
| 134 |
|
| 135 |
def closelog(): |
| 136 |
"""Close the log file.""" |
| 137 |
global log, logfile, logfp |
| 138 |
logfile = "" |
| 139 |
if logfp: |
| 140 |
logfp.close() |
| 141 |
logfp = None |
| 142 |
log = initlog |
| 143 |
|
| 144 |
|
| 145 |
log = initlog # The current logging function |
| 146 |
|
| 147 |
|
| 148 |
# Parsing functions |
| 149 |
# ================= |
| 150 |
|
| 151 |
# Maximum input we will accept when REQUEST_METHOD is POST |
| 152 |
# 0 ==> unlimited input |
| 153 |
maxlen = 0 |
| 154 |
|
| 155 |
|
| 156 |
def parse( |
| 157 |
fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0, separator="&" |
| 158 |
): |
| 159 |
"""Parse a query in the environment or from a file (default stdin) |
| 160 |
|
| 161 |
Arguments, all optional: |
| 162 |
|
| 163 |
fp : file pointer; default: sys.stdin.buffer |
| 164 |
|
| 165 |
environ : environment dictionary; default: os.environ |
| 166 |
|
| 167 |
keep_blank_values: flag indicating whether blank values in |
| 168 |
percent-encoded forms should be treated as blank strings. |
| 169 |
A true value indicates that blanks should be retained as |
| 170 |
blank strings. The default false value indicates that |
| 171 |
blank values are to be ignored and treated as if they were |
| 172 |
not included. |
| 173 |
|
| 174 |
strict_parsing: flag indicating what to do with parsing errors. |
| 175 |
If false (the default), errors are silently ignored. |
| 176 |
If true, errors raise a ValueError exception. |
| 177 |
|
| 178 |
separator: str. The symbol to use for separating the query arguments. |
| 179 |
Defaults to &. |
| 180 |
""" |
| 181 |
if fp is None: |
| 182 |
fp = sys.stdin |
| 183 |
|
| 184 |
# field keys and values (except for files) are returned as strings |
| 185 |
# an encoding is required to decode the bytes read from self.fp |
| 186 |
if hasattr(fp, "encoding"): |
| 187 |
encoding = fp.encoding |
| 188 |
else: |
| 189 |
encoding = "latin-1" |
| 190 |
|
| 191 |
# fp.read() must return bytes |
| 192 |
if isinstance(fp, TextIOWrapper): |
| 193 |
fp = fp.buffer |
| 194 |
|
| 195 |
if not "REQUEST_METHOD" in environ: |
| 196 |
environ["REQUEST_METHOD"] = "GET" # For testing stand-alone |
| 197 |
if environ["REQUEST_METHOD"] == "POST": |
| 198 |
ctype, pdict = parse_header(environ["CONTENT_TYPE"]) |
| 199 |
if ctype == "multipart/form-data": |
| 200 |
return parse_multipart(fp, pdict, separator=separator) |
| 201 |
elif ctype == "application/x-www-form-urlencoded": |
| 202 |
clength = int(environ["CONTENT_LENGTH"]) |
| 203 |
if maxlen and clength > maxlen: |
| 204 |
raise ValueError("Maximum content length exceeded") |
| 205 |
qs = fp.read(clength).decode(encoding) |
| 206 |
else: |
| 207 |
qs = "" # Unknown content-type |
| 208 |
if "QUERY_STRING" in environ: |
| 209 |
if qs: |
| 210 |
qs = qs + "&" |
| 211 |
qs = qs + environ["QUERY_STRING"] |
| 212 |
elif sys.argv[1:]: |
| 213 |
if qs: |
| 214 |
qs = qs + "&" |
| 215 |
qs = qs + sys.argv[1] |
| 216 |
environ["QUERY_STRING"] = qs # XXX Shouldn't, really |
| 217 |
elif "QUERY_STRING" in environ: |
| 218 |
qs = environ["QUERY_STRING"] |
| 219 |
else: |
| 220 |
if sys.argv[1:]: |
| 221 |
qs = sys.argv[1] |
| 222 |
else: |
| 223 |
qs = "" |
| 224 |
environ["QUERY_STRING"] = qs # XXX Shouldn't, really |
| 225 |
return urllib.parse.parse_qs( |
| 226 |
qs, keep_blank_values, strict_parsing, encoding=encoding, separator=separator |
| 227 |
) |
| 228 |
|
| 229 |
|
| 230 |
def parse_multipart(fp, pdict, encoding="utf-8", errors="replace", separator="&"): |
| 231 |
"""Parse multipart input. |
| 232 |
|
| 233 |
Arguments: |
| 234 |
fp : input file |
| 235 |
pdict: dictionary containing other parameters of content-type header |
| 236 |
encoding, errors: request encoding and error handler, passed to |
| 237 |
FieldStorage |
| 238 |
|
| 239 |
Returns a dictionary just like parse_qs(): keys are the field names, each |
| 240 |
value is a list of values for that field. For non-file fields, the value |
| 241 |
is a list of strings. |
| 242 |
""" |
| 243 |
# RFC 2046, Section 5.1 : The "multipart" boundary delimiters are always |
| 244 |
# represented as 7bit US-ASCII. |
| 245 |
boundary = pdict["boundary"].decode("ascii") |
| 246 |
ctype = "multipart/form-data; boundary={}".format(boundary) |
| 247 |
headers = Message() |
| 248 |
headers.set_type(ctype) |
| 249 |
try: |
| 250 |
headers["Content-Length"] = pdict["CONTENT-LENGTH"] |
| 251 |
except KeyError: |
| 252 |
pass |
| 253 |
fs = FieldStorage( |
| 254 |
fp, |
| 255 |
headers=headers, |
| 256 |
encoding=encoding, |
| 257 |
errors=errors, |
| 258 |
environ={"REQUEST_METHOD": "POST"}, |
| 259 |
separator=separator, |
| 260 |
) |
| 261 |
return {k: fs.getlist(k) for k in fs} |
| 262 |
|
| 263 |
|
| 264 |
def _parseparam(s): |
| 265 |
while s[:1] == ";": |
| 266 |
s = s[1:] |
| 267 |
end = s.find(";") |
| 268 |
while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2: |
| 269 |
end = s.find(";", end + 1) |
| 270 |
if end < 0: |
| 271 |
end = len(s) |
| 272 |
f = s[:end] |
| 273 |
yield f.strip() |
| 274 |
s = s[end:] |
| 275 |
|
| 276 |
|
| 277 |
def parse_header(line): |
| 278 |
"""Parse a Content-type like header. |
| 279 |
|
| 280 |
Return the main content-type and a dictionary of options. |
| 281 |
|
| 282 |
""" |
| 283 |
parts = _parseparam(";" + line) |
| 284 |
key = parts.__next__() |
| 285 |
pdict = {} |
| 286 |
for p in parts: |
| 287 |
i = p.find("=") |
| 288 |
if i >= 0: |
| 289 |
name = p[:i].strip().lower() |
| 290 |
value = p[i + 1 :].strip() |
| 291 |
if len(value) >= 2 and value[0] == value[-1] == '"': |
| 292 |
value = value[1:-1] |
| 293 |
value = value.replace("\\\\", "\\").replace('\\"', '"') |
| 294 |
pdict[name] = value |
| 295 |
return key, pdict |
| 296 |
|
| 297 |
|
| 298 |
# Classes for field storage |
| 299 |
# ========================= |
| 300 |
|
| 301 |
|
| 302 |
class MiniFieldStorage: |
| 303 |
"""Like FieldStorage, for use when no file uploads are possible.""" |
| 304 |
|
| 305 |
# Dummy attributes |
| 306 |
filename = None |
| 307 |
list = None |
| 308 |
type = None |
| 309 |
file = None |
| 310 |
type_options = {} |
| 311 |
disposition = None |
| 312 |
disposition_options = {} |
| 313 |
headers = {} |
| 314 |
|
| 315 |
def __init__(self, name, value): |
| 316 |
"""Constructor from field name and value.""" |
| 317 |
self.name = name |
| 318 |
self.value = value |
| 319 |
# self.file = StringIO(value) |
| 320 |
|
| 321 |
def __repr__(self): |
| 322 |
"""Return printable representation.""" |
| 323 |
return "MiniFieldStorage(%r, %r)" % (self.name, self.value) |
| 324 |
|
| 325 |
|
| 326 |
class FieldStorage: |
| 327 |
"""Store a sequence of fields, reading multipart/form-data. |
| 328 |
|
| 329 |
This class provides naming, typing, files stored on disk, and |
| 330 |
more. At the top level, it is accessible like a dictionary, whose |
| 331 |
keys are the field names. (Note: None can occur as a field name.) |
| 332 |
The items are either a Python list (if there's multiple values) or |
| 333 |
another FieldStorage or MiniFieldStorage object. If it's a single |
| 334 |
object, it has the following attributes: |
| 335 |
|
| 336 |
name: the field name, if specified; otherwise None |
| 337 |
|
| 338 |
filename: the filename, if specified; otherwise None; this is the |
| 339 |
client side filename, *not* the file name on which it is |
| 340 |
stored (that's a temporary file you don't deal with) |
| 341 |
|
| 342 |
value: the value as a *string*; for file uploads, this |
| 343 |
transparently reads the file every time you request the value |
| 344 |
and returns *bytes* |
| 345 |
|
| 346 |
file: the file(-like) object from which you can read the data *as |
| 347 |
bytes* ; None if the data is stored a simple string |
| 348 |
|
| 349 |
type: the content-type, or None if not specified |
| 350 |
|
| 351 |
type_options: dictionary of options specified on the content-type |
| 352 |
line |
| 353 |
|
| 354 |
disposition: content-disposition, or None if not specified |
| 355 |
|
| 356 |
disposition_options: dictionary of corresponding options |
| 357 |
|
| 358 |
headers: a dictionary(-like) object (sometimes email.message.Message or a |
| 359 |
subclass thereof) containing *all* headers |
| 360 |
|
| 361 |
The class is subclassable, mostly for the purpose of overriding |
| 362 |
the make_file() method, which is called internally to come up with |
| 363 |
a file open for reading and writing. This makes it possible to |
| 364 |
override the default choice of storing all files in a temporary |
| 365 |
directory and unlinking them as soon as they have been opened. |
| 366 |
|
| 367 |
""" |
| 368 |
|
| 369 |
def __init__( |
| 370 |
self, |
| 371 |
fp=None, |
| 372 |
headers=None, |
| 373 |
outerboundary=b"", |
| 374 |
environ=os.environ, |
| 375 |
keep_blank_values=0, |
| 376 |
strict_parsing=0, |
| 377 |
limit=None, |
| 378 |
encoding="utf-8", |
| 379 |
errors="replace", |
| 380 |
max_num_fields=None, |
| 381 |
separator="&", |
| 382 |
): |
| 383 |
"""Constructor. Read multipart/* until last part. |
| 384 |
|
| 385 |
Arguments, all optional: |
| 386 |
|
| 387 |
fp : file pointer; default: sys.stdin.buffer |
| 388 |
(not used when the request method is GET) |
| 389 |
Can be : |
| 390 |
1. a TextIOWrapper object |
| 391 |
2. an object whose read() and readline() methods return bytes |
| 392 |
|
| 393 |
headers : header dictionary-like object; default: |
| 394 |
taken from environ as per CGI spec |
| 395 |
|
| 396 |
outerboundary : terminating multipart boundary |
| 397 |
(for internal use only) |
| 398 |
|
| 399 |
environ : environment dictionary; default: os.environ |
| 400 |
|
| 401 |
keep_blank_values: flag indicating whether blank values in |
| 402 |
percent-encoded forms should be treated as blank strings. |
| 403 |
A true value indicates that blanks should be retained as |
| 404 |
blank strings. The default false value indicates that |
| 405 |
blank values are to be ignored and treated as if they were |
| 406 |
not included. |
| 407 |
|
| 408 |
strict_parsing: flag indicating what to do with parsing errors. |
| 409 |
If false (the default), errors are silently ignored. |
| 410 |
If true, errors raise a ValueError exception. |
| 411 |
|
| 412 |
limit : used internally to read parts of multipart/form-data forms, |
| 413 |
to exit from the reading loop when reached. It is the difference |
| 414 |
between the form content-length and the number of bytes already |
| 415 |
read |
| 416 |
|
| 417 |
encoding, errors : the encoding and error handler used to decode the |
| 418 |
binary stream to strings. Must be the same as the charset defined |
| 419 |
for the page sending the form (content-type : meta http-equiv or |
| 420 |
header) |
| 421 |
|
| 422 |
max_num_fields: int. If set, then __init__ throws a ValueError |
| 423 |
if there are more than n fields read by parse_qsl(). |
| 424 |
|
| 425 |
""" |
| 426 |
method = "GET" |
| 427 |
self.keep_blank_values = keep_blank_values |
| 428 |
self.strict_parsing = strict_parsing |
| 429 |
self.max_num_fields = max_num_fields |
| 430 |
self.separator = separator |
| 431 |
if "REQUEST_METHOD" in environ: |
| 432 |
method = environ["REQUEST_METHOD"].upper() |
| 433 |
self.qs_on_post = None |
| 434 |
if method == "GET" or method == "HEAD": |
| 435 |
if "QUERY_STRING" in environ: |
| 436 |
qs = environ["QUERY_STRING"] |
| 437 |
elif sys.argv[1:]: |
| 438 |
qs = sys.argv[1] |
| 439 |
else: |
| 440 |
qs = "" |
| 441 |
qs = qs.encode(locale.getpreferredencoding(), "surrogateescape") |
| 442 |
fp = BytesIO(qs) |
| 443 |
if headers is None: |
| 444 |
headers = {"content-type": "application/x-www-form-urlencoded"} |
| 445 |
if headers is None: |
| 446 |
headers = {} |
| 447 |
if method == "POST": |
| 448 |
# Set default content-type for POST to what's traditional |
| 449 |
headers["content-type"] = "application/x-www-form-urlencoded" |
| 450 |
if "CONTENT_TYPE" in environ: |
| 451 |
headers["content-type"] = environ["CONTENT_TYPE"] |
| 452 |
if "QUERY_STRING" in environ: |
| 453 |
self.qs_on_post = environ["QUERY_STRING"] |
| 454 |
if "CONTENT_LENGTH" in environ: |
| 455 |
headers["content-length"] = environ["CONTENT_LENGTH"] |
| 456 |
else: |
| 457 |
if not (isinstance(headers, (Mapping, Message))): |
| 458 |
raise TypeError( |
| 459 |
"headers must be mapping or an instance of " "email.message.Message" |
| 460 |
) |
| 461 |
self.headers = headers |
| 462 |
if fp is None: |
| 463 |
self.fp = sys.stdin.buffer |
| 464 |
# self.fp.read() must return bytes |
| 465 |
elif isinstance(fp, TextIOWrapper): |
| 466 |
self.fp = fp.buffer |
| 467 |
else: |
| 468 |
if not (hasattr(fp, "read") and hasattr(fp, "readline")): |
| 469 |
raise TypeError("fp must be file pointer") |
| 470 |
self.fp = fp |
| 471 |
|
| 472 |
self.encoding = encoding |
| 473 |
self.errors = errors |
| 474 |
|
| 475 |
if not isinstance(outerboundary, bytes): |
| 476 |
raise TypeError( |
| 477 |
"outerboundary must be bytes, not %s" % type(outerboundary).__name__ |
| 478 |
) |
| 479 |
self.outerboundary = outerboundary |
| 480 |
|
| 481 |
self.bytes_read = 0 |
| 482 |
self.limit = limit |
| 483 |
|
| 484 |
# Process content-disposition header |
| 485 |
cdisp, pdict = "", {} |
| 486 |
if "content-disposition" in self.headers: |
| 487 |
cdisp, pdict = parse_header(self.headers["content-disposition"]) |
| 488 |
self.disposition = cdisp |
| 489 |
self.disposition_options = pdict |
| 490 |
self.name = None |
| 491 |
if "name" in pdict: |
| 492 |
self.name = pdict["name"] |
| 493 |
self.filename = None |
| 494 |
if "filename" in pdict: |
| 495 |
self.filename = pdict["filename"] |
| 496 |
self._binary_file = self.filename is not None |
| 497 |
|
| 498 |
# Process content-type header |
| 499 |
# |
| 500 |
# Honor any existing content-type header. But if there is no |
| 501 |
# content-type header, use some sensible defaults. Assume |
| 502 |
# outerboundary is "" at the outer level, but something non-false |
| 503 |
# inside a multi-part. The default for an inner part is text/plain, |
| 504 |
# but for an outer part it should be urlencoded. This should catch |
| 505 |
# bogus clients which erroneously forget to include a content-type |
| 506 |
# header. |
| 507 |
# |
| 508 |
# See below for what we do if there does exist a content-type header, |
| 509 |
# but it happens to be something we don't understand. |
| 510 |
if "content-type" in self.headers: |
| 511 |
ctype, pdict = parse_header(self.headers["content-type"]) |
| 512 |
elif self.outerboundary or method != "POST": |
| 513 |
ctype, pdict = "text/plain", {} |
| 514 |
else: |
| 515 |
ctype, pdict = "application/x-www-form-urlencoded", {} |
| 516 |
self.type = ctype |
| 517 |
self.type_options = pdict |
| 518 |
if "boundary" in pdict: |
| 519 |
self.innerboundary = pdict["boundary"].encode(self.encoding, self.errors) |
| 520 |
else: |
| 521 |
self.innerboundary = b"" |
| 522 |
|
| 523 |
clen = -1 |
| 524 |
if "content-length" in self.headers: |
| 525 |
try: |
| 526 |
clen = int(self.headers["content-length"]) |
| 527 |
except ValueError: |
| 528 |
pass |
| 529 |
if maxlen and clen > maxlen: |
| 530 |
raise ValueError("Maximum content length exceeded") |
| 531 |
self.length = clen |
| 532 |
if self.limit is None and clen >= 0: |
| 533 |
self.limit = clen |
| 534 |
|
| 535 |
self.list = self.file = None |
| 536 |
self.done = 0 |
| 537 |
if ctype == "application/x-www-form-urlencoded": |
| 538 |
self.read_urlencoded() |
| 539 |
elif ctype[:10] == "multipart/": |
| 540 |
self.read_multi(environ, keep_blank_values, strict_parsing) |
| 541 |
else: |
| 542 |
self.read_single() |
| 543 |
|
| 544 |
def __del__(self): |
| 545 |
try: |
| 546 |
self.file.close() |
| 547 |
except AttributeError: |
| 548 |
pass |
| 549 |
|
| 550 |
def __enter__(self): |
| 551 |
return self |
| 552 |
|
| 553 |
def __exit__(self, *args): |
| 554 |
self.file.close() |
| 555 |
|
| 556 |
def __repr__(self): |
| 557 |
"""Return a printable representation.""" |
| 558 |
return "FieldStorage(%r, %r, %r)" % (self.name, self.filename, self.value) |
| 559 |
|
| 560 |
def __iter__(self): |
| 561 |
return iter(self.keys()) |
| 562 |
|
| 563 |
def __getattr__(self, name): |
| 564 |
if name != "value": |
| 565 |
raise AttributeError(name) |
| 566 |
if self.file: |
| 567 |
self.file.seek(0) |
| 568 |
value = self.file.read() |
| 569 |
self.file.seek(0) |
| 570 |
elif self.list is not None: |
| 571 |
value = self.list |
| 572 |
else: |
| 573 |
value = None |
| 574 |
return value |
| 575 |
|
| 576 |
def __getitem__(self, key): |
| 577 |
"""Dictionary style indexing.""" |
| 578 |
if self.list is None: |
| 579 |
raise TypeError("not indexable") |
| 580 |
found = [] |
| 581 |
for item in self.list: |
| 582 |
if item.name == key: |
| 583 |
found.append(item) |
| 584 |
if not found: |
| 585 |
raise KeyError(key) |
| 586 |
if len(found) == 1: |
| 587 |
return found[0] |
| 588 |
else: |
| 589 |
return found |
| 590 |
|
| 591 |
def getvalue(self, key, default=None): |
| 592 |
"""Dictionary style get() method, including 'value' lookup.""" |
| 593 |
if key in self: |
| 594 |
value = self[key] |
| 595 |
if isinstance(value, list): |
| 596 |
return [x.value for x in value] |
| 597 |
else: |
| 598 |
return value.value |
| 599 |
else: |
| 600 |
return default |
| 601 |
|
| 602 |
def getfirst(self, key, default=None): |
| 603 |
"""Return the first value received.""" |
| 604 |
if key in self: |
| 605 |
value = self[key] |
| 606 |
if isinstance(value, list): |
| 607 |
return value[0].value |
| 608 |
else: |
| 609 |
return value.value |
| 610 |
else: |
| 611 |
return default |
| 612 |
|
| 613 |
def getlist(self, key): |
| 614 |
"""Return list of received values.""" |
| 615 |
if key in self: |
| 616 |
value = self[key] |
| 617 |
if isinstance(value, list): |
| 618 |
return [x.value for x in value] |
| 619 |
else: |
| 620 |
return [value.value] |
| 621 |
else: |
| 622 |
return [] |
| 623 |
|
| 624 |
def keys(self): |
| 625 |
"""Dictionary style keys() method.""" |
| 626 |
if self.list is None: |
| 627 |
raise TypeError("not indexable") |
| 628 |
return list(set(item.name for item in self.list)) |
| 629 |
|
| 630 |
def __contains__(self, key): |
| 631 |
"""Dictionary style __contains__ method.""" |
| 632 |
if self.list is None: |
| 633 |
raise TypeError("not indexable") |
| 634 |
return any(item.name == key for item in self.list) |
| 635 |
|
| 636 |
def __len__(self): |
| 637 |
"""Dictionary style len(x) support.""" |
| 638 |
return len(self.keys()) |
| 639 |
|
| 640 |
def __bool__(self): |
| 641 |
if self.list is None: |
| 642 |
raise TypeError("Cannot be converted to bool.") |
| 643 |
return bool(self.list) |
| 644 |
|
| 645 |
def read_urlencoded(self): |
| 646 |
"""Internal: read data in query string format.""" |
| 647 |
qs = self.fp.read(self.length) |
| 648 |
if not isinstance(qs, bytes): |
| 649 |
raise ValueError( |
| 650 |
"%s should return bytes, got %s" % (self.fp, type(qs).__name__) |
| 651 |
) |
| 652 |
qs = qs.decode(self.encoding, self.errors) |
| 653 |
if self.qs_on_post: |
| 654 |
qs += "&" + self.qs_on_post |
| 655 |
query = urllib.parse.parse_qsl( |
| 656 |
qs, |
| 657 |
self.keep_blank_values, |
| 658 |
self.strict_parsing, |
| 659 |
encoding=self.encoding, |
| 660 |
errors=self.errors, |
| 661 |
max_num_fields=self.max_num_fields, |
| 662 |
separator=self.separator, |
| 663 |
) |
| 664 |
self.list = [MiniFieldStorage(key, value) for key, value in query] |
| 665 |
self.skip_lines() |
| 666 |
|
| 667 |
FieldStorageClass = None |
| 668 |
|
| 669 |
def read_multi(self, environ, keep_blank_values, strict_parsing): |
| 670 |
"""Internal: read a part that is itself multipart.""" |
| 671 |
ib = self.innerboundary |
| 672 |
if not valid_boundary(ib): |
| 673 |
raise ValueError("Invalid boundary in multipart form: %r" % (ib,)) |
| 674 |
self.list = [] |
| 675 |
if self.qs_on_post: |
| 676 |
query = urllib.parse.parse_qsl( |
| 677 |
self.qs_on_post, |
| 678 |
self.keep_blank_values, |
| 679 |
self.strict_parsing, |
| 680 |
encoding=self.encoding, |
| 681 |
errors=self.errors, |
| 682 |
max_num_fields=self.max_num_fields, |
| 683 |
separator=self.separator, |
| 684 |
) |
| 685 |
self.list.extend(MiniFieldStorage(key, value) for key, value in query) |
| 686 |
|
| 687 |
klass = self.FieldStorageClass or self.__class__ |
| 688 |
first_line = self.fp.readline() # bytes |
| 689 |
if not isinstance(first_line, bytes): |
| 690 |
raise ValueError( |
| 691 |
"%s should return bytes, got %s" % (self.fp, type(first_line).__name__) |
| 692 |
) |
| 693 |
self.bytes_read += len(first_line) |
| 694 |
|
| 695 |
# Ensure that we consume the file until we've hit our inner boundary |
| 696 |
while first_line.strip() != (b"--" + self.innerboundary) and first_line: |
| 697 |
first_line = self.fp.readline() |
| 698 |
self.bytes_read += len(first_line) |
| 699 |
|
| 700 |
# Propagate max_num_fields into the sub class appropriately |
| 701 |
max_num_fields = self.max_num_fields |
| 702 |
if max_num_fields is not None: |
| 703 |
max_num_fields -= len(self.list) |
| 704 |
|
| 705 |
while True: |
| 706 |
parser = FeedParser() |
| 707 |
hdr_text = b"" |
| 708 |
while True: |
| 709 |
data = self.fp.readline() |
| 710 |
hdr_text += data |
| 711 |
if not data.strip(): |
| 712 |
break |
| 713 |
if not hdr_text: |
| 714 |
break |
| 715 |
# parser takes strings, not bytes |
| 716 |
self.bytes_read += len(hdr_text) |
| 717 |
parser.feed(hdr_text.decode(self.encoding, self.errors)) |
| 718 |
headers = parser.close() |
| 719 |
|
| 720 |
# Some clients add Content-Length for part headers, ignore them |
| 721 |
if "content-length" in headers: |
| 722 |
del headers["content-length"] |
| 723 |
|
| 724 |
limit = None if self.limit is None else self.limit - self.bytes_read |
| 725 |
part = klass( |
| 726 |
self.fp, |
| 727 |
headers, |
| 728 |
ib, |
| 729 |
environ, |
| 730 |
keep_blank_values, |
| 731 |
strict_parsing, |
| 732 |
limit, |
| 733 |
self.encoding, |
| 734 |
self.errors, |
| 735 |
max_num_fields, |
| 736 |
self.separator, |
| 737 |
) |
| 738 |
|
| 739 |
if max_num_fields is not None: |
| 740 |
max_num_fields -= 1 |
| 741 |
if part.list: |
| 742 |
max_num_fields -= len(part.list) |
| 743 |
if max_num_fields < 0: |
| 744 |
raise ValueError("Max number of fields exceeded") |
| 745 |
|
| 746 |
self.bytes_read += part.bytes_read |
| 747 |
self.list.append(part) |
| 748 |
if part.done or self.bytes_read >= self.length > 0: |
| 749 |
break |
| 750 |
self.skip_lines() |
| 751 |
|
| 752 |
def read_single(self): |
| 753 |
"""Internal: read an atomic part.""" |
| 754 |
if self.length >= 0: |
| 755 |
self.read_binary() |
| 756 |
self.skip_lines() |
| 757 |
else: |
| 758 |
self.read_lines() |
| 759 |
self.file.seek(0) |
| 760 |
|
| 761 |
bufsize = 8 * 1024 # I/O buffering size for copy to file |
| 762 |
|
| 763 |
def read_binary(self): |
| 764 |
"""Internal: read binary data.""" |
| 765 |
self.file = self.make_file() |
| 766 |
todo = self.length |
| 767 |
if todo >= 0: |
| 768 |
while todo > 0: |
| 769 |
data = self.fp.read(min(todo, self.bufsize)) # bytes |
| 770 |
if not isinstance(data, bytes): |
| 771 |
raise ValueError( |
| 772 |
"%s should return bytes, got %s" |
| 773 |
% (self.fp, type(data).__name__) |
| 774 |
) |
| 775 |
self.bytes_read += len(data) |
| 776 |
if not data: |
| 777 |
self.done = -1 |
| 778 |
break |
| 779 |
self.file.write(data) |
| 780 |
todo = todo - len(data) |
| 781 |
|
| 782 |
def read_lines(self): |
| 783 |
"""Internal: read lines until EOF or outerboundary.""" |
| 784 |
if self._binary_file: |
| 785 |
self.file = self.__file = BytesIO() # store data as bytes for files |
| 786 |
else: |
| 787 |
self.file = self.__file = StringIO() # as strings for other fields |
| 788 |
if self.outerboundary: |
| 789 |
self.read_lines_to_outerboundary() |
| 790 |
else: |
| 791 |
self.read_lines_to_eof() |
| 792 |
|
| 793 |
def __write(self, line): |
| 794 |
"""line is always bytes, not string""" |
| 795 |
if self.__file is not None: |
| 796 |
if self.__file.tell() + len(line) > 1000: |
| 797 |
self.file = self.make_file() |
| 798 |
data = self.__file.getvalue() |
| 799 |
self.file.write(data) |
| 800 |
self.__file = None |
| 801 |
if self._binary_file: |
| 802 |
# keep bytes |
| 803 |
self.file.write(line) |
| 804 |
else: |
| 805 |
# decode to string |
| 806 |
self.file.write(line.decode(self.encoding, self.errors)) |
| 807 |
|
| 808 |
def read_lines_to_eof(self): |
| 809 |
"""Internal: read lines until EOF.""" |
| 810 |
while 1: |
| 811 |
line = self.fp.readline(1 << 16) # bytes |
| 812 |
self.bytes_read += len(line) |
| 813 |
if not line: |
| 814 |
self.done = -1 |
| 815 |
break |
| 816 |
self.__write(line) |
| 817 |
|
| 818 |
def read_lines_to_outerboundary(self): |
| 819 |
"""Internal: read lines until outerboundary. |
| 820 |
Data is read as bytes: boundaries and line ends must be converted |
| 821 |
to bytes for comparisons. |
| 822 |
""" |
| 823 |
next_boundary = b"--" + self.outerboundary |
| 824 |
last_boundary = next_boundary + b"--" |
| 825 |
delim = b"" |
| 826 |
last_line_lfend = True |
| 827 |
_read = 0 |
| 828 |
while 1: |
| 829 |
|
| 830 |
if self.limit is not None and 0 <= self.limit <= _read: |
| 831 |
break |
| 832 |
line = self.fp.readline(1 << 16) # bytes |
| 833 |
self.bytes_read += len(line) |
| 834 |
_read += len(line) |
| 835 |
if not line: |
| 836 |
self.done = -1 |
| 837 |
break |
| 838 |
if delim == b"\r": |
| 839 |
line = delim + line |
| 840 |
delim = b"" |
| 841 |
if line.startswith(b"--") and last_line_lfend: |
| 842 |
strippedline = line.rstrip() |
| 843 |
if strippedline == next_boundary: |
| 844 |
break |
| 845 |
if strippedline == last_boundary: |
| 846 |
self.done = 1 |
| 847 |
break |
| 848 |
odelim = delim |
| 849 |
if line.endswith(b"\r\n"): |
| 850 |
delim = b"\r\n" |
| 851 |
line = line[:-2] |
| 852 |
last_line_lfend = True |
| 853 |
elif line.endswith(b"\n"): |
| 854 |
delim = b"\n" |
| 855 |
line = line[:-1] |
| 856 |
last_line_lfend = True |
| 857 |
elif line.endswith(b"\r"): |
| 858 |
# We may interrupt \r\n sequences if they span the 2**16 |
| 859 |
# byte boundary |
| 860 |
delim = b"\r" |
| 861 |
line = line[:-1] |
| 862 |
last_line_lfend = False |
| 863 |
else: |
| 864 |
delim = b"" |
| 865 |
last_line_lfend = False |
| 866 |
self.__write(odelim + line) |
| 867 |
|
| 868 |
def skip_lines(self): |
| 869 |
"""Internal: skip lines until outer boundary if defined.""" |
| 870 |
if not self.outerboundary or self.done: |
| 871 |
return |
| 872 |
next_boundary = b"--" + self.outerboundary |
| 873 |
last_boundary = next_boundary + b"--" |
| 874 |
last_line_lfend = True |
| 875 |
while True: |
| 876 |
line = self.fp.readline(1 << 16) |
| 877 |
self.bytes_read += len(line) |
| 878 |
if not line: |
| 879 |
self.done = -1 |
| 880 |
break |
| 881 |
if line.endswith(b"--") and last_line_lfend: |
| 882 |
strippedline = line.strip() |
| 883 |
if strippedline == next_boundary: |
| 884 |
break |
| 885 |
if strippedline == last_boundary: |
| 886 |
self.done = 1 |
| 887 |
break |
| 888 |
last_line_lfend = line.endswith(b"\n") |
| 889 |
|
| 890 |
def make_file(self): |
| 891 |
"""Overridable: return a readable & writable file. |
| 892 |
|
| 893 |
The file will be used as follows: |
| 894 |
- data is written to it |
| 895 |
- seek(0) |
| 896 |
- data is read from it |
| 897 |
|
| 898 |
The file is opened in binary mode for files, in text mode |
| 899 |
for other fields |
| 900 |
|
| 901 |
This version opens a temporary file for reading and writing, |
| 902 |
and immediately deletes (unlinks) it. The trick (on Unix!) is |
| 903 |
that the file can still be used, but it can't be opened by |
| 904 |
another process, and it will automatically be deleted when it |
| 905 |
is closed or when the current process terminates. |
| 906 |
|
| 907 |
If you want a more permanent file, you derive a class which |
| 908 |
overrides this method. If you want a visible temporary file |
| 909 |
that is nevertheless automatically deleted when the script |
| 910 |
terminates, try defining a __del__ method in a derived class |
| 911 |
which unlinks the temporary files you have created. |
| 912 |
|
| 913 |
""" |
| 914 |
if self._binary_file: |
| 915 |
return tempfile.TemporaryFile("wb+") |
| 916 |
else: |
| 917 |
return tempfile.TemporaryFile("w+", encoding=self.encoding, newline="\n") |
| 918 |
|
| 919 |
|
| 920 |
# Test/debug code |
| 921 |
# =============== |
| 922 |
|
| 923 |
|
| 924 |
def test(environ=os.environ): |
| 925 |
"""Robust test CGI script, usable as main program. |
| 926 |
|
| 927 |
Write minimal HTTP headers and dump all information provided to |
| 928 |
the script in HTML form. |
| 929 |
|
| 930 |
""" |
| 931 |
print("Content-type: text/html") |
| 932 |
print() |
| 933 |
sys.stderr = sys.stdout |
| 934 |
try: |
| 935 |
form = FieldStorage() # Replace with other classes to test those |
| 936 |
print_directory() |
| 937 |
print_arguments() |
| 938 |
print_form(form) |
| 939 |
print_environ(environ) |
| 940 |
print_environ_usage() |
| 941 |
|
| 942 |
def f(): |
| 943 |
exec("testing print_exception() -- <I>italics?</I>") |
| 944 |
|
| 945 |
def g(f=f): |
| 946 |
f() |
| 947 |
|
| 948 |
print("<H3>What follows is a test, not an actual exception:</H3>") |
| 949 |
g() |
| 950 |
except: |
| 951 |
print_exception() |
| 952 |
|
| 953 |
print("<H1>Second try with a small maxlen...</H1>") |
| 954 |
|
| 955 |
global maxlen |
| 956 |
maxlen = 50 |
| 957 |
try: |
| 958 |
form = FieldStorage() # Replace with other classes to test those |
| 959 |
print_directory() |
| 960 |
print_arguments() |
| 961 |
print_form(form) |
| 962 |
print_environ(environ) |
| 963 |
except: |
| 964 |
print_exception() |
| 965 |
|
| 966 |
|
| 967 |
def print_exception(type=None, value=None, tb=None, limit=None): |
| 968 |
if type is None: |
| 969 |
type, value, tb = sys.exc_info() |
| 970 |
import traceback |
| 971 |
|
| 972 |
print() |
| 973 |
print("<H3>Traceback (most recent call last):</H3>") |
| 974 |
list = traceback.format_tb(tb, limit) + traceback.format_exception_only(type, value) |
| 975 |
print( |
| 976 |
"<PRE>%s<B>%s</B></PRE>" |
| 977 |
% ( |
| 978 |
html.escape("".join(list[:-1])), |
| 979 |
html.escape(list[-1]), |
| 980 |
) |
| 981 |
) |
| 982 |
del tb |
| 983 |
|
| 984 |
|
| 985 |
def print_environ(environ=os.environ): |
| 986 |
"""Dump the shell environment as HTML.""" |
| 987 |
keys = sorted(environ.keys()) |
| 988 |
print() |
| 989 |
print("<H3>Shell Environment:</H3>") |
| 990 |
print("<DL>") |
| 991 |
for key in keys: |
| 992 |
print("<DT>", html.escape(key), "<DD>", html.escape(environ[key])) |
| 993 |
print("</DL>") |
| 994 |
print() |
| 995 |
|
| 996 |
|
| 997 |
def print_form(form): |
| 998 |
"""Dump the contents of a form as HTML.""" |
| 999 |
keys = sorted(form.keys()) |
| 1000 |
print() |
| 1001 |
print("<H3>Form Contents:</H3>") |
| 1002 |
if not keys: |
| 1003 |
print("<P>No form fields.") |
| 1004 |
print("<DL>") |
| 1005 |
for key in keys: |
| 1006 |
print("<DT>" + html.escape(key) + ":", end=" ") |
| 1007 |
value = form[key] |
| 1008 |
print("<i>" + html.escape(repr(type(value))) + "</i>") |
| 1009 |
print("<DD>" + html.escape(repr(value))) |
| 1010 |
print("</DL>") |
| 1011 |
print() |
| 1012 |
|
| 1013 |
|
| 1014 |
def print_directory(): |
| 1015 |
"""Dump the current directory as HTML.""" |
| 1016 |
print() |
| 1017 |
print("<H3>Current Working Directory:</H3>") |
| 1018 |
try: |
| 1019 |
pwd = os.getcwd() |
| 1020 |
except OSError as msg: |
| 1021 |
print("OSError:", html.escape(str(msg))) |
| 1022 |
else: |
| 1023 |
print(html.escape(pwd)) |
| 1024 |
print() |
| 1025 |
|
| 1026 |
|
| 1027 |
def print_arguments(): |
| 1028 |
print() |
| 1029 |
print("<H3>Command Line Arguments:</H3>") |
| 1030 |
print() |
| 1031 |
print(sys.argv) |
| 1032 |
print() |
| 1033 |
|
| 1034 |
|
| 1035 |
def print_environ_usage(): |
| 1036 |
"""Dump a list of environment variables used by CGI as HTML.""" |
| 1037 |
print( |
| 1038 |
""" |
| 1039 |
<H3>These environment variables could have been set:</H3> |
| 1040 |
<UL> |
| 1041 |
<LI>AUTH_TYPE |
| 1042 |
<LI>CONTENT_LENGTH |
| 1043 |
<LI>CONTENT_TYPE |
| 1044 |
<LI>DATE_GMT |
| 1045 |
<LI>DATE_LOCAL |
| 1046 |
<LI>DOCUMENT_NAME |
| 1047 |
<LI>DOCUMENT_ROOT |
| 1048 |
<LI>DOCUMENT_URI |
| 1049 |
<LI>GATEWAY_INTERFACE |
| 1050 |
<LI>LAST_MODIFIED |
| 1051 |
<LI>PATH |
| 1052 |
<LI>PATH_INFO |
| 1053 |
<LI>PATH_TRANSLATED |
| 1054 |
<LI>QUERY_STRING |
| 1055 |
<LI>REMOTE_ADDR |
| 1056 |
<LI>REMOTE_HOST |
| 1057 |
<LI>REMOTE_IDENT |
| 1058 |
<LI>REMOTE_USER |
| 1059 |
<LI>REQUEST_METHOD |
| 1060 |
<LI>SCRIPT_NAME |
| 1061 |
<LI>SERVER_NAME |
| 1062 |
<LI>SERVER_PORT |
| 1063 |
<LI>SERVER_PROTOCOL |
| 1064 |
<LI>SERVER_ROOT |
| 1065 |
<LI>SERVER_SOFTWARE |
| 1066 |
</UL> |
| 1067 |
In addition, HTTP headers sent by the server may be passed in the |
| 1068 |
environment as well. Here are some common variable names: |
| 1069 |
<UL> |
| 1070 |
<LI>HTTP_ACCEPT |
| 1071 |
<LI>HTTP_CONNECTION |
| 1072 |
<LI>HTTP_HOST |
| 1073 |
<LI>HTTP_PRAGMA |
| 1074 |
<LI>HTTP_REFERER |
| 1075 |
<LI>HTTP_USER_AGENT |
| 1076 |
</UL> |
| 1077 |
""" |
| 1078 |
) |
| 1079 |
|
| 1080 |
|
| 1081 |
# Utilities |
| 1082 |
# ========= |
| 1083 |
|
| 1084 |
|
| 1085 |
def valid_boundary(s): |
| 1086 |
import re |
| 1087 |
|
| 1088 |
if isinstance(s, bytes): |
| 1089 |
_vb_pattern = b"^[ -~]{0,200}[!-~]$" |
| 1090 |
else: |
| 1091 |
_vb_pattern = "^[ -~]{0,200}[!-~]$" |
| 1092 |
return re.match(_vb_pattern, s) |
| 1093 |
|
| 1094 |
|
| 1095 |
# Invoke mainline |
| 1096 |
# =============== |
| 1097 |
|
| 1098 |
# Call test() when this file is run as a script (not imported as a module) |
| 1099 |
if __name__ == "__main__": |
| 1100 |
test() |