cgi.py 34 KB

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