request.py 25 KB

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