logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

cgi.py (34099B)


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