httpheaders.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  1. # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
  2. # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
  3. # (c) 2005 Ian Bicking, Clark C. Evans and contributors
  4. # This module is part of the Python Paste Project and is released under
  5. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  6. # Some of this code was funded by: http://prometheusresearch.com
  7. """
  8. HTTP Message Header Fields (see RFC 4229)
  9. This contains general support for HTTP/1.1 message headers [1]_ in a
  10. manner that supports WSGI ``environ`` [2]_ and ``response_headers``
  11. [3]_. Specifically, this module defines a ``HTTPHeader`` class whose
  12. instances correspond to field-name items. The actual field-content for
  13. the message-header is stored in the appropriate WSGI collection (either
  14. the ``environ`` for requests, or ``response_headers`` for responses).
  15. Each ``HTTPHeader`` instance is a callable (defining ``__call__``)
  16. that takes one of the following:
  17. - an ``environ`` dictionary, returning the corresponding header
  18. value by according to the WSGI's ``HTTP_`` prefix mechanism, e.g.,
  19. ``USER_AGENT(environ)`` returns ``environ.get('HTTP_USER_AGENT')``
  20. - a ``response_headers`` list, giving a comma-delimited string for
  21. each corresponding ``header_value`` tuple entries (see below).
  22. - a sequence of string ``*args`` that are comma-delimited into
  23. a single string value: ``CONTENT_TYPE("text/html","text/plain")``
  24. returns ``"text/html, text/plain"``
  25. - a set of ``**kwargs`` keyword arguments that are used to create
  26. a header value, in a manner dependent upon the particular header in
  27. question (to make value construction easier and error-free):
  28. ``CONTENT_DISPOSITION(max_age=CONTENT_DISPOSITION.ONEWEEK)``
  29. returns ``"public, max-age=60480"``
  30. Each ``HTTPHeader`` instance also provides several methods to act on
  31. a WSGI collection, for removing and setting header values.
  32. ``delete(collection)``
  33. This method removes all entries of the corresponding header from
  34. the given collection (``environ`` or ``response_headers``), e.g.,
  35. ``USER_AGENT.remove(environ)`` deletes the 'HTTP_USER_AGENT' entry
  36. from the ``environ``.
  37. ``update(collection, *args, **kwargs)``
  38. This method does an in-place replacement of the given header entry,
  39. for example: ``CONTENT_LENGTH(response_headers,len(body))``
  40. The first argument is a valid ``environ`` dictionary or
  41. ``response_headers`` list; remaining arguments are passed on to
  42. ``__call__(*args, **kwargs)`` for value construction.
  43. ``apply(collection, **kwargs)``
  44. This method is similar to update, only that it may affect other
  45. headers. For example, according to recommendations in RFC 2616,
  46. certain Cache-Control configurations should also set the
  47. ``Expires`` header for HTTP/1.0 clients. By default, ``apply()``
  48. is simply ``update()`` but limited to keyword arguments.
  49. This particular approach to managing headers within a WSGI collection
  50. has several advantages:
  51. 1. Typos in the header name are easily detected since they become a
  52. ``NameError`` when executed. The approach of using header strings
  53. directly can be problematic; for example, the following should
  54. return ``None`` : ``environ.get("HTTP_ACCEPT_LANGUAGES")``
  55. 2. For specific headers with validation, using ``__call__`` will
  56. result in an automatic header value check. For example, the
  57. _ContentDisposition header will reject a value having ``maxage``
  58. or ``max_age`` (the appropriate parameter is ``max-age`` ).
  59. 3. When appending/replacing headers, the field-name has the suggested
  60. RFC capitalization (e.g. ``Content-Type`` or ``ETag``) for
  61. user-agents that incorrectly use case-sensitive matches.
  62. 4. Some headers (such as ``Content-Type``) are 0, that is,
  63. only one entry of this type may occur in a given set of
  64. ``response_headers``. This module knows about those cases and
  65. enforces this cardinality constraint.
  66. 5. The exact details of WSGI header management are abstracted so
  67. the programmer need not worry about operational differences
  68. between ``environ`` dictionary or ``response_headers`` list.
  69. 6. Sorting of ``HTTPHeaders`` is done following the RFC suggestion
  70. that general-headers come first, followed by request and response
  71. headers, and finishing with entity-headers.
  72. 7. Special care is given to exceptional cases such as Set-Cookie
  73. which violates the RFC's recommendation about combining header
  74. content into a single entry using comma separation.
  75. A particular difficulty with HTTP message headers is a categorization
  76. of sorts as described in section 4.2:
  77. Multiple message-header fields with the same field-name MAY be
  78. present in a message if and only if the entire field-value for
  79. that header field is defined as a comma-separated list [i.e.,
  80. #(values)]. It MUST be possible to combine the multiple header
  81. fields into one "field-name: field-value" pair, without changing
  82. the semantics of the message, by appending each subsequent
  83. field-value to the first, each separated by a comma.
  84. This creates three fundamentally different kinds of headers:
  85. - Those that do not have a #(values) production, and hence are
  86. singular and may only occur once in a set of response fields;
  87. this case is handled by the ``_SingleValueHeader`` subclass.
  88. - Those which have the #(values) production and follow the
  89. combining rule outlined above; our ``_MultiValueHeader`` case.
  90. - Those which are multi-valued, but cannot be combined (such as the
  91. ``Set-Cookie`` header due to its ``Expires`` parameter); or where
  92. combining them into a single header entry would cause common
  93. user-agents to fail (``WWW-Authenticate``, ``Warning``) since
  94. they fail to handle dates even when properly quoted. This case
  95. is handled by ``_MultiEntryHeader``.
  96. Since this project does not have time to provide rigorous support
  97. and validation for all headers, it does a basic construction of
  98. headers listed in RFC 2616 (plus a few others) so that they can
  99. be obtained by simply doing ``from paste.httpheaders import *``;
  100. the name of the header instance is the "common name" less any
  101. dashes to give CamelCase style names.
  102. .. [1] http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
  103. .. [2] http://www.python.org/peps/pep-0333.html#environ-variables
  104. .. [3] http://www.python.org/peps/pep-0333.html#the-start-response-callable
  105. """
  106. import urllib2
  107. import re
  108. from mimetypes import guess_type
  109. from rfc822 import formatdate, parsedate_tz, mktime_tz
  110. from time import time as now
  111. from httpexceptions import HTTPBadRequest
  112. __all__ = ['get_header', 'list_headers', 'normalize_headers',
  113. 'HTTPHeader', 'EnvironVariable' ]
  114. class EnvironVariable(str):
  115. """
  116. a CGI ``environ`` variable as described by WSGI
  117. This is a helper object so that standard WSGI ``environ`` variables
  118. can be extracted w/o syntax error possibility.
  119. """
  120. def __call__(self, environ):
  121. return environ.get(self,'')
  122. def __repr__(self):
  123. return '<EnvironVariable %s>' % self
  124. def update(self, environ, value):
  125. environ[self] = value
  126. REMOTE_USER = EnvironVariable("REMOTE_USER")
  127. REMOTE_SESSION = EnvironVariable("REMOTE_SESSION")
  128. AUTH_TYPE = EnvironVariable("AUTH_TYPE")
  129. REQUEST_METHOD = EnvironVariable("REQUEST_METHOD")
  130. SCRIPT_NAME = EnvironVariable("SCRIPT_NAME")
  131. PATH_INFO = EnvironVariable("PATH_INFO")
  132. for _name, _obj in globals().items():
  133. if isinstance(_obj, EnvironVariable):
  134. __all__.append(_name)
  135. _headers = {}
  136. class HTTPHeader(object):
  137. """
  138. an HTTP header
  139. HTTPHeader instances represent a particular ``field-name`` of an
  140. HTTP message header. They do not hold a field-value, but instead
  141. provide operations that work on is corresponding values. Storage
  142. of the actual field values is done with WSGI ``environ`` or
  143. ``response_headers`` as appropriate. Typically, a sub-classes that
  144. represent a specific HTTP header, such as _ContentDisposition, are
  145. 0. Once constructed the HTTPHeader instances themselves
  146. are immutable and stateless.
  147. For purposes of documentation a "container" refers to either a
  148. WSGI ``environ`` dictionary, or a ``response_headers`` list.
  149. Member variables (and correspondingly constructor arguments).
  150. ``name``
  151. the ``field-name`` of the header, in "common form"
  152. as presented in RFC 2616; e.g. 'Content-Type'
  153. ``category``
  154. one of 'general', 'request', 'response', or 'entity'
  155. ``version``
  156. version of HTTP (informational) with which the header should
  157. be recognized
  158. ``sort_order``
  159. sorting order to be applied before sorting on
  160. field-name when ordering headers in a response
  161. Special Methods:
  162. ``__call__``
  163. The primary method of the HTTPHeader instance is to make
  164. it a callable, it takes either a collection, a string value,
  165. or keyword arguments and attempts to find/construct a valid
  166. field-value
  167. ``__lt__``
  168. This method is used so that HTTPHeader objects can be
  169. sorted in a manner suggested by RFC 2616.
  170. ``__str__``
  171. The string-value for instances of this class is
  172. the ``field-name``.
  173. Primary Methods:
  174. ``delete()``
  175. remove the all occurrences (if any) of the given
  176. header in the collection provided
  177. ``update()``
  178. replaces (if they exist) all field-value items
  179. in the given collection with the value provided
  180. ``tuples()``
  181. returns a set of (field-name, field-value) tuples
  182. 5 for extending ``response_headers``
  183. Custom Methods (these may not be implemented):
  184. ``apply()``
  185. similar to ``update``, but with two differences; first,
  186. only keyword arguments can be used, and second, specific
  187. sub-classes may introduce side-effects
  188. ``parse()``
  189. converts a string value of the header into a more usable
  190. form, such as time in seconds for a date header, etc.
  191. The collected versions of initialized header instances are immediately
  192. registered and accessible through the ``get_header`` function. Do not
  193. inherit from this directly, use one of ``_SingleValueHeader``,
  194. ``_MultiValueHeader``, or ``_MultiEntryHeader`` as appropriate.
  195. """
  196. #
  197. # Things which can be customized
  198. #
  199. version = '1.1'
  200. category = 'general'
  201. reference = ''
  202. extensions = {}
  203. def compose(self, **kwargs):
  204. """
  205. build header value from keyword arguments
  206. This method is used to build the corresponding header value when
  207. keyword arguments (or no arguments) were provided. The result
  208. should be a sequence of values. For example, the ``Expires``
  209. header takes a keyword argument ``time`` (e.g. time.time()) from
  210. which it returns a the corresponding date.
  211. """
  212. raise NotImplementedError()
  213. def parse(self, *args, **kwargs):
  214. """
  215. convert raw header value into more usable form
  216. This method invokes ``values()`` with the arguments provided,
  217. parses the header results, and then returns a header-specific
  218. data structure corresponding to the header. For example, the
  219. ``Expires`` header returns seconds (as returned by time.time())
  220. """
  221. raise NotImplementedError()
  222. def apply(self, collection, **kwargs):
  223. """
  224. update the collection /w header value (may have side effects)
  225. This method is similar to ``update`` only that usage may result
  226. in other headers being changed as recommended by the corresponding
  227. specification. The return value is defined by the particular
  228. sub-class. For example, the ``_CacheControl.apply()`` sets the
  229. ``Expires`` header in addition to its normal behavior.
  230. """
  231. self.update(collection, **kwargs)
  232. #
  233. # Things which are standardized (mostly)
  234. #
  235. def __new__(cls, name, category=None, reference=None, version=None):
  236. """
  237. construct a new ``HTTPHeader`` instance
  238. We use the ``__new__`` operator to ensure that only one
  239. ``HTTPHeader`` instance exists for each field-name, and to
  240. register the header so that it can be found/enumerated.
  241. """
  242. self = get_header(name, raiseError=False)
  243. if self:
  244. # Allow the registration to happen again, but assert
  245. # that everything is identical.
  246. assert self.name == name, \
  247. "duplicate registration with different capitalization"
  248. assert self.category == category, \
  249. "duplicate registration with different category"
  250. assert cls == self.__class__, \
  251. "duplicate registration with different class"
  252. return self
  253. self = object.__new__(cls)
  254. self.name = name
  255. assert isinstance(self.name, str)
  256. self.category = category or self.category
  257. self.version = version or self.version
  258. self.reference = reference or self.reference
  259. _headers[self.name.lower()] = self
  260. self.sort_order = {'general': 1, 'request': 2,
  261. 'response': 3, 'entity': 4 }[self.category]
  262. self._environ_name = getattr(self, '_environ_name',
  263. 'HTTP_'+ self.name.upper().replace("-","_"))
  264. self._headers_name = getattr(self, '_headers_name',
  265. self.name.lower())
  266. assert self.version in ('1.1', '1.0', '0.9')
  267. return self
  268. def __str__(self):
  269. return self.name
  270. def __lt__(self, other):
  271. """
  272. sort header instances as specified by RFC 2616
  273. Re-define sorting so that general headers are first, followed
  274. by request/response headers, and then entity headers. The
  275. list.sort() methods use the less-than operator for this purpose.
  276. """
  277. if isinstance(other, HTTPHeader):
  278. if self.sort_order != other.sort_order:
  279. return self.sort_order < other.sort_order
  280. return self.name < other.name
  281. return False
  282. def __repr__(self):
  283. ref = self.reference and (' (%s)' % self.reference) or ''
  284. return '<%s %s%s>' % (self.__class__.__name__, self.name, ref)
  285. def values(self, *args, **kwargs):
  286. """
  287. find/construct field-value(s) for the given header
  288. Resolution is done according to the following arguments:
  289. - If only keyword arguments are given, then this is equivalent
  290. to ``compose(**kwargs)``.
  291. - If the first (and only) argument is a dict, it is assumed
  292. to be a WSGI ``environ`` and the result of the corresponding
  293. ``HTTP_`` entry is returned.
  294. - If the first (and only) argument is a list, it is assumed
  295. to be a WSGI ``response_headers`` and the field-value(s)
  296. for this header are collected and returned.
  297. - In all other cases, the arguments are collected, checked that
  298. they are string values, possibly verified by the header's
  299. logic, and returned.
  300. At this time it is an error to provide keyword arguments if args
  301. is present (this might change). It is an error to provide both
  302. a WSGI object and also string arguments. If no arguments are
  303. provided, then ``compose()`` is called to provide a default
  304. value for the header; if there is not default it is an error.
  305. """
  306. if not args:
  307. return self.compose(**kwargs)
  308. if list == type(args[0]):
  309. assert 1 == len(args)
  310. result = []
  311. name = self.name.lower()
  312. for value in [value for header, value in args[0]
  313. if header.lower() == name]:
  314. result.append(value)
  315. return result
  316. if dict == type(args[0]):
  317. assert 1 == len(args) and 'wsgi.version' in args[0]
  318. value = args[0].get(self._environ_name)
  319. if not value:
  320. return ()
  321. return (value,)
  322. for item in args:
  323. assert not type(item) in (dict, list)
  324. return args
  325. def __call__(self, *args, **kwargs):
  326. """
  327. converts ``values()`` into a string value
  328. This method converts the results of ``values()`` into a string
  329. value for common usage. By default, it is asserted that only
  330. one value exists; if you need to access all values then either
  331. call ``values()`` directly, or inherit ``_MultiValueHeader``
  332. which overrides this method to return a comma separated list of
  333. values as described by section 4.2 of RFC 2616.
  334. """
  335. values = self.values(*args, **kwargs)
  336. assert isinstance(values, (tuple, list))
  337. if not values:
  338. return ''
  339. assert len(values) == 1, "more than one value: %s" % repr(values)
  340. return str(values[0]).strip()
  341. def delete(self, collection):
  342. """
  343. removes all occurances of the header from the collection provided
  344. """
  345. if type(collection) == dict:
  346. if self._environ_name in collection:
  347. del collection[self._environ_name]
  348. return self
  349. assert list == type(collection)
  350. i = 0
  351. while i < len(collection):
  352. if collection[i][0].lower() == self._headers_name:
  353. del collection[i]
  354. continue
  355. i += 1
  356. def update(self, collection, *args, **kwargs):
  357. """
  358. updates the collection with the provided header value
  359. This method replaces (in-place when possible) all occurrences of
  360. the given header with the provided value. If no value is
  361. provided, this is the same as ``remove`` (note that this case
  362. can only occur if the target is a collection w/o a corresponding
  363. header value). The return value is the new header value (which
  364. could be a list for ``_MultiEntryHeader`` instances).
  365. """
  366. value = self.__call__(*args, **kwargs)
  367. if not value:
  368. self.remove(collection)
  369. return
  370. if type(collection) == dict:
  371. collection[self._environ_name] = value
  372. return
  373. assert list == type(collection)
  374. i = 0
  375. found = False
  376. while i < len(collection):
  377. if collection[i][0].lower() == self._headers_name:
  378. if found:
  379. del collection[i]
  380. continue
  381. collection[i] = (self.name, value)
  382. found = True
  383. i += 1
  384. if not found:
  385. collection.append((self.name, value))
  386. def tuples(self, *args, **kwargs):
  387. value = self.__call__(*args, **kwargs)
  388. if not value:
  389. return ()
  390. return [(self.name, value)]
  391. class _SingleValueHeader(HTTPHeader):
  392. """
  393. a ``HTTPHeader`` with exactly a single value
  394. This is the default behavior of ``HTTPHeader`` where returning a
  395. the string-value of headers via ``__call__`` assumes that only
  396. a single value exists.
  397. """
  398. pass
  399. class _MultiValueHeader(HTTPHeader):
  400. """
  401. a ``HTTPHeader`` with one or more values
  402. The field-value for these header instances is is allowed to be more
  403. than one value; whereby the ``__call__`` method returns a comma
  404. separated list as described by section 4.2 of RFC 2616.
  405. """
  406. def __call__(self, *args, **kwargs):
  407. results = self.values(*args, **kwargs)
  408. if not results:
  409. return ''
  410. return ", ".join([str(v).strip() for v in results])
  411. def parse(self, *args, **kwargs):
  412. value = self.__call__(*args, **kwargs)
  413. values = value.split(',')
  414. return [
  415. v.strip() for v in values
  416. if v.strip()]
  417. class _MultiEntryHeader(HTTPHeader):
  418. """
  419. a multi-value ``HTTPHeader`` where items cannot be combined with a comma
  420. This header is multi-valued, but the values should not be combined
  421. with a comma since the header is not in compliance with RFC 2616
  422. (Set-Cookie due to Expires parameter) or which common user-agents do
  423. not behave well when the header values are combined.
  424. """
  425. def update(self, collection, *args, **kwargs):
  426. assert list == type(collection), "``environ`` may not be updated"
  427. self.delete(collection)
  428. collection.extend(self.tuples(*args, **kwargs))
  429. def tuples(self, *args, **kwargs):
  430. values = self.values(*args, **kwargs)
  431. if not values:
  432. return ()
  433. return [(self.name, value.strip()) for value in values]
  434. def get_header(name, raiseError=True):
  435. """
  436. find the given ``HTTPHeader`` instance
  437. This function finds the corresponding ``HTTPHeader`` for the
  438. ``name`` provided. So that python-style names can be used,
  439. underscores are converted to dashes before the lookup.
  440. """
  441. retval = _headers.get(str(name).strip().lower().replace("_","-"))
  442. if not retval and raiseError:
  443. raise AssertionError("'%s' is an unknown header" % name)
  444. return retval
  445. def list_headers(general=None, request=None, response=None, entity=None):
  446. " list all headers for a given category "
  447. if not (general or request or response or entity):
  448. general = request = response = entity = True
  449. search = []
  450. for (bool, strval) in ((general, 'general'), (request, 'request'),
  451. (response, 'response'), (entity, 'entity')):
  452. if bool:
  453. search.append(strval)
  454. return [head for head in _headers.values() if head.category in search]
  455. def normalize_headers(response_headers, strict=True):
  456. """
  457. sort headers as suggested by RFC 2616
  458. This alters the underlying response_headers to use the common
  459. name for each header; as well as sorting them with general
  460. headers first, followed by request/response headers, then
  461. entity headers, and unknown headers last.
  462. """
  463. category = {}
  464. for idx in range(len(response_headers)):
  465. (key, val) = response_headers[idx]
  466. head = get_header(key, strict)
  467. if not head:
  468. newhead = '-'.join([x.capitalize() for x in
  469. key.replace("_","-").split("-")])
  470. response_headers[idx] = (newhead, val)
  471. category[newhead] = 4
  472. continue
  473. response_headers[idx] = (str(head), val)
  474. category[str(head)] = head.sort_order
  475. def compare(a, b):
  476. ac = category[a[0]]
  477. bc = category[b[0]]
  478. if ac == bc:
  479. return cmp(a[0], b[0])
  480. return cmp(ac, bc)
  481. response_headers.sort(compare)
  482. class _DateHeader(_SingleValueHeader):
  483. """
  484. handle date-based headers
  485. This extends the ``_SingleValueHeader`` object with specific
  486. treatment of time values:
  487. - It overrides ``compose`` to provide a sole keyword argument
  488. ``time`` which is an offset in seconds from the current time.
  489. - A ``time`` method is provided which parses the given value
  490. and returns the current time value.
  491. """
  492. def compose(self, time=None, delta=None):
  493. time = time or now()
  494. if delta:
  495. assert type(delta) == int
  496. time += delta
  497. return (formatdate(time),)
  498. def parse(self, *args, **kwargs):
  499. """ return the time value (in seconds since 1970) """
  500. value = self.__call__(*args, **kwargs)
  501. if value:
  502. try:
  503. return mktime_tz(parsedate_tz(value))
  504. except TypeError:
  505. raise HTTPBadRequest((
  506. "Received an ill-formed timestamp for %s: %s\r\n") %
  507. (self.name, value))
  508. #
  509. # Following are specific HTTP headers. Since these classes are mostly
  510. # singletons, there is no point in keeping the class around once it has
  511. # been instantiated, so we use the same name.
  512. #
  513. class _CacheControl(_MultiValueHeader):
  514. """
  515. Cache-Control, RFC 2616 14.9 (use ``CACHE_CONTROL``)
  516. This header can be constructed (using keyword arguments), by
  517. first specifying one of the following mechanisms:
  518. ``public``
  519. if True, this argument specifies that the
  520. response, as a whole, may be cashed.
  521. ``private``
  522. if True, this argument specifies that the response, as a
  523. whole, may be cashed; this implementation does not support
  524. the enumeration of private fields
  525. ``no_cache``
  526. if True, this argument specifies that the response, as a
  527. whole, may not be cashed; this implementation does not
  528. support the enumeration of private fields
  529. In general, only one of the above three may be True, the other 2
  530. must then be False or None. If all three are None, then the cache
  531. is assumed to be ``public``. Following one of these mechanism
  532. specifiers are various modifiers:
  533. ``no_store``
  534. indicates if content may be stored on disk;
  535. otherwise cache is limited to memory (note:
  536. users can still save the data, this applies
  537. to intermediate caches)
  538. ``max_age``
  539. the maximum duration (in seconds) for which
  540. the content should be cached; if ``no-cache``
  541. is specified, this defaults to 0 seconds
  542. ``s_maxage``
  543. the maximum duration (in seconds) for which the
  544. content should be allowed in a shared cache.
  545. ``no_transform``
  546. specifies that an intermediate cache should
  547. not convert the content from one type to
  548. another (e.g. transform a BMP to a PNG).
  549. ``extensions``
  550. gives additional cache-control extensions,
  551. such as items like, community="UCI" (14.9.6)
  552. The usage of ``apply()`` on this header has side-effects. As
  553. recommended by RFC 2616, if ``max_age`` is provided, then then the
  554. ``Expires`` header is also calculated for HTTP/1.0 clients and
  555. proxies (this is done at the time ``apply()`` is called). For
  556. ``no-cache`` and for ``private`` cases, we either do not want the
  557. response cached or do not want any response accidently returned to
  558. other users; so to prevent this case, we set the ``Expires`` header
  559. to the time of the request, signifying to HTTP/1.0 transports that
  560. the content isn't to be cached. If you are using SSL, your
  561. communication is already "private", so to work with HTTP/1.0
  562. browsers over SSL, consider specifying your cache as ``public`` as
  563. the distinction between public and private is moot.
  564. """
  565. # common values for max-age; "good enough" approximates
  566. ONE_HOUR = 60*60
  567. ONE_DAY = ONE_HOUR * 24
  568. ONE_WEEK = ONE_DAY * 7
  569. ONE_MONTH = ONE_DAY * 30
  570. ONE_YEAR = ONE_WEEK * 52
  571. def _compose(self, public=None, private=None, no_cache=None,
  572. no_store=False, max_age=None, s_maxage=None,
  573. no_transform=False, **extensions):
  574. assert isinstance(max_age, (type(None), int))
  575. assert isinstance(s_maxage, (type(None), int))
  576. expires = 0
  577. result = []
  578. if private is True:
  579. assert not public and not no_cache and not s_maxage
  580. result.append('private')
  581. elif no_cache is True:
  582. assert not public and not private and not max_age
  583. result.append('no-cache')
  584. else:
  585. assert public is None or public is True
  586. assert not private and not no_cache
  587. expires = max_age
  588. result.append('public')
  589. if no_store:
  590. result.append('no-store')
  591. if no_transform:
  592. result.append('no-transform')
  593. if max_age is not None:
  594. result.append('max-age=%d' % max_age)
  595. if s_maxage is not None:
  596. result.append('s-maxage=%d' % s_maxage)
  597. for (k, v) in extensions.items():
  598. if k not in self.extensions:
  599. raise AssertionError("unexpected extension used: '%s'" % k)
  600. result.append('%s="%s"' % (k.replace("_", "-"), v))
  601. return (result, expires)
  602. def compose(self, **kwargs):
  603. (result, expires) = self._compose(**kwargs)
  604. return result
  605. def apply(self, collection, **kwargs):
  606. """ returns the offset expiration in seconds """
  607. (result, expires) = self._compose(**kwargs)
  608. if expires is not None:
  609. EXPIRES.update(collection, delta=expires)
  610. self.update(collection, *result)
  611. return expires
  612. _CacheControl('Cache-Control', 'general', 'RFC 2616, 14.9')
  613. class _ContentType(_SingleValueHeader):
  614. """
  615. Content-Type, RFC 2616 section 14.17
  616. Unlike other headers, use the CGI variable instead.
  617. """
  618. version = '1.0'
  619. _environ_name = 'CONTENT_TYPE'
  620. # common mimetype constants
  621. UNKNOWN = 'application/octet-stream'
  622. TEXT_PLAIN = 'text/plain'
  623. TEXT_HTML = 'text/html'
  624. TEXT_XML = 'text/xml'
  625. def compose(self, major=None, minor=None, charset=None):
  626. if not major:
  627. if minor in ('plain', 'html', 'xml'):
  628. major = 'text'
  629. else:
  630. assert not minor and not charset
  631. return (self.UNKNOWN,)
  632. if not minor:
  633. minor = "*"
  634. result = "%s/%s" % (major, minor)
  635. if charset:
  636. result += "; charset=%s" % charset
  637. return (result,)
  638. _ContentType('Content-Type', 'entity', 'RFC 2616, 14.17')
  639. class _ContentLength(_SingleValueHeader):
  640. """
  641. Content-Length, RFC 2616 section 14.13
  642. Unlike other headers, use the CGI variable instead.
  643. """
  644. version = "1.0"
  645. _environ_name = 'CONTENT_LENGTH'
  646. _ContentLength('Content-Length', 'entity', 'RFC 2616, 14.13')
  647. class _ContentDisposition(_SingleValueHeader):
  648. """
  649. Content-Disposition, RFC 2183 (use ``CONTENT_DISPOSITION``)
  650. This header can be constructed (using keyword arguments),
  651. by first specifying one of the following mechanisms:
  652. ``attachment``
  653. if True, this specifies that the content should not be
  654. shown in the browser and should be handled externally,
  655. even if the browser could render the content
  656. ``inline``
  657. exclusive with attachment; indicates that the content
  658. should be rendered in the browser if possible, but
  659. otherwise it should be handled externally
  660. Only one of the above 2 may be True. If both are None, then
  661. the disposition is assumed to be an ``attachment``. These are
  662. distinct fields since support for field enumeration may be
  663. added in the future.
  664. ``filename``
  665. the filename parameter, if any, to be reported; if
  666. this is None, then the current object's filename
  667. attribute is used
  668. The usage of ``apply()`` on this header has side-effects. If
  669. filename is provided, and Content-Type is not set or is
  670. 'application/octet-stream', then the mimetypes.guess is used to
  671. upgrade the Content-Type setting.
  672. """
  673. def _compose(self, attachment=None, inline=None, filename=None):
  674. result = []
  675. if inline is True:
  676. assert not attachment
  677. result.append('inline')
  678. else:
  679. assert not inline
  680. result.append('attachment')
  681. if filename:
  682. assert '"' not in filename
  683. filename = filename.split("/")[-1]
  684. filename = filename.split("\\")[-1]
  685. result.append('filename="%s"' % filename)
  686. return (("; ".join(result),), filename)
  687. def compose(self, **kwargs):
  688. (result, mimetype) = self._compose(**kwargs)
  689. return result
  690. def apply(self, collection, **kwargs):
  691. """ return the new Content-Type side-effect value """
  692. (result, filename) = self._compose(**kwargs)
  693. mimetype = CONTENT_TYPE(collection)
  694. if filename and (not mimetype or CONTENT_TYPE.UNKNOWN == mimetype):
  695. mimetype, _ = guess_type(filename)
  696. if mimetype and CONTENT_TYPE.UNKNOWN != mimetype:
  697. CONTENT_TYPE.update(collection, mimetype)
  698. self.update(collection, *result)
  699. return mimetype
  700. _ContentDisposition('Content-Disposition', 'entity', 'RFC 2183')
  701. class _IfModifiedSince(_DateHeader):
  702. """
  703. If-Modified-Since, RFC 2616 section 14.25
  704. """
  705. version = '1.0'
  706. def __call__(self, *args, **kwargs):
  707. """
  708. Split the value on ';' incase the header includes extra attributes. E.g.
  709. IE 6 is known to send:
  710. If-Modified-Since: Sun, 25 Jun 2006 20:36:35 GMT; length=1506
  711. """
  712. return _DateHeader.__call__(self, *args, **kwargs).split(';', 1)[0]
  713. def parse(self, *args, **kwargs):
  714. value = _DateHeader.parse(self, *args, **kwargs)
  715. if value and value > now():
  716. raise HTTPBadRequest((
  717. "Please check your system clock.\r\n"
  718. "According to this server, the time provided in the\r\n"
  719. "%s header is in the future.\r\n") % self.name)
  720. return value
  721. _IfModifiedSince('If-Modified-Since', 'request', 'RFC 2616, 14.25')
  722. class _Range(_MultiValueHeader):
  723. """
  724. Range, RFC 2616 14.35 (use ``RANGE``)
  725. According to section 14.16, the response to this message should be a
  726. 206 Partial Content and that if multiple non-overlapping byte ranges
  727. are requested (it is an error to request multiple overlapping
  728. ranges) the result should be sent as multipart/byteranges mimetype.
  729. The server should respond with '416 Requested Range Not Satisfiable'
  730. if the requested ranges are out-of-bounds. The specification also
  731. indicates that a syntax error in the Range request should result in
  732. the header being ignored rather than a '400 Bad Request'.
  733. """
  734. def parse(self, *args, **kwargs):
  735. """
  736. Returns a tuple (units, list), where list is a sequence of
  737. (begin, end) tuples; and end is None if it was not provided.
  738. """
  739. value = self.__call__(*args, **kwargs)
  740. if not value:
  741. return None
  742. ranges = []
  743. last_end = -1
  744. try:
  745. (units, range) = value.split("=", 1)
  746. units = units.strip().lower()
  747. for item in range.split(","):
  748. (begin, end) = item.split("-")
  749. if not begin.strip():
  750. begin = 0
  751. else:
  752. begin = int(begin)
  753. if begin <= last_end:
  754. raise ValueError()
  755. if not end.strip():
  756. end = None
  757. else:
  758. end = int(end)
  759. last_end = end
  760. ranges.append((begin, end))
  761. except ValueError:
  762. # In this case where the Range header is malformed,
  763. # section 14.16 says to treat the request as if the
  764. # Range header was not present. How do I log this?
  765. return None
  766. return (units, ranges)
  767. _Range('Range', 'request', 'RFC 2616, 14.35')
  768. class _AcceptLanguage(_MultiValueHeader):
  769. """
  770. Accept-Language, RFC 2616 section 14.4
  771. """
  772. def parse(self, *args, **kwargs):
  773. """
  774. Return a list of language tags sorted by their "q" values. For example,
  775. "en-us,en;q=0.5" should return ``["en-us", "en"]``. If there is no
  776. ``Accept-Language`` header present, default to ``[]``.
  777. """
  778. header = self.__call__(*args, **kwargs)
  779. if header is None:
  780. return []
  781. langs = [v for v in header.split(",") if v]
  782. qs = []
  783. for lang in langs:
  784. pieces = lang.split(";")
  785. lang, params = pieces[0].strip().lower(), pieces[1:]
  786. q = 1
  787. for param in params:
  788. if '=' not in param:
  789. # Malformed request; probably a bot, we'll ignore
  790. continue
  791. lvalue, rvalue = param.split("=")
  792. lvalue = lvalue.strip().lower()
  793. rvalue = rvalue.strip()
  794. if lvalue == "q":
  795. q = float(rvalue)
  796. qs.append((lang, q))
  797. qs.sort(lambda a, b: -cmp(a[1], b[1]))
  798. return [lang for (lang, q) in qs]
  799. _AcceptLanguage('Accept-Language', 'request', 'RFC 2616, 14.4')
  800. class _AcceptRanges(_MultiValueHeader):
  801. """
  802. Accept-Ranges, RFC 2616 section 14.5
  803. """
  804. def compose(self, none=None, bytes=None):
  805. if bytes:
  806. return ('bytes',)
  807. return ('none',)
  808. _AcceptRanges('Accept-Ranges', 'response', 'RFC 2616, 14.5')
  809. class _ContentRange(_SingleValueHeader):
  810. """
  811. Content-Range, RFC 2616 section 14.6
  812. """
  813. def compose(self, first_byte=None, last_byte=None, total_length=None):
  814. retval = "bytes %d-%d/%d" % (first_byte, last_byte, total_length)
  815. assert last_byte == -1 or first_byte <= last_byte
  816. assert last_byte < total_length
  817. return (retval,)
  818. _ContentRange('Content-Range', 'entity', 'RFC 2616, 14.6')
  819. class _Authorization(_SingleValueHeader):
  820. """
  821. Authorization, RFC 2617 (RFC 2616, 14.8)
  822. """
  823. def compose(self, digest=None, basic=None, username=None, password=None,
  824. challenge=None, path=None, method=None):
  825. assert username and password
  826. if basic or not challenge:
  827. assert not digest
  828. userpass = "%s:%s" % (username.strip(), password.strip())
  829. return "Basic %s" % userpass.encode('base64').strip()
  830. assert challenge and not basic
  831. path = path or "/"
  832. (_, realm) = challenge.split('realm="')
  833. (realm, _) = realm.split('"', 1)
  834. auth = urllib2.AbstractDigestAuthHandler()
  835. auth.add_password(realm, path, username, password)
  836. (token, challenge) = challenge.split(' ', 1)
  837. chal = urllib2.parse_keqv_list(urllib2.parse_http_list(challenge))
  838. class FakeRequest(object):
  839. def get_full_url(self):
  840. return path
  841. def has_data(self):
  842. return False
  843. def get_method(self):
  844. return method or "GET"
  845. get_selector = get_full_url
  846. retval = "Digest %s" % auth.get_authorization(FakeRequest(), chal)
  847. return (retval,)
  848. _Authorization('Authorization', 'request', 'RFC 2617')
  849. #
  850. # For now, construct a minimalistic version of the field-names; at a
  851. # later date more complicated headers may sprout content constructors.
  852. # The items commented out have concrete variants.
  853. #
  854. for (name, category, version, style, comment) in \
  855. (("Accept" ,'request' ,'1.1','multi-value','RFC 2616, 14.1' )
  856. ,("Accept-Charset" ,'request' ,'1.1','multi-value','RFC 2616, 14.2' )
  857. ,("Accept-Encoding" ,'request' ,'1.1','multi-value','RFC 2616, 14.3' )
  858. #,("Accept-Language" ,'request' ,'1.1','multi-value','RFC 2616, 14.4' )
  859. #,("Accept-Ranges" ,'response','1.1','multi-value','RFC 2616, 14.5' )
  860. ,("Age" ,'response','1.1','singular' ,'RFC 2616, 14.6' )
  861. ,("Allow" ,'entity' ,'1.0','multi-value','RFC 2616, 14.7' )
  862. #,("Authorization" ,'request' ,'1.0','singular' ,'RFC 2616, 14.8' )
  863. #,("Cache-Control" ,'general' ,'1.1','multi-value','RFC 2616, 14.9' )
  864. ,("Cookie" ,'request' ,'1.0','multi-value','RFC 2109/Netscape')
  865. ,("Connection" ,'general' ,'1.1','multi-value','RFC 2616, 14.10')
  866. ,("Content-Encoding" ,'entity' ,'1.0','multi-value','RFC 2616, 14.11')
  867. #,("Content-Disposition",'entity' ,'1.1','multi-value','RFC 2616, 15.5' )
  868. ,("Content-Language" ,'entity' ,'1.1','multi-value','RFC 2616, 14.12')
  869. #,("Content-Length" ,'entity' ,'1.0','singular' ,'RFC 2616, 14.13')
  870. ,("Content-Location" ,'entity' ,'1.1','singular' ,'RFC 2616, 14.14')
  871. ,("Content-MD5" ,'entity' ,'1.1','singular' ,'RFC 2616, 14.15')
  872. #,("Content-Range" ,'entity' ,'1.1','singular' ,'RFC 2616, 14.16')
  873. #,("Content-Type" ,'entity' ,'1.0','singular' ,'RFC 2616, 14.17')
  874. ,("Date" ,'general' ,'1.0','date-header','RFC 2616, 14.18')
  875. ,("ETag" ,'response','1.1','singular' ,'RFC 2616, 14.19')
  876. ,("Expect" ,'request' ,'1.1','multi-value','RFC 2616, 14.20')
  877. ,("Expires" ,'entity' ,'1.0','date-header','RFC 2616, 14.21')
  878. ,("From" ,'request' ,'1.0','singular' ,'RFC 2616, 14.22')
  879. ,("Host" ,'request' ,'1.1','singular' ,'RFC 2616, 14.23')
  880. ,("If-Match" ,'request' ,'1.1','multi-value','RFC 2616, 14.24')
  881. #,("If-Modified-Since" ,'request' ,'1.0','date-header','RFC 2616, 14.25')
  882. ,("If-None-Match" ,'request' ,'1.1','multi-value','RFC 2616, 14.26')
  883. ,("If-Range" ,'request' ,'1.1','singular' ,'RFC 2616, 14.27')
  884. ,("If-Unmodified-Since",'request' ,'1.1','date-header' ,'RFC 2616, 14.28')
  885. ,("Last-Modified" ,'entity' ,'1.0','date-header','RFC 2616, 14.29')
  886. ,("Location" ,'response','1.0','singular' ,'RFC 2616, 14.30')
  887. ,("Max-Forwards" ,'request' ,'1.1','singular' ,'RFC 2616, 14.31')
  888. ,("Pragma" ,'general' ,'1.0','multi-value','RFC 2616, 14.32')
  889. ,("Proxy-Authenticate" ,'response','1.1','multi-value','RFC 2616, 14.33')
  890. ,("Proxy-Authorization",'request' ,'1.1','singular' ,'RFC 2616, 14.34')
  891. #,("Range" ,'request' ,'1.1','multi-value','RFC 2616, 14.35')
  892. ,("Referer" ,'request' ,'1.0','singular' ,'RFC 2616, 14.36')
  893. ,("Retry-After" ,'response','1.1','singular' ,'RFC 2616, 14.37')
  894. ,("Server" ,'response','1.0','singular' ,'RFC 2616, 14.38')
  895. ,("Set-Cookie" ,'response','1.0','multi-entry','RFC 2109/Netscape')
  896. ,("TE" ,'request' ,'1.1','multi-value','RFC 2616, 14.39')
  897. ,("Trailer" ,'general' ,'1.1','multi-value','RFC 2616, 14.40')
  898. ,("Transfer-Encoding" ,'general' ,'1.1','multi-value','RFC 2616, 14.41')
  899. ,("Upgrade" ,'general' ,'1.1','multi-value','RFC 2616, 14.42')
  900. ,("User-Agent" ,'request' ,'1.0','singular' ,'RFC 2616, 14.43')
  901. ,("Vary" ,'response','1.1','multi-value','RFC 2616, 14.44')
  902. ,("Via" ,'general' ,'1.1','multi-value','RFC 2616, 14.45')
  903. ,("Warning" ,'general' ,'1.1','multi-entry','RFC 2616, 14.46')
  904. ,("WWW-Authenticate" ,'response','1.0','multi-entry','RFC 2616, 14.47')):
  905. klass = {'multi-value': _MultiValueHeader,
  906. 'multi-entry': _MultiEntryHeader,
  907. 'date-header': _DateHeader,
  908. 'singular' : _SingleValueHeader}[style]
  909. klass(name, category, comment, version).__doc__ = comment
  910. del klass
  911. for head in _headers.values():
  912. headname = head.name.replace("-","_").upper()
  913. locals()[headname] = head
  914. __all__.append(headname)
  915. __pudge_all__ = __all__[:]
  916. for _name, _obj in globals().items():
  917. if isinstance(_obj, type) and issubclass(_obj, HTTPHeader):
  918. __pudge_all__.append(_name)