cgi.py 34 KB

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