cgi.py 33 KB

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