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

/django/http/request.py

https://github.com/insane/django
Python | 518 lines | 502 code | 11 blank | 5 comment | 2 complexity | 7d5a8beda3da2e6c2b4eaa4484ad9e77 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from __future__ import absolute_import, unicode_literals
  2. import copy
  3. import os
  4. import re
  5. import sys
  6. from io import BytesIO
  7. from pprint import pformat
  8. try:
  9. from urllib.parse import parse_qsl, urlencode, quote, urljoin
  10. except ImportError:
  11. from urllib import urlencode, quote
  12. from urlparse import parse_qsl, urljoin
  13. from django.conf import settings
  14. from django.core import signing
  15. from django.core.exceptions import DisallowedHost, ImproperlyConfigured
  16. from django.core.files import uploadhandler
  17. from django.http.multipartparser import MultiPartParser
  18. from django.utils import six
  19. from django.utils.datastructures import MultiValueDict, ImmutableList
  20. from django.utils.encoding import force_bytes, force_text, force_str, iri_to_uri
  21. RAISE_ERROR = object()
  22. absolute_http_url_re = re.compile(r"^https?://", re.I)
  23. host_validation_re = re.compile(r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9:]+\])(:\d+)?$")
  24. class UnreadablePostError(IOError):
  25. pass
  26. class HttpRequest(object):
  27. """A basic HTTP request."""
  28. # The encoding used in GET/POST dicts. None means use default setting.
  29. _encoding = None
  30. _upload_handlers = []
  31. def __init__(self):
  32. # WARNING: The `WSGIRequest` subclass doesn't call `super`.
  33. # Any variable assignment made here should also happen in
  34. # `WSGIRequest.__init__()`.
  35. self.GET, self.POST, self.COOKIES, self.META, self.FILES = {}, {}, {}, {}, {}
  36. self.path = ''
  37. self.path_info = ''
  38. self.method = None
  39. self.resolver_match = None
  40. self._post_parse_error = False
  41. def __repr__(self):
  42. return build_request_repr(self)
  43. def get_host(self):
  44. """Returns the HTTP host using the environment or request headers."""
  45. # We try three options, in order of decreasing preference.
  46. if settings.USE_X_FORWARDED_HOST and (
  47. 'HTTP_X_FORWARDED_HOST' in self.META):
  48. host = self.META['HTTP_X_FORWARDED_HOST']
  49. elif 'HTTP_HOST' in self.META:
  50. host = self.META['HTTP_HOST']
  51. else:
  52. # Reconstruct the host using the algorithm from PEP 333.
  53. host = self.META['SERVER_NAME']
  54. server_port = str(self.META['SERVER_PORT'])
  55. if server_port != ('443' if self.is_secure() else '80'):
  56. host = '%s:%s' % (host, server_port)
  57. allowed_hosts = ['*'] if settings.DEBUG else settings.ALLOWED_HOSTS
  58. domain, port = split_domain_port(host)
  59. if domain and validate_host(domain, allowed_hosts):
  60. return host
  61. else:
  62. msg = "Invalid HTTP_HOST header: %r." % host
  63. if domain:
  64. msg += "You may need to add %r to ALLOWED_HOSTS." % domain
  65. raise DisallowedHost(msg)
  66. def get_full_path(self):
  67. # RFC 3986 requires query string arguments to be in the ASCII range.
  68. # Rather than crash if this doesn't happen, we encode defensively.
  69. return '%s%s' % (self.path, ('?' + iri_to_uri(self.META.get('QUERY_STRING', ''))) if self.META.get('QUERY_STRING', '') else '')
  70. def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
  71. """
  72. Attempts to return a signed cookie. If the signature fails or the
  73. cookie has expired, raises an exception... unless you provide the
  74. default argument in which case that value will be returned instead.
  75. """
  76. try:
  77. cookie_value = self.COOKIES[key]
  78. except KeyError:
  79. if default is not RAISE_ERROR:
  80. return default
  81. else:
  82. raise
  83. try:
  84. value = signing.get_cookie_signer(salt=key + salt).unsign(
  85. cookie_value, max_age=max_age)
  86. except signing.BadSignature:
  87. if default is not RAISE_ERROR:
  88. return default
  89. else:
  90. raise
  91. return value
  92. def build_absolute_uri(self, location=None):
  93. """
  94. Builds an absolute URI from the location and the variables available in
  95. this request. If no location is specified, the absolute URI is built on
  96. ``request.get_full_path()``.
  97. """
  98. if not location:
  99. location = self.get_full_path()
  100. if not absolute_http_url_re.match(location):
  101. current_uri = '%s://%s%s' % ('https' if self.is_secure() else 'http',
  102. self.get_host(), self.path)
  103. location = urljoin(current_uri, location)
  104. return iri_to_uri(location)
  105. def _is_secure(self):
  106. return os.environ.get("HTTPS") == "on"
  107. def is_secure(self):
  108. # First, check the SECURE_PROXY_SSL_HEADER setting.
  109. if settings.SECURE_PROXY_SSL_HEADER:
  110. try:
  111. header, value = settings.SECURE_PROXY_SSL_HEADER
  112. except ValueError:
  113. raise ImproperlyConfigured('The SECURE_PROXY_SSL_HEADER setting must be a tuple containing two values.')
  114. if self.META.get(header, None) == value:
  115. return True
  116. # Failing that, fall back to _is_secure(), which is a hook for
  117. # subclasses to implement.
  118. return self._is_secure()
  119. def is_ajax(self):
  120. return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
  121. @property
  122. def encoding(self):
  123. return self._encoding
  124. @encoding.setter
  125. def encoding(self, val):
  126. """
  127. Sets the encoding used for GET/POST accesses. If the GET or POST
  128. dictionary has already been created, it is removed and recreated on the
  129. next access (so that it is decoded correctly).
  130. """
  131. self._encoding = val
  132. if hasattr(self, '_get'):
  133. del self._get
  134. if hasattr(self, '_post'):
  135. del self._post
  136. def _initialize_handlers(self):
  137. self._upload_handlers = [uploadhandler.load_handler(handler, self)
  138. for handler in settings.FILE_UPLOAD_HANDLERS]
  139. @property
  140. def upload_handlers(self):
  141. if not self._upload_handlers:
  142. # If there are no upload handlers defined, initialize them from settings.
  143. self._initialize_handlers()
  144. return self._upload_handlers
  145. @upload_handlers.setter
  146. def upload_handlers(self, upload_handlers):
  147. if hasattr(self, '_files'):
  148. raise AttributeError("You cannot set the upload handlers after the upload has been processed.")
  149. self._upload_handlers = upload_handlers
  150. def parse_file_upload(self, META, post_data):
  151. """Returns a tuple of (POST QueryDict, FILES MultiValueDict)."""
  152. self.upload_handlers = ImmutableList(
  153. self.upload_handlers,
  154. warning="You cannot alter upload handlers after the upload has been processed."
  155. )
  156. parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
  157. return parser.parse()
  158. @property
  159. def body(self):
  160. if not hasattr(self, '_body'):
  161. if self._read_started:
  162. raise Exception("You cannot access body after reading from request's data stream")
  163. try:
  164. self._body = self.read()
  165. except IOError as e:
  166. six.reraise(UnreadablePostError, UnreadablePostError(*e.args), sys.exc_info()[2])
  167. self._stream = BytesIO(self._body)
  168. return self._body
  169. def _mark_post_parse_error(self):
  170. self._post = QueryDict('')
  171. self._files = MultiValueDict()
  172. self._post_parse_error = True
  173. def _load_post_and_files(self):
  174. """Populate self._post and self._files if the content-type is a form type"""
  175. if self.method != 'POST':
  176. self._post, self._files = QueryDict('', encoding=self._encoding), MultiValueDict()
  177. return
  178. if self._read_started and not hasattr(self, '_body'):
  179. self._mark_post_parse_error()
  180. return
  181. if self.META.get('CONTENT_TYPE', '').startswith('multipart/form-data'):
  182. if hasattr(self, '_body'):
  183. # Use already read data
  184. data = BytesIO(self._body)
  185. else:
  186. data = self
  187. try:
  188. self._post, self._files = self.parse_file_upload(self.META, data)
  189. except:
  190. # An error occured while parsing POST data. Since when
  191. # formatting the error the request handler might access
  192. # self.POST, set self._post and self._file to prevent
  193. # attempts to parse POST data again.
  194. # Mark that an error occured. This allows self.__repr__ to
  195. # be explicit about it instead of simply representing an
  196. # empty POST
  197. self._mark_post_parse_error()
  198. raise
  199. elif self.META.get('CONTENT_TYPE', '').startswith('application/x-www-form-urlencoded'):
  200. self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
  201. else:
  202. self._post, self._files = QueryDict('', encoding=self._encoding), MultiValueDict()
  203. ## File-like and iterator interface.
  204. ##
  205. ## Expects self._stream to be set to an appropriate source of bytes by
  206. ## a corresponding request subclass (e.g. WSGIRequest).
  207. ## Also when request data has already been read by request.POST or
  208. ## request.body, self._stream points to a BytesIO instance
  209. ## containing that data.
  210. def read(self, *args, **kwargs):
  211. self._read_started = True
  212. try:
  213. return self._stream.read(*args, **kwargs)
  214. except IOError as e:
  215. six.reraise(UnreadablePostError, UnreadablePostError(*e.args), sys.exc_info()[2])
  216. def readline(self, *args, **kwargs):
  217. self._read_started = True
  218. try:
  219. return self._stream.readline(*args, **kwargs)
  220. except IOError as e:
  221. six.reraise(UnreadablePostError, UnreadablePostError(*e.args), sys.exc_info()[2])
  222. def xreadlines(self):
  223. while True:
  224. buf = self.readline()
  225. if not buf:
  226. break
  227. yield buf
  228. __iter__ = xreadlines
  229. def readlines(self):
  230. return list(iter(self))
  231. class QueryDict(MultiValueDict):
  232. """
  233. A specialized MultiValueDict that takes a query string when initialized.
  234. This is immutable unless you create a copy of it.
  235. Values retrieved from this class are converted from the given encoding
  236. (DEFAULT_CHARSET by default) to unicode.
  237. """
  238. # These are both reset in __init__, but is specified here at the class
  239. # level so that unpickling will have valid values
  240. _mutable = True
  241. _encoding = None
  242. def __init__(self, query_string, mutable=False, encoding=None):
  243. super(QueryDict, self).__init__()
  244. if not encoding:
  245. encoding = settings.DEFAULT_CHARSET
  246. self.encoding = encoding
  247. if six.PY3:
  248. if isinstance(query_string, bytes):
  249. # query_string contains URL-encoded data, a subset of ASCII.
  250. query_string = query_string.decode()
  251. for key, value in parse_qsl(query_string or '',
  252. keep_blank_values=True,
  253. encoding=encoding):
  254. self.appendlist(key, value)
  255. else:
  256. for key, value in parse_qsl(query_string or '',
  257. keep_blank_values=True):
  258. self.appendlist(force_text(key, encoding, errors='replace'),
  259. force_text(value, encoding, errors='replace'))
  260. self._mutable = mutable
  261. @property
  262. def encoding(self):
  263. if self._encoding is None:
  264. self._encoding = settings.DEFAULT_CHARSET
  265. return self._encoding
  266. @encoding.setter
  267. def encoding(self, value):
  268. self._encoding = value
  269. def _assert_mutable(self):
  270. if not self._mutable:
  271. raise AttributeError("This QueryDict instance is immutable")
  272. def __setitem__(self, key, value):
  273. self._assert_mutable()
  274. key = bytes_to_text(key, self.encoding)
  275. value = bytes_to_text(value, self.encoding)
  276. super(QueryDict, self).__setitem__(key, value)
  277. def __delitem__(self, key):
  278. self._assert_mutable()
  279. super(QueryDict, self).__delitem__(key)
  280. def __copy__(self):
  281. result = self.__class__('', mutable=True, encoding=self.encoding)
  282. for key, value in six.iterlists(self):
  283. result.setlist(key, value)
  284. return result
  285. def __deepcopy__(self, memo):
  286. result = self.__class__('', mutable=True, encoding=self.encoding)
  287. memo[id(self)] = result
  288. for key, value in six.iterlists(self):
  289. result.setlist(copy.deepcopy(key, memo), copy.deepcopy(value, memo))
  290. return result
  291. def setlist(self, key, list_):
  292. self._assert_mutable()
  293. key = bytes_to_text(key, self.encoding)
  294. list_ = [bytes_to_text(elt, self.encoding) for elt in list_]
  295. super(QueryDict, self).setlist(key, list_)
  296. def setlistdefault(self, key, default_list=None):
  297. self._assert_mutable()
  298. return super(QueryDict, self).setlistdefault(key, default_list)
  299. def appendlist(self, key, value):
  300. self._assert_mutable()
  301. key = bytes_to_text(key, self.encoding)
  302. value = bytes_to_text(value, self.encoding)
  303. super(QueryDict, self).appendlist(key, value)
  304. def pop(self, key, *args):
  305. self._assert_mutable()
  306. return super(QueryDict, self).pop(key, *args)
  307. def popitem(self):
  308. self._assert_mutable()
  309. return super(QueryDict, self).popitem()
  310. def clear(self):
  311. self._assert_mutable()
  312. super(QueryDict, self).clear()
  313. def setdefault(self, key, default=None):
  314. self._assert_mutable()
  315. key = bytes_to_text(key, self.encoding)
  316. default = bytes_to_text(default, self.encoding)
  317. return super(QueryDict, self).setdefault(key, default)
  318. def copy(self):
  319. """Returns a mutable copy of this object."""
  320. return self.__deepcopy__({})
  321. def urlencode(self, safe=None):
  322. """
  323. Returns an encoded string of all query string arguments.
  324. :arg safe: Used to specify characters which do not require quoting, for
  325. example::
  326. >>> q = QueryDict('', mutable=True)
  327. >>> q['next'] = '/a&b/'
  328. >>> q.urlencode()
  329. 'next=%2Fa%26b%2F'
  330. >>> q.urlencode(safe='/')
  331. 'next=/a%26b/'
  332. """
  333. output = []
  334. if safe:
  335. safe = force_bytes(safe, self.encoding)
  336. encode = lambda k, v: '%s=%s' % ((quote(k, safe), quote(v, safe)))
  337. else:
  338. encode = lambda k, v: urlencode({k: v})
  339. for k, list_ in self.lists():
  340. k = force_bytes(k, self.encoding)
  341. output.extend([encode(k, force_bytes(v, self.encoding))
  342. for v in list_])
  343. return '&'.join(output)
  344. def build_request_repr(request, path_override=None, GET_override=None,
  345. POST_override=None, COOKIES_override=None,
  346. META_override=None):
  347. """
  348. Builds and returns the request's representation string. The request's
  349. attributes may be overridden by pre-processed values.
  350. """
  351. # Since this is called as part of error handling, we need to be very
  352. # robust against potentially malformed input.
  353. try:
  354. get = (pformat(GET_override)
  355. if GET_override is not None
  356. else pformat(request.GET))
  357. except Exception:
  358. get = '<could not parse>'
  359. if request._post_parse_error:
  360. post = '<could not parse>'
  361. else:
  362. try:
  363. post = (pformat(POST_override)
  364. if POST_override is not None
  365. else pformat(request.POST))
  366. except Exception:
  367. post = '<could not parse>'
  368. try:
  369. cookies = (pformat(COOKIES_override)
  370. if COOKIES_override is not None
  371. else pformat(request.COOKIES))
  372. except Exception:
  373. cookies = '<could not parse>'
  374. try:
  375. meta = (pformat(META_override)
  376. if META_override is not None
  377. else pformat(request.META))
  378. except Exception:
  379. meta = '<could not parse>'
  380. path = path_override if path_override is not None else request.path
  381. return force_str('<%s\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' %
  382. (request.__class__.__name__,
  383. path,
  384. six.text_type(get),
  385. six.text_type(post),
  386. six.text_type(cookies),
  387. six.text_type(meta)))
  388. # It's neither necessary nor appropriate to use
  389. # django.utils.encoding.smart_text for parsing URLs and form inputs. Thus,
  390. # this slightly more restricted function, used by QueryDict.
  391. def bytes_to_text(s, encoding):
  392. """
  393. Converts basestring objects to unicode, using the given encoding. Illegally
  394. encoded input characters are replaced with Unicode "unknown" codepoint
  395. (\ufffd).
  396. Returns any non-basestring objects without change.
  397. """
  398. if isinstance(s, bytes):
  399. return six.text_type(s, encoding, 'replace')
  400. else:
  401. return s
  402. def split_domain_port(host):
  403. """
  404. Return a (domain, port) tuple from a given host.
  405. Returned domain is lower-cased. If the host is invalid, the domain will be
  406. empty.
  407. """
  408. host = host.lower()
  409. if not host_validation_re.match(host):
  410. return '', ''
  411. if host[-1] == ']':
  412. # It's an IPv6 address without a port.
  413. return host, ''
  414. bits = host.rsplit(':', 1)
  415. if len(bits) == 2:
  416. return tuple(bits)
  417. return bits[0], ''
  418. def validate_host(host, allowed_hosts):
  419. """
  420. Validate the given host for this site.
  421. Check that the host looks valid and matches a host or host pattern in the
  422. given list of ``allowed_hosts``. Any pattern beginning with a period
  423. matches a domain and all its subdomains (e.g. ``.example.com`` matches
  424. ``example.com`` and any subdomain), ``*`` matches anything, and anything
  425. else must match exactly.
  426. Note: This function assumes that the given host is lower-cased and has
  427. already had the port, if any, stripped off.
  428. Return ``True`` for a valid host, ``False`` otherwise.
  429. """
  430. for pattern in allowed_hosts:
  431. pattern = pattern.lower()
  432. match = (
  433. pattern == '*' or
  434. pattern.startswith('.') and (
  435. host.endswith(pattern) or host == pattern[1:]
  436. ) or
  437. pattern == host
  438. )
  439. if match:
  440. return True
  441. return False