You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

request.py 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. import copy
  2. import re
  3. import warnings
  4. from io import BytesIO
  5. from itertools import chain
  6. from urllib.parse import quote, urlencode, urljoin, urlsplit
  7. from django.conf import settings
  8. from django.core import signing
  9. from django.core.exceptions import (
  10. DisallowedHost, ImproperlyConfigured, RequestDataTooBig,
  11. )
  12. from django.core.files import uploadhandler
  13. from django.http.multipartparser import MultiPartParser, MultiPartParserError
  14. from django.utils.datastructures import (
  15. CaseInsensitiveMapping, ImmutableList, MultiValueDict,
  16. )
  17. from django.utils.deprecation import RemovedInDjango30Warning
  18. from django.utils.encoding import escape_uri_path, iri_to_uri
  19. from django.utils.functional import cached_property
  20. from django.utils.http import is_same_domain, limited_parse_qsl
  21. RAISE_ERROR = object()
  22. host_validation_re = re.compile(r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9\.:]+\])(:\d+)?$")
  23. class UnreadablePostError(IOError):
  24. pass
  25. class RawPostDataException(Exception):
  26. """
  27. You cannot access raw_post_data from a request that has
  28. multipart/* POST data if it has been accessed via POST,
  29. FILES, etc..
  30. """
  31. pass
  32. class HttpRequest:
  33. """A basic HTTP request."""
  34. # The encoding used in GET/POST dicts. None means use default setting.
  35. _encoding = None
  36. _upload_handlers = []
  37. def __init__(self):
  38. # WARNING: The `WSGIRequest` subclass doesn't call `super`.
  39. # Any variable assignment made here should also happen in
  40. # `WSGIRequest.__init__()`.
  41. self.GET = QueryDict(mutable=True)
  42. self.POST = QueryDict(mutable=True)
  43. self.COOKIES = {}
  44. self.META = {}
  45. self.FILES = MultiValueDict()
  46. self.path = ''
  47. self.path_info = ''
  48. self.method = None
  49. self.resolver_match = None
  50. self.content_type = None
  51. self.content_params = None
  52. def __repr__(self):
  53. if self.method is None or not self.get_full_path():
  54. return '<%s>' % self.__class__.__name__
  55. return '<%s: %s %r>' % (self.__class__.__name__, self.method, self.get_full_path())
  56. @cached_property
  57. def headers(self):
  58. return HttpHeaders(self.META)
  59. def _get_raw_host(self):
  60. """
  61. Return the HTTP host using the environment or request headers. Skip
  62. allowed hosts protection, so may return an insecure host.
  63. """
  64. # We try three options, in order of decreasing preference.
  65. if settings.USE_X_FORWARDED_HOST and (
  66. 'HTTP_X_FORWARDED_HOST' in self.META):
  67. host = self.META['HTTP_X_FORWARDED_HOST']
  68. elif 'HTTP_HOST' in self.META:
  69. host = self.META['HTTP_HOST']
  70. else:
  71. # Reconstruct the host using the algorithm from PEP 333.
  72. host = self.META['SERVER_NAME']
  73. server_port = self.get_port()
  74. if server_port != ('443' if self.is_secure() else '80'):
  75. host = '%s:%s' % (host, server_port)
  76. return host
  77. def get_host(self):
  78. """Return the HTTP host using the environment or request headers."""
  79. host = self._get_raw_host()
  80. # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
  81. allowed_hosts = settings.ALLOWED_HOSTS
  82. if settings.DEBUG and not allowed_hosts:
  83. allowed_hosts = ['localhost', '127.0.0.1', '[::1]']
  84. domain, port = split_domain_port(host)
  85. if domain and validate_host(domain, allowed_hosts):
  86. return host
  87. else:
  88. msg = "Invalid HTTP_HOST header: %r." % host
  89. if domain:
  90. msg += " You may need to add %r to ALLOWED_HOSTS." % domain
  91. else:
  92. msg += " The domain name provided is not valid according to RFC 1034/1035."
  93. raise DisallowedHost(msg)
  94. def get_port(self):
  95. """Return the port number for the request as a string."""
  96. if settings.USE_X_FORWARDED_PORT and 'HTTP_X_FORWARDED_PORT' in self.META:
  97. port = self.META['HTTP_X_FORWARDED_PORT']
  98. else:
  99. port = self.META['SERVER_PORT']
  100. return str(port)
  101. def get_full_path(self, force_append_slash=False):
  102. return self._get_full_path(self.path, force_append_slash)
  103. def get_full_path_info(self, force_append_slash=False):
  104. return self._get_full_path(self.path_info, force_append_slash)
  105. def _get_full_path(self, path, force_append_slash):
  106. # RFC 3986 requires query string arguments to be in the ASCII range.
  107. # Rather than crash if this doesn't happen, we encode defensively.
  108. return '%s%s%s' % (
  109. escape_uri_path(path),
  110. '/' if force_append_slash and not path.endswith('/') else '',
  111. ('?' + iri_to_uri(self.META.get('QUERY_STRING', ''))) if self.META.get('QUERY_STRING', '') else ''
  112. )
  113. def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
  114. """
  115. Attempt to return a signed cookie. If the signature fails or the
  116. cookie has expired, raise an exception, unless the `default` argument
  117. is provided, in which case return that value.
  118. """
  119. try:
  120. cookie_value = self.COOKIES[key]
  121. except KeyError:
  122. if default is not RAISE_ERROR:
  123. return default
  124. else:
  125. raise
  126. try:
  127. value = signing.get_cookie_signer(salt=key + salt).unsign(
  128. cookie_value, max_age=max_age)
  129. except signing.BadSignature:
  130. if default is not RAISE_ERROR:
  131. return default
  132. else:
  133. raise
  134. return value
  135. def get_raw_uri(self):
  136. """
  137. Return an absolute URI from variables available in this request. Skip
  138. allowed hosts protection, so may return insecure URI.
  139. """
  140. return '{scheme}://{host}{path}'.format(
  141. scheme=self.scheme,
  142. host=self._get_raw_host(),
  143. path=self.get_full_path(),
  144. )
  145. def build_absolute_uri(self, location=None):
  146. """
  147. Build an absolute URI from the location and the variables available in
  148. this request. If no ``location`` is specified, build the absolute URI
  149. using request.get_full_path(). If the location is absolute, convert it
  150. to an RFC 3987 compliant URI and return it. If location is relative or
  151. is scheme-relative (i.e., ``//example.com/``), urljoin() it to a base
  152. URL constructed from the request variables.
  153. """
  154. if location is None:
  155. # Make it an absolute url (but schemeless and domainless) for the
  156. # edge case that the path starts with '//'.
  157. location = '//%s' % self.get_full_path()
  158. bits = urlsplit(location)
  159. if not (bits.scheme and bits.netloc):
  160. # Handle the simple, most common case. If the location is absolute
  161. # and a scheme or host (netloc) isn't provided, skip an expensive
  162. # urljoin() as long as no path segments are '.' or '..'.
  163. if (bits.path.startswith('/') and not bits.scheme and not bits.netloc and
  164. '/./' not in bits.path and '/../' not in bits.path):
  165. # If location starts with '//' but has no netloc, reuse the
  166. # schema and netloc from the current request. Strip the double
  167. # slashes and continue as if it wasn't specified.
  168. if location.startswith('//'):
  169. location = location[2:]
  170. location = self._current_scheme_host + location
  171. else:
  172. # Join the constructed URL with the provided location, which
  173. # allows the provided location to apply query strings to the
  174. # base path.
  175. location = urljoin(self._current_scheme_host + self.path, location)
  176. return iri_to_uri(location)
  177. @cached_property
  178. def _current_scheme_host(self):
  179. return '{}://{}'.format(self.scheme, self.get_host())
  180. def _get_scheme(self):
  181. """
  182. Hook for subclasses like WSGIRequest to implement. Return 'http' by
  183. default.
  184. """
  185. return 'http'
  186. @property
  187. def scheme(self):
  188. if settings.SECURE_PROXY_SSL_HEADER:
  189. try:
  190. header, secure_value = settings.SECURE_PROXY_SSL_HEADER
  191. except ValueError:
  192. raise ImproperlyConfigured(
  193. 'The SECURE_PROXY_SSL_HEADER setting must be a tuple containing two values.'
  194. )
  195. header_value = self.META.get(header)
  196. if header_value is not None:
  197. return 'https' if header_value == secure_value else 'http'
  198. return self._get_scheme()
  199. def is_secure(self):
  200. return self.scheme == 'https'
  201. def is_ajax(self):
  202. return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
  203. @property
  204. def encoding(self):
  205. return self._encoding
  206. @encoding.setter
  207. def encoding(self, val):
  208. """
  209. Set the encoding used for GET/POST accesses. If the GET or POST
  210. dictionary has already been created, remove and recreate it on the
  211. next access (so that it is decoded correctly).
  212. """
  213. self._encoding = val
  214. if hasattr(self, 'GET'):
  215. del self.GET
  216. if hasattr(self, '_post'):
  217. del self._post
  218. def _initialize_handlers(self):
  219. self._upload_handlers = [uploadhandler.load_handler(handler, self)
  220. for handler in settings.FILE_UPLOAD_HANDLERS]
  221. @property
  222. def upload_handlers(self):
  223. if not self._upload_handlers:
  224. # If there are no upload handlers defined, initialize them from settings.
  225. self._initialize_handlers()
  226. return self._upload_handlers
  227. @upload_handlers.setter
  228. def upload_handlers(self, upload_handlers):
  229. if hasattr(self, '_files'):
  230. raise AttributeError("You cannot set the upload handlers after the upload has been processed.")
  231. self._upload_handlers = upload_handlers
  232. def parse_file_upload(self, META, post_data):
  233. """Return a tuple of (POST QueryDict, FILES MultiValueDict)."""
  234. self.upload_handlers = ImmutableList(
  235. self.upload_handlers,
  236. warning="You cannot alter upload handlers after the upload has been processed."
  237. )
  238. parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
  239. return parser.parse()
  240. @property
  241. def body(self):
  242. if not hasattr(self, '_body'):
  243. if self._read_started:
  244. raise RawPostDataException("You cannot access body after reading from request's data stream")
  245. # Limit the maximum request data size that will be handled in-memory.
  246. if (settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and
  247. int(self.META.get('CONTENT_LENGTH') or 0) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE):
  248. raise RequestDataTooBig('Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE.')
  249. try:
  250. self._body = self.read()
  251. except IOError as e:
  252. raise UnreadablePostError(*e.args) from e
  253. self._stream = BytesIO(self._body)
  254. return self._body
  255. def _mark_post_parse_error(self):
  256. self._post = QueryDict()
  257. self._files = MultiValueDict()
  258. def _load_post_and_files(self):
  259. """Populate self._post and self._files if the content-type is a form type"""
  260. if self.method != 'POST':
  261. self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
  262. return
  263. if self._read_started and not hasattr(self, '_body'):
  264. self._mark_post_parse_error()
  265. return
  266. if self.content_type == 'multipart/form-data':
  267. if hasattr(self, '_body'):
  268. # Use already read data
  269. data = BytesIO(self._body)
  270. else:
  271. data = self
  272. try:
  273. self._post, self._files = self.parse_file_upload(self.META, data)
  274. except MultiPartParserError:
  275. # An error occurred while parsing POST data. Since when
  276. # formatting the error the request handler might access
  277. # self.POST, set self._post and self._file to prevent
  278. # attempts to parse POST data again.
  279. self._mark_post_parse_error()
  280. raise
  281. elif self.content_type == 'application/x-www-form-urlencoded':
  282. self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
  283. else:
  284. self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
  285. def close(self):
  286. if hasattr(self, '_files'):
  287. for f in chain.from_iterable(l[1] for l in self._files.lists()):
  288. f.close()
  289. # File-like and iterator interface.
  290. #
  291. # Expects self._stream to be set to an appropriate source of bytes by
  292. # a corresponding request subclass (e.g. WSGIRequest).
  293. # Also when request data has already been read by request.POST or
  294. # request.body, self._stream points to a BytesIO instance
  295. # containing that data.
  296. def read(self, *args, **kwargs):
  297. self._read_started = True
  298. try:
  299. return self._stream.read(*args, **kwargs)
  300. except IOError as e:
  301. raise UnreadablePostError(*e.args) from e
  302. def readline(self, *args, **kwargs):
  303. self._read_started = True
  304. try:
  305. return self._stream.readline(*args, **kwargs)
  306. except IOError as e:
  307. raise UnreadablePostError(*e.args) from e
  308. def __iter__(self):
  309. return iter(self.readline, b'')
  310. def xreadlines(self):
  311. warnings.warn(
  312. 'HttpRequest.xreadlines() is deprecated in favor of iterating the '
  313. 'request.', RemovedInDjango30Warning, stacklevel=2,
  314. )
  315. yield from self
  316. def readlines(self):
  317. return list(self)
  318. class HttpHeaders(CaseInsensitiveMapping):
  319. HTTP_PREFIX = 'HTTP_'
  320. # PEP 333 gives two headers which aren't prepended with HTTP_.
  321. UNPREFIXED_HEADERS = {'CONTENT_TYPE', 'CONTENT_LENGTH'}
  322. def __init__(self, environ):
  323. headers = {}
  324. for header, value in environ.items():
  325. name = self.parse_header_name(header)
  326. if name:
  327. headers[name] = value
  328. super().__init__(headers)
  329. @classmethod
  330. def parse_header_name(cls, header):
  331. if header.startswith(cls.HTTP_PREFIX):
  332. header = header[len(cls.HTTP_PREFIX):]
  333. elif header not in cls.UNPREFIXED_HEADERS:
  334. return None
  335. return header.replace('_', '-').title()
  336. class QueryDict(MultiValueDict):
  337. """
  338. A specialized MultiValueDict which represents a query string.
  339. A QueryDict can be used to represent GET or POST data. It subclasses
  340. MultiValueDict since keys in such data can be repeated, for instance
  341. in the data from a form with a <select multiple> field.
  342. By default QueryDicts are immutable, though the copy() method
  343. will always return a mutable copy.
  344. Both keys and values set on this class are converted from the given encoding
  345. (DEFAULT_CHARSET by default) to str.
  346. """
  347. # These are both reset in __init__, but is specified here at the class
  348. # level so that unpickling will have valid values
  349. _mutable = True
  350. _encoding = None
  351. def __init__(self, query_string=None, mutable=False, encoding=None):
  352. super().__init__()
  353. self.encoding = encoding or settings.DEFAULT_CHARSET
  354. query_string = query_string or ''
  355. parse_qsl_kwargs = {
  356. 'keep_blank_values': True,
  357. 'fields_limit': settings.DATA_UPLOAD_MAX_NUMBER_FIELDS,
  358. 'encoding': self.encoding,
  359. }
  360. if isinstance(query_string, bytes):
  361. # query_string normally contains URL-encoded data, a subset of ASCII.
  362. try:
  363. query_string = query_string.decode(self.encoding)
  364. except UnicodeDecodeError:
  365. # ... but some user agents are misbehaving :-(
  366. query_string = query_string.decode('iso-8859-1')
  367. for key, value in limited_parse_qsl(query_string, **parse_qsl_kwargs):
  368. self.appendlist(key, value)
  369. self._mutable = mutable
  370. @classmethod
  371. def fromkeys(cls, iterable, value='', mutable=False, encoding=None):
  372. """
  373. Return a new QueryDict with keys (may be repeated) from an iterable and
  374. values from value.
  375. """
  376. q = cls('', mutable=True, encoding=encoding)
  377. for key in iterable:
  378. q.appendlist(key, value)
  379. if not mutable:
  380. q._mutable = False
  381. return q
  382. @property
  383. def encoding(self):
  384. if self._encoding is None:
  385. self._encoding = settings.DEFAULT_CHARSET
  386. return self._encoding
  387. @encoding.setter
  388. def encoding(self, value):
  389. self._encoding = value
  390. def _assert_mutable(self):
  391. if not self._mutable:
  392. raise AttributeError("This QueryDict instance is immutable")
  393. def __setitem__(self, key, value):
  394. self._assert_mutable()
  395. key = bytes_to_text(key, self.encoding)
  396. value = bytes_to_text(value, self.encoding)
  397. super().__setitem__(key, value)
  398. def __delitem__(self, key):
  399. self._assert_mutable()
  400. super().__delitem__(key)
  401. def __copy__(self):
  402. result = self.__class__('', mutable=True, encoding=self.encoding)
  403. for key, value in self.lists():
  404. result.setlist(key, value)
  405. return result
  406. def __deepcopy__(self, memo):
  407. result = self.__class__('', mutable=True, encoding=self.encoding)
  408. memo[id(self)] = result
  409. for key, value in self.lists():
  410. result.setlist(copy.deepcopy(key, memo), copy.deepcopy(value, memo))
  411. return result
  412. def setlist(self, key, list_):
  413. self._assert_mutable()
  414. key = bytes_to_text(key, self.encoding)
  415. list_ = [bytes_to_text(elt, self.encoding) for elt in list_]
  416. super().setlist(key, list_)
  417. def setlistdefault(self, key, default_list=None):
  418. self._assert_mutable()
  419. return super().setlistdefault(key, default_list)
  420. def appendlist(self, key, value):
  421. self._assert_mutable()
  422. key = bytes_to_text(key, self.encoding)
  423. value = bytes_to_text(value, self.encoding)
  424. super().appendlist(key, value)
  425. def pop(self, key, *args):
  426. self._assert_mutable()
  427. return super().pop(key, *args)
  428. def popitem(self):
  429. self._assert_mutable()
  430. return super().popitem()
  431. def clear(self):
  432. self._assert_mutable()
  433. super().clear()
  434. def setdefault(self, key, default=None):
  435. self._assert_mutable()
  436. key = bytes_to_text(key, self.encoding)
  437. default = bytes_to_text(default, self.encoding)
  438. return super().setdefault(key, default)
  439. def copy(self):
  440. """Return a mutable copy of this object."""
  441. return self.__deepcopy__({})
  442. def urlencode(self, safe=None):
  443. """
  444. Return an encoded string of all query string arguments.
  445. `safe` specifies characters which don't require quoting, for example::
  446. >>> q = QueryDict(mutable=True)
  447. >>> q['next'] = '/a&b/'
  448. >>> q.urlencode()
  449. 'next=%2Fa%26b%2F'
  450. >>> q.urlencode(safe='/')
  451. 'next=/a%26b/'
  452. """
  453. output = []
  454. if safe:
  455. safe = safe.encode(self.encoding)
  456. def encode(k, v):
  457. return '%s=%s' % ((quote(k, safe), quote(v, safe)))
  458. else:
  459. def encode(k, v):
  460. return urlencode({k: v})
  461. for k, list_ in self.lists():
  462. output.extend(
  463. encode(k.encode(self.encoding), str(v).encode(self.encoding))
  464. for v in list_
  465. )
  466. return '&'.join(output)
  467. # It's neither necessary nor appropriate to use
  468. # django.utils.encoding.force_text for parsing URLs and form inputs. Thus,
  469. # this slightly more restricted function, used by QueryDict.
  470. def bytes_to_text(s, encoding):
  471. """
  472. Convert bytes objects to strings, using the given encoding. Illegally
  473. encoded input characters are replaced with Unicode "unknown" codepoint
  474. (\ufffd).
  475. Return any non-bytes objects without change.
  476. """
  477. if isinstance(s, bytes):
  478. return str(s, encoding, 'replace')
  479. else:
  480. return s
  481. def split_domain_port(host):
  482. """
  483. Return a (domain, port) tuple from a given host.
  484. Returned domain is lowercased. If the host is invalid, the domain will be
  485. empty.
  486. """
  487. host = host.lower()
  488. if not host_validation_re.match(host):
  489. return '', ''
  490. if host[-1] == ']':
  491. # It's an IPv6 address without a port.
  492. return host, ''
  493. bits = host.rsplit(':', 1)
  494. domain, port = bits if len(bits) == 2 else (bits[0], '')
  495. # Remove a trailing dot (if present) from the domain.
  496. domain = domain[:-1] if domain.endswith('.') else domain
  497. return domain, port
  498. def validate_host(host, allowed_hosts):
  499. """
  500. Validate the given host for this site.
  501. Check that the host looks valid and matches a host or host pattern in the
  502. given list of ``allowed_hosts``. Any pattern beginning with a period
  503. matches a domain and all its subdomains (e.g. ``.example.com`` matches
  504. ``example.com`` and any subdomain), ``*`` matches anything, and anything
  505. else must match exactly.
  506. Note: This function assumes that the given host is lowercased and has
  507. already had the port, if any, stripped off.
  508. Return ``True`` for a valid host, ``False`` otherwise.
  509. """
  510. return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts)