cgi.py 33 KB

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