PageRenderTime 50ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/Backend/lib/cgi.boa

https://bitbucket.org/AdamMil/boaold
Python | 1054 lines | 1014 code | 11 blank | 29 comment | 2 complexity | 4b1f2b962ecd559a34bb954ca58cb4c5 MD5 | raw file
Possible License(s): GPL-2.0
  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. # XXX Perhaps there should be a slimmed version that doesn't contain
  15. # all those backwards compatible and debugging classes and functions?
  16. # History
  17. # -------
  18. #
  19. # Michael McLay started this module. Steve Majewski changed the
  20. # interface to SvFormContentDict and FormContentDict. The multipart
  21. # parsing was inspired by code submitted by Andreas Paepcke. Guido van
  22. # Rossum rewrote, reformatted and documented the module and is currently
  23. # responsible for its maintenance.
  24. #
  25. __version__ = "2.6"
  26. # Imports
  27. # =======
  28. import sys
  29. import os
  30. import urllib
  31. import mimetools
  32. import rfc822
  33. import UserDict
  34. from StringIO import StringIO
  35. __all__ = ["MiniFieldStorage", "FieldStorage", "FormContentDict",
  36. "SvFormContentDict", "InterpFormContentDict", "FormContent",
  37. "parse", "parse_qs", "parse_qsl", "parse_multipart",
  38. "parse_header", "print_exception", "print_environ",
  39. "print_form", "print_directory", "print_arguments",
  40. "print_environ_usage", "escape"]
  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 logfp, log
  64. if logfile and not logfp:
  65. try:
  66. logfp = open(logfile, "a")
  67. except IOError:
  68. pass
  69. if not logfp:
  70. log = nolog
  71. else:
  72. log = dolog
  73. log(*allargs)
  74. def dolog(fmt, *args):
  75. """Write a log message to the log file. See initlog() for docs."""
  76. logfp.write(fmt%args + "\n")
  77. def nolog(*allargs):
  78. """Dummy function, assigned to log when logging is disabled."""
  79. pass
  80. log = initlog # The current logging function
  81. # Parsing functions
  82. # =================
  83. # Maximum input we will accept when REQUEST_METHOD is POST
  84. # 0 ==> unlimited input
  85. maxlen = 0
  86. def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0):
  87. """Parse a query in the environment or from a file (default stdin)
  88. Arguments, all optional:
  89. fp : file pointer; default: sys.stdin
  90. environ : environment dictionary; default: os.environ
  91. keep_blank_values: flag indicating whether blank values in
  92. URL encoded forms should be treated as blank strings.
  93. A true value indicates that blanks should be retained as
  94. blank strings. The default false value indicates that
  95. blank values are to be ignored and treated as if they were
  96. not included.
  97. strict_parsing: flag indicating what to do with parsing errors.
  98. If false (the default), errors are silently ignored.
  99. If true, errors raise a ValueError exception.
  100. """
  101. if fp is None:
  102. fp = sys.stdin
  103. if not 'REQUEST_METHOD' in environ:
  104. environ['REQUEST_METHOD'] = 'GET' # For testing stand-alone
  105. if environ['REQUEST_METHOD'] == 'POST':
  106. ctype, pdict = parse_header(environ['CONTENT_TYPE'])
  107. if ctype == 'multipart/form-data':
  108. return parse_multipart(fp, pdict)
  109. elif ctype == 'application/x-www-form-urlencoded':
  110. clength = int(environ['CONTENT_LENGTH'])
  111. if maxlen and clength > maxlen:
  112. raise ValueError('Maximum content length exceeded')
  113. qs = fp.read(clength)
  114. else:
  115. qs = '' # Unknown content-type
  116. if 'QUERY_STRING' in environ:
  117. if qs: qs = qs + '&'
  118. qs = qs + environ['QUERY_STRING']
  119. elif sys.argv[1:]:
  120. if qs: qs = qs + '&'
  121. qs = qs + sys.argv[1]
  122. environ['QUERY_STRING'] = qs # XXX Shouldn't, really
  123. elif 'QUERY_STRING' in environ:
  124. qs = environ['QUERY_STRING']
  125. else:
  126. if sys.argv[1:]:
  127. qs = sys.argv[1]
  128. else:
  129. qs = ""
  130. environ['QUERY_STRING'] = qs # XXX Shouldn't, really
  131. return parse_qs(qs, keep_blank_values, strict_parsing)
  132. def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
  133. """Parse a query given as a string argument.
  134. Arguments:
  135. qs: URL-encoded query string to be parsed
  136. keep_blank_values: flag indicating whether blank values in
  137. URL encoded queries should be treated as blank strings.
  138. A true value indicates that blanks should be retained as
  139. blank strings. The default false value indicates that
  140. blank values are to be ignored and treated as if they were
  141. not included.
  142. strict_parsing: flag indicating what to do with parsing errors.
  143. If false (the default), errors are silently ignored.
  144. If true, errors raise a ValueError exception.
  145. """
  146. dict = {}
  147. for name, value in parse_qsl(qs, keep_blank_values, strict_parsing):
  148. if name in dict:
  149. dict[name].append(value)
  150. else:
  151. dict[name] = [value]
  152. return dict
  153. def parse_qsl(qs, keep_blank_values=0, strict_parsing=0):
  154. """Parse a query given as a string argument.
  155. Arguments:
  156. qs: URL-encoded query string to be parsed
  157. keep_blank_values: flag indicating whether blank values in
  158. URL encoded queries should be treated as blank strings. A
  159. true value indicates that blanks should be retained as blank
  160. strings. The default false value indicates that blank values
  161. are to be ignored and treated as if they were not included.
  162. strict_parsing: flag indicating what to do with parsing errors. If
  163. false (the default), errors are silently ignored. If true,
  164. errors raise a ValueError exception.
  165. Returns a list, as G-d intended.
  166. """
  167. pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  168. r = []
  169. for name_value in pairs:
  170. if not name_value and not strict_parsing:
  171. continue
  172. nv = name_value.split('=', 1)
  173. if len(nv) != 2:
  174. if strict_parsing:
  175. raise ValueError("bad query field: %r" % name_value)
  176. # Handle case of a control-name with no equal sign
  177. if keep_blank_values:
  178. nv.append('')
  179. else:
  180. continue
  181. if len(nv[1]) or keep_blank_values:
  182. name = urllib.unquote(nv[0].replace('+', ' '))
  183. value = urllib.unquote(nv[1].replace('+', ' '))
  184. r.append((name, value))
  185. return r
  186. def parse_multipart(fp, pdict):
  187. """Parse multipart input.
  188. Arguments:
  189. fp : input file
  190. pdict: dictionary containing other parameters of conten-type header
  191. Returns a dictionary just like parse_qs(): keys are the field names, each
  192. value is a list of values for that field. This is easy to use but not
  193. much good if you are expecting megabytes to be uploaded -- in that case,
  194. use the FieldStorage class instead which is much more flexible. Note
  195. that content-type is the raw, unparsed contents of the content-type
  196. header.
  197. XXX This does not parse nested multipart parts -- use FieldStorage for
  198. that.
  199. XXX This should really be subsumed by FieldStorage altogether -- no
  200. point in having two implementations of the same parsing algorithm.
  201. """
  202. boundary = ""
  203. if 'boundary' in pdict:
  204. boundary = pdict['boundary']
  205. if not valid_boundary(boundary):
  206. raise ValueError('Invalid boundary in multipart form: %r' % boundary)
  207. nextpart = "--" + boundary
  208. lastpart = "--" + boundary + "--"
  209. partdict = {}
  210. terminator = ""
  211. while terminator != lastpart:
  212. bytes = -1
  213. data = None
  214. if terminator:
  215. # At start of next part. Read headers first.
  216. headers = mimetools.Message(fp)
  217. clength = headers.getheader('content-length')
  218. if clength:
  219. try:
  220. bytes = int(clength)
  221. except ValueError:
  222. pass
  223. if bytes > 0:
  224. if maxlen and bytes > maxlen:
  225. raise ValueError('Maximum content length exceeded')
  226. data = fp.read(bytes)
  227. else:
  228. data = ""
  229. # Read lines until end of part.
  230. lines = []
  231. while 1:
  232. line = fp.readline()
  233. if not line:
  234. terminator = lastpart # End outer loop
  235. break
  236. if line[:2] == "--":
  237. terminator = line.strip()
  238. if terminator in (nextpart, lastpart):
  239. break
  240. lines.append(line)
  241. # Done with part.
  242. if data is None:
  243. continue
  244. if bytes < 0:
  245. if lines:
  246. # Strip final line terminator
  247. line = lines[-1]
  248. if line[-2:] == "\r\n":
  249. line = line[:-2]
  250. elif line[-1:] == "\n":
  251. line = line[:-1]
  252. lines[-1] = line
  253. data = "".join(lines)
  254. line = headers['content-disposition']
  255. if not line:
  256. continue
  257. key, params = parse_header(line)
  258. if key != 'form-data':
  259. continue
  260. if 'name' in params:
  261. name = params['name']
  262. else:
  263. continue
  264. if name in partdict:
  265. partdict[name].append(data)
  266. else:
  267. partdict[name] = [data]
  268. return partdict
  269. def parse_header(line):
  270. """Parse a Content-type like header.
  271. Return the main content-type and a dictionary of options.
  272. """
  273. plist = map(lambda x: x.strip(), line.split(';'))
  274. key = plist.pop(0).lower()
  275. pdict = {}
  276. for p in plist:
  277. i = p.find('=')
  278. if i >= 0:
  279. name = p[:i].strip().lower()
  280. value = p[i+1:].strip()
  281. if len(value) >= 2 and value[0] == value[-1] == '"':
  282. value = value[1:-1]
  283. value = value.replace('\\\\', '\\').replace('\\"', '"')
  284. pdict[name] = value
  285. return key, pdict
  286. # Classes for field storage
  287. # =========================
  288. class MiniFieldStorage:
  289. """Like FieldStorage, for use when no file uploads are possible."""
  290. # Dummy attributes
  291. filename = None
  292. list = None
  293. type = None
  294. file = None
  295. type_options = {}
  296. disposition = None
  297. disposition_options = {}
  298. headers = {}
  299. def __init__(self, name, value):
  300. """Constructor from field name and value."""
  301. self.name = name
  302. self.value = value
  303. # self.file = StringIO(value)
  304. def __repr__(self):
  305. """Return printable representation."""
  306. return "MiniFieldStorage(%r, %r)" % (self.name, self.value)
  307. class FieldStorage:
  308. """Store a sequence of fields, reading multipart/form-data.
  309. This class provides naming, typing, files stored on disk, and
  310. more. At the top level, it is accessible like a dictionary, whose
  311. keys are the field names. (Note: None can occur as a field name.)
  312. The items are either a Python list (if there's multiple values) or
  313. another FieldStorage or MiniFieldStorage object. If it's a single
  314. object, it has the following attributes:
  315. name: the field name, if specified; otherwise None
  316. filename: the filename, if specified; otherwise None; this is the
  317. client side filename, *not* the file name on which it is
  318. stored (that's a temporary file you don't deal with)
  319. value: the value as a *string*; for file uploads, this
  320. transparently reads the file every time you request the value
  321. file: the file(-like) object from which you can read the data;
  322. None if the data is stored a simple string
  323. type: the content-type, or None if not specified
  324. type_options: dictionary of options specified on the content-type
  325. line
  326. disposition: content-disposition, or None if not specified
  327. disposition_options: dictionary of corresponding options
  328. headers: a dictionary(-like) object (sometimes rfc822.Message or a
  329. subclass thereof) containing *all* headers
  330. The class is subclassable, mostly for the purpose of overriding
  331. the make_file() method, which is called internally to come up with
  332. a file open for reading and writing. This makes it possible to
  333. override the default choice of storing all files in a temporary
  334. directory and unlinking them as soon as they have been opened.
  335. """
  336. def __init__(self, fp=None, headers=None, outerboundary="",
  337. environ=os.environ, keep_blank_values=0, strict_parsing=0):
  338. """Constructor. Read multipart/* until last part.
  339. Arguments, all optional:
  340. fp : file pointer; default: sys.stdin
  341. (not used when the request method is GET)
  342. headers : header dictionary-like object; default:
  343. taken from environ as per CGI spec
  344. outerboundary : terminating multipart boundary
  345. (for internal use only)
  346. environ : environment dictionary; default: os.environ
  347. keep_blank_values: flag indicating whether blank values in
  348. URL encoded forms should be treated as blank strings.
  349. A true value indicates that blanks should be retained as
  350. blank strings. The default false value indicates that
  351. blank values are to be ignored and treated as if they were
  352. not included.
  353. strict_parsing: flag indicating what to do with parsing errors.
  354. If false (the default), errors are silently ignored.
  355. If true, errors raise a ValueError exception.
  356. """
  357. method = 'GET'
  358. self.keep_blank_values = keep_blank_values
  359. self.strict_parsing = strict_parsing
  360. if 'REQUEST_METHOD' in environ:
  361. method = environ['REQUEST_METHOD'].upper()
  362. if method == 'GET' or method == 'HEAD':
  363. if 'QUERY_STRING' in environ:
  364. qs = environ['QUERY_STRING']
  365. elif sys.argv[1:]:
  366. qs = sys.argv[1]
  367. else:
  368. qs = ""
  369. fp = StringIO(qs)
  370. if headers is None:
  371. headers = {'content-type':
  372. "application/x-www-form-urlencoded"}
  373. if headers is None:
  374. headers = {}
  375. if method == 'POST':
  376. # Set default content-type for POST to what's traditional
  377. headers['content-type'] = "application/x-www-form-urlencoded"
  378. if 'CONTENT_TYPE' in environ:
  379. headers['content-type'] = environ['CONTENT_TYPE']
  380. if 'CONTENT_LENGTH' in environ:
  381. headers['content-length'] = environ['CONTENT_LENGTH']
  382. self.fp = fp or sys.stdin
  383. self.headers = headers
  384. self.outerboundary = outerboundary
  385. # Process content-disposition header
  386. cdisp, pdict = "", {}
  387. if 'content-disposition' in self.headers:
  388. cdisp, pdict = parse_header(self.headers['content-disposition'])
  389. self.disposition = cdisp
  390. self.disposition_options = pdict
  391. self.name = None
  392. if 'name' in pdict:
  393. self.name = pdict['name']
  394. self.filename = None
  395. if 'filename' in pdict:
  396. self.filename = pdict['filename']
  397. # Process content-type header
  398. #
  399. # Honor any existing content-type header. But if there is no
  400. # content-type header, use some sensible defaults. Assume
  401. # outerboundary is "" at the outer level, but something non-false
  402. # inside a multi-part. The default for an inner part is text/plain,
  403. # but for an outer part it should be urlencoded. This should catch
  404. # bogus clients which erroneously forget to include a content-type
  405. # header.
  406. #
  407. # See below for what we do if there does exist a content-type header,
  408. # but it happens to be something we don't understand.
  409. if 'content-type' in self.headers:
  410. ctype, pdict = parse_header(self.headers['content-type'])
  411. elif self.outerboundary or method != 'POST':
  412. ctype, pdict = "text/plain", {}
  413. else:
  414. ctype, pdict = 'application/x-www-form-urlencoded', {}
  415. self.type = ctype
  416. self.type_options = pdict
  417. self.innerboundary = ""
  418. if 'boundary' in pdict:
  419. self.innerboundary = pdict['boundary']
  420. clen = -1
  421. if 'content-length' in self.headers:
  422. try:
  423. clen = int(self.headers['content-length'])
  424. except ValueError:
  425. pass
  426. if maxlen and clen > maxlen:
  427. raise ValueError('Maximum content length exceeded')
  428. self.length = clen
  429. self.list = self.file = None
  430. self.done = 0
  431. if ctype == 'application/x-www-form-urlencoded':
  432. self.read_urlencoded()
  433. elif ctype[:10] == 'multipart/':
  434. self.read_multi(environ, keep_blank_values, strict_parsing)
  435. else:
  436. self.read_single()
  437. def __repr__(self):
  438. """Return a printable representation."""
  439. return "FieldStorage(%r, %r, %r)" % (
  440. self.name, self.filename, self.value)
  441. def __iter__(self):
  442. return iter(self.keys())
  443. def __getattr__(self, name):
  444. if name != 'value':
  445. raise AttributeError(name)
  446. if self.file:
  447. self.file.seek(0)
  448. value = self.file.read()
  449. self.file.seek(0)
  450. elif self.list is not None:
  451. value = self.list
  452. else:
  453. value = None
  454. return value
  455. def __getitem__(self, key):
  456. """Dictionary style indexing."""
  457. if self.list is None:
  458. raise TypeError("not indexable")
  459. found = []
  460. for item in self.list:
  461. if item.name == key: found.append(item)
  462. if not found:
  463. raise KeyError(key)
  464. if len(found) == 1:
  465. return found[0]
  466. else:
  467. return found
  468. def getvalue(self, key, default=None):
  469. """Dictionary style get() method, including 'value' lookup."""
  470. if key in self:
  471. value = self[key]
  472. if type(value) is type([]):
  473. return map(lambda v: v.value, value)
  474. else:
  475. return value.value
  476. else:
  477. return default
  478. def getfirst(self, key, default=None):
  479. """ Return the first value received."""
  480. if key in self:
  481. value = self[key]
  482. if type(value) is type([]):
  483. return value[0].value
  484. else:
  485. return value.value
  486. else:
  487. return default
  488. def getlist(self, key):
  489. """ Return list of received values."""
  490. if key in self:
  491. value = self[key]
  492. if type(value) is type([]):
  493. return map(lambda v: v.value, value)
  494. else:
  495. return [value.value]
  496. else:
  497. return []
  498. def keys(self):
  499. """Dictionary style keys() method."""
  500. if self.list is None:
  501. raise TypeError("not indexable")
  502. keys = []
  503. for item in self.list:
  504. if item.name not in keys: keys.append(item.name)
  505. return keys
  506. def has_key(self, key):
  507. """Dictionary style has_key() method."""
  508. if self.list is None:
  509. raise TypeError("not indexable")
  510. for item in self.list:
  511. if item.name == key: return True
  512. return False
  513. def __contains__(self, key):
  514. """Dictionary style __contains__ method."""
  515. if self.list is None:
  516. raise TypeError("not indexable")
  517. for item in self.list:
  518. if item.name == key: return True
  519. return False
  520. def __len__(self):
  521. """Dictionary style len(x) support."""
  522. return len(self.keys())
  523. def read_urlencoded(self):
  524. """Internal: read data in query string format."""
  525. qs = self.fp.read(self.length)
  526. self.list = list = []
  527. for key, value in parse_qsl(qs, self.keep_blank_values,
  528. self.strict_parsing):
  529. list.append(MiniFieldStorage(key, value))
  530. self.skip_lines()
  531. FieldStorageClass = None
  532. def read_multi(self, environ, keep_blank_values, strict_parsing):
  533. """Internal: read a part that is itself multipart."""
  534. ib = self.innerboundary
  535. if not valid_boundary(ib):
  536. raise ValueError('Invalid boundary in multipart form: %r' % ib)
  537. self.list = []
  538. klass = self.FieldStorageClass or self.__class__
  539. part = klass(self.fp, {}, ib,
  540. environ, keep_blank_values, strict_parsing)
  541. # Throw first part away
  542. while not part.done:
  543. headers = rfc822.Message(self.fp)
  544. part = klass(self.fp, headers, ib,
  545. environ, keep_blank_values, strict_parsing)
  546. self.list.append(part)
  547. self.skip_lines()
  548. def read_single(self):
  549. """Internal: read an atomic part."""
  550. if self.length >= 0:
  551. self.read_binary()
  552. self.skip_lines()
  553. else:
  554. self.read_lines()
  555. self.file.seek(0)
  556. bufsize = 8*1024 # I/O buffering size for copy to file
  557. def read_binary(self):
  558. """Internal: read binary data."""
  559. self.file = self.make_file('b')
  560. todo = self.length
  561. if todo >= 0:
  562. while todo > 0:
  563. data = self.fp.read(min(todo, self.bufsize))
  564. if not data:
  565. self.done = -1
  566. break
  567. self.file.write(data)
  568. todo = todo - len(data)
  569. def read_lines(self):
  570. """Internal: read lines until EOF or outerboundary."""
  571. self.file = self.__file = StringIO()
  572. if self.outerboundary:
  573. self.read_lines_to_outerboundary()
  574. else:
  575. self.read_lines_to_eof()
  576. def __write(self, line):
  577. if self.__file is not None:
  578. if self.__file.tell() + len(line) > 1000:
  579. self.file = self.make_file('')
  580. self.file.write(self.__file.getvalue())
  581. self.__file = None
  582. self.file.write(line)
  583. def read_lines_to_eof(self):
  584. """Internal: read lines until EOF."""
  585. while 1:
  586. line = self.fp.readline()
  587. if not line:
  588. self.done = -1
  589. break
  590. self.__write(line)
  591. def read_lines_to_outerboundary(self):
  592. """Internal: read lines until outerboundary."""
  593. next = "--" + self.outerboundary
  594. last = next + "--"
  595. delim = ""
  596. while 1:
  597. line = self.fp.readline()
  598. if not line:
  599. self.done = -1
  600. break
  601. if line[:2] == "--":
  602. strippedline = line.strip()
  603. if strippedline == next:
  604. break
  605. if strippedline == last:
  606. self.done = 1
  607. break
  608. odelim = delim
  609. if line[-2:] == "\r\n":
  610. delim = "\r\n"
  611. line = line[:-2]
  612. elif line[-1] == "\n":
  613. delim = "\n"
  614. line = line[:-1]
  615. else:
  616. delim = ""
  617. self.__write(odelim + line)
  618. def skip_lines(self):
  619. """Internal: skip lines until outer boundary if defined."""
  620. if not self.outerboundary or self.done:
  621. return
  622. next = "--" + self.outerboundary
  623. last = next + "--"
  624. while 1:
  625. line = self.fp.readline()
  626. if not line:
  627. self.done = -1
  628. break
  629. if line[:2] == "--":
  630. strippedline = line.strip()
  631. if strippedline == next:
  632. break
  633. if strippedline == last:
  634. self.done = 1
  635. break
  636. def make_file(self, binary=None):
  637. """Overridable: return a readable & writable file.
  638. The file will be used as follows:
  639. - data is written to it
  640. - seek(0)
  641. - data is read from it
  642. The 'binary' argument is unused -- the file is always opened
  643. in binary mode.
  644. This version opens a temporary file for reading and writing,
  645. and immediately deletes (unlinks) it. The trick (on Unix!) is
  646. that the file can still be used, but it can't be opened by
  647. another process, and it will automatically be deleted when it
  648. is closed or when the current process terminates.
  649. If you want a more permanent file, you derive a class which
  650. overrides this method. If you want a visible temporary file
  651. that is nevertheless automatically deleted when the script
  652. terminates, try defining a __del__ method in a derived class
  653. which unlinks the temporary files you have created.
  654. """
  655. import tempfile
  656. return tempfile.TemporaryFile("w+b")
  657. # Backwards Compatibility Classes
  658. # ===============================
  659. class FormContentDict(UserDict.UserDict):
  660. """Form content as dictionary with a list of values per field.
  661. form = FormContentDict()
  662. form[key] -> [value, value, ...]
  663. key in form -> Boolean
  664. form.keys() -> [key, key, ...]
  665. form.values() -> [[val, val, ...], [val, val, ...], ...]
  666. form.items() -> [(key, [val, val, ...]), (key, [val, val, ...]), ...]
  667. form.dict == {key: [val, val, ...], ...}
  668. """
  669. def __init__(self, environ=os.environ):
  670. self.dict = self.data = parse(environ=environ)
  671. self.query_string = environ['QUERY_STRING']
  672. class SvFormContentDict(FormContentDict):
  673. """Form content as dictionary expecting a single value per field.
  674. If you only expect a single value for each field, then form[key]
  675. will return that single value. It will raise an IndexError if
  676. that expectation is not true. If you expect a field to have
  677. possible multiple values, than you can use form.getlist(key) to
  678. get all of the values. values() and items() are a compromise:
  679. they return single strings where there is a single value, and
  680. lists of strings otherwise.
  681. """
  682. def __getitem__(self, key):
  683. if len(self.dict[key]) > 1:
  684. raise IndexError('expecting a single value')
  685. return self.dict[key][0]
  686. def getlist(self, key):
  687. return self.dict[key]
  688. def values(self):
  689. result = []
  690. for value in self.dict.values():
  691. if len(value) == 1:
  692. result.append(value[0])
  693. else: result.append(value)
  694. return result
  695. def items(self):
  696. result = []
  697. for key, value in self.dict.items():
  698. if len(value) == 1:
  699. result.append((key, value[0]))
  700. else: result.append((key, value))
  701. return result
  702. class InterpFormContentDict(SvFormContentDict):
  703. """This class is present for backwards compatibility only."""
  704. def __getitem__(self, key):
  705. v = SvFormContentDict.__getitem__(self, key)
  706. if v[0] in '0123456789+-.':
  707. try: return int(v)
  708. except ValueError:
  709. try: return float(v)
  710. except ValueError: pass
  711. return v.strip()
  712. def values(self):
  713. result = []
  714. for key in self.keys():
  715. try:
  716. result.append(self[key])
  717. except IndexError:
  718. result.append(self.dict[key])
  719. return result
  720. def items(self):
  721. result = []
  722. for key in self.keys():
  723. try:
  724. result.append((key, self[key]))
  725. except IndexError:
  726. result.append((key, self.dict[key]))
  727. return result
  728. class FormContent(FormContentDict):
  729. """This class is present for backwards compatibility only."""
  730. def values(self, key):
  731. if key in self.dict :return self.dict[key]
  732. else: return None
  733. def indexed_value(self, key, location):
  734. if key in self.dict:
  735. if len(self.dict[key]) > location:
  736. return self.dict[key][location]
  737. else: return None
  738. else: return None
  739. def value(self, key):
  740. if key in self.dict: return self.dict[key][0]
  741. else: return None
  742. def length(self, key):
  743. return len(self.dict[key])
  744. def stripped(self, key):
  745. if key in self.dict: return self.dict[key][0].strip()
  746. else: return None
  747. def pars(self):
  748. return self.dict
  749. # Test/debug code
  750. # ===============
  751. def test(environ=os.environ):
  752. """Robust test CGI script, usable as main program.
  753. Write minimal HTTP headers and dump all information provided to
  754. the script in HTML form.
  755. """
  756. print "Content-type: text/html"
  757. print
  758. sys.stderr = sys.stdout
  759. try:
  760. form = FieldStorage() # Replace with other classes to test those
  761. print_directory()
  762. print_arguments()
  763. print_form(form)
  764. print_environ(environ)
  765. print_environ_usage()
  766. def f():
  767. exec "testing print_exception() -- <I>italics?</I>"
  768. def g(f=f):
  769. f()
  770. print "<H3>What follows is a test, not an actual exception:</H3>"
  771. g()
  772. except:
  773. print_exception()
  774. print "<H1>Second try with a small maxlen...</H1>"
  775. global maxlen
  776. maxlen = 50
  777. try:
  778. form = FieldStorage() # Replace with other classes to test those
  779. print_directory()
  780. print_arguments()
  781. print_form(form)
  782. print_environ(environ)
  783. except:
  784. print_exception()
  785. def print_exception(type=None, value=None, tb=None, limit=None):
  786. if type is None:
  787. type, value, tb = sys.exc_info()
  788. import traceback
  789. print
  790. print "<H3>Traceback (most recent call last):</H3>"
  791. list = traceback.format_tb(tb, limit) + \
  792. traceback.format_exception_only(type, value)
  793. print "<PRE>%s<B>%s</B></PRE>" % (
  794. escape("".join(list[:-1])),
  795. escape(list[-1]),
  796. )
  797. del tb
  798. def print_environ(environ=os.environ):
  799. """Dump the shell environment as HTML."""
  800. keys = environ.keys()
  801. keys.sort()
  802. print
  803. print "<H3>Shell Environment:</H3>"
  804. print "<DL>"
  805. for key in keys:
  806. print "<DT>", escape(key), "<DD>", escape(environ[key])
  807. print "</DL>"
  808. print
  809. def print_form(form):
  810. """Dump the contents of a form as HTML."""
  811. keys = form.keys()
  812. keys.sort()
  813. print
  814. print "<H3>Form Contents:</H3>"
  815. if not keys:
  816. print "<P>No form fields."
  817. print "<DL>"
  818. for key in keys:
  819. print "<DT>" + escape(key) + ":",
  820. value = form[key]
  821. print "<i>" + escape(repr(type(value))) + "</i>"
  822. print "<DD>" + escape(repr(value))
  823. print "</DL>"
  824. print
  825. def print_directory():
  826. """Dump the current directory as HTML."""
  827. print
  828. print "<H3>Current Working Directory:</H3>"
  829. try:
  830. pwd = os.getcwd()
  831. except os.error, msg:
  832. print "os.error:", escape(str(msg.Message))
  833. else:
  834. print escape(pwd)
  835. print
  836. def print_arguments():
  837. print
  838. print "<H3>Command Line Arguments:</H3>"
  839. print
  840. print sys.argv
  841. print
  842. def print_environ_usage():
  843. """Dump a list of environment variables used by CGI as HTML."""
  844. print """
  845. <H3>These environment variables could have been set:</H3>
  846. <UL>
  847. <LI>AUTH_TYPE
  848. <LI>CONTENT_LENGTH
  849. <LI>CONTENT_TYPE
  850. <LI>DATE_GMT
  851. <LI>DATE_LOCAL
  852. <LI>DOCUMENT_NAME
  853. <LI>DOCUMENT_ROOT
  854. <LI>DOCUMENT_URI
  855. <LI>GATEWAY_INTERFACE
  856. <LI>LAST_MODIFIED
  857. <LI>PATH
  858. <LI>PATH_INFO
  859. <LI>PATH_TRANSLATED
  860. <LI>QUERY_STRING
  861. <LI>REMOTE_ADDR
  862. <LI>REMOTE_HOST
  863. <LI>REMOTE_IDENT
  864. <LI>REMOTE_USER
  865. <LI>REQUEST_METHOD
  866. <LI>SCRIPT_NAME
  867. <LI>SERVER_NAME
  868. <LI>SERVER_PORT
  869. <LI>SERVER_PROTOCOL
  870. <LI>SERVER_ROOT
  871. <LI>SERVER_SOFTWARE
  872. </UL>
  873. In addition, HTTP headers sent by the server may be passed in the
  874. environment as well. Here are some common variable names:
  875. <UL>
  876. <LI>HTTP_ACCEPT
  877. <LI>HTTP_CONNECTION
  878. <LI>HTTP_HOST
  879. <LI>HTTP_PRAGMA
  880. <LI>HTTP_REFERER
  881. <LI>HTTP_USER_AGENT
  882. </UL>
  883. """
  884. # Utilities
  885. # =========
  886. def escape(s, quote=None):
  887. """Replace special characters '&', '<' and '>' by SGML entities."""
  888. s = s.replace("&", "&amp;") # Must be done first!
  889. s = s.replace("<", "&lt;")
  890. s = s.replace(">", "&gt;")
  891. if quote:
  892. s = s.replace('"', "&quot;")
  893. return s
  894. def valid_boundary(s, _vb_pattern="^[ -~]{0,200}[!-~]$"):
  895. import re
  896. return re.match(_vb_pattern, s)
  897. # Invoke mainline
  898. # ===============
  899. # Call test() when this file is run as a script (not imported as a module)
  900. if __name__ == '__main__':
  901. test()