httpheaders.py 43 KB

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