cgi.py 34 KB

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