request.py 20 KB

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