request.py 19 KB

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