cgi.py 35 KB

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