http.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. import base64
  2. import calendar
  3. import datetime
  4. import re
  5. import unicodedata
  6. import warnings
  7. from binascii import Error as BinasciiError
  8. from email.utils import formatdate
  9. from urllib.parse import (
  10. ParseResult, SplitResult, _coerce_args, _splitnetloc, _splitparams, quote,
  11. quote_plus, scheme_chars, unquote, unquote_plus,
  12. urlencode as original_urlencode, uses_params,
  13. )
  14. from django.core.exceptions import TooManyFieldsSent
  15. from django.utils.datastructures import MultiValueDict
  16. from django.utils.deprecation import RemovedInDjango40Warning
  17. from django.utils.functional import keep_lazy_text
  18. # based on RFC 7232, Appendix C
  19. ETAG_MATCH = re.compile(r'''
  20. \A( # start of string and capture group
  21. (?:W/)? # optional weak indicator
  22. " # opening quote
  23. [^"]* # any sequence of non-quote characters
  24. " # end quote
  25. )\Z # end of string and capture group
  26. ''', re.X)
  27. MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split()
  28. __D = r'(?P<day>\d{2})'
  29. __D2 = r'(?P<day>[ \d]\d)'
  30. __M = r'(?P<mon>\w{3})'
  31. __Y = r'(?P<year>\d{4})'
  32. __Y2 = r'(?P<year>\d{2})'
  33. __T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})'
  34. RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T))
  35. RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T))
  36. ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y))
  37. RFC3986_GENDELIMS = ":/?#[]@"
  38. RFC3986_SUBDELIMS = "!$&'()*+,;="
  39. FIELDS_MATCH = re.compile('[&;]')
  40. @keep_lazy_text
  41. def urlquote(url, safe='/'):
  42. """
  43. A legacy compatibility wrapper to Python's urllib.parse.quote() function.
  44. (was used for unicode handling on Python 2)
  45. """
  46. warnings.warn(
  47. 'django.utils.http.urlquote() is deprecated in favor of '
  48. 'urllib.parse.quote().',
  49. RemovedInDjango40Warning, stacklevel=2,
  50. )
  51. return quote(url, safe)
  52. @keep_lazy_text
  53. def urlquote_plus(url, safe=''):
  54. """
  55. A legacy compatibility wrapper to Python's urllib.parse.quote_plus()
  56. function. (was used for unicode handling on Python 2)
  57. """
  58. warnings.warn(
  59. 'django.utils.http.urlquote_plus() is deprecated in favor of '
  60. 'urllib.parse.quote_plus(),',
  61. RemovedInDjango40Warning, stacklevel=2,
  62. )
  63. return quote_plus(url, safe)
  64. @keep_lazy_text
  65. def urlunquote(quoted_url):
  66. """
  67. A legacy compatibility wrapper to Python's urllib.parse.unquote() function.
  68. (was used for unicode handling on Python 2)
  69. """
  70. warnings.warn(
  71. 'django.utils.http.urlunquote() is deprecated in favor of '
  72. 'urllib.parse.unquote().',
  73. RemovedInDjango40Warning, stacklevel=2,
  74. )
  75. return unquote(quoted_url)
  76. @keep_lazy_text
  77. def urlunquote_plus(quoted_url):
  78. """
  79. A legacy compatibility wrapper to Python's urllib.parse.unquote_plus()
  80. function. (was used for unicode handling on Python 2)
  81. """
  82. warnings.warn(
  83. 'django.utils.http.urlunquote_plus() is deprecated in favor of '
  84. 'urllib.parse.unquote_plus().',
  85. RemovedInDjango40Warning, stacklevel=2,
  86. )
  87. return unquote_plus(quoted_url)
  88. def urlencode(query, doseq=False):
  89. """
  90. A version of Python's urllib.parse.urlencode() function that can operate on
  91. MultiValueDict and non-string values.
  92. """
  93. if isinstance(query, MultiValueDict):
  94. query = query.lists()
  95. elif hasattr(query, 'items'):
  96. query = query.items()
  97. query_params = []
  98. for key, value in query:
  99. if value is None:
  100. raise TypeError(
  101. "Cannot encode None for key '%s' in a query string. Did you "
  102. "mean to pass an empty string or omit the value?" % key
  103. )
  104. elif not doseq or isinstance(value, (str, bytes)):
  105. query_val = value
  106. else:
  107. try:
  108. itr = iter(value)
  109. except TypeError:
  110. query_val = value
  111. else:
  112. # Consume generators and iterators, when doseq=True, to
  113. # work around https://bugs.python.org/issue31706.
  114. query_val = []
  115. for item in itr:
  116. if item is None:
  117. raise TypeError(
  118. "Cannot encode None for key '%s' in a query "
  119. "string. Did you mean to pass an empty string or "
  120. "omit the value?" % key
  121. )
  122. elif not isinstance(item, bytes):
  123. item = str(item)
  124. query_val.append(item)
  125. query_params.append((key, query_val))
  126. return original_urlencode(query_params, doseq)
  127. def http_date(epoch_seconds=None):
  128. """
  129. Format the time to match the RFC1123 date format as specified by HTTP
  130. RFC7231 section 7.1.1.1.
  131. `epoch_seconds` is a floating point number expressed in seconds since the
  132. epoch, in UTC - such as that outputted by time.time(). If set to None, it
  133. defaults to the current time.
  134. Output a string in the format 'Wdy, DD Mon YYYY HH:MM:SS GMT'.
  135. """
  136. return formatdate(epoch_seconds, usegmt=True)
  137. def parse_http_date(date):
  138. """
  139. Parse a date format as specified by HTTP RFC7231 section 7.1.1.1.
  140. The three formats allowed by the RFC are accepted, even if only the first
  141. one is still in widespread use.
  142. Return an integer expressed in seconds since the epoch, in UTC.
  143. """
  144. # email.utils.parsedate() does the job for RFC1123 dates; unfortunately
  145. # RFC7231 makes it mandatory to support RFC850 dates too. So we roll
  146. # our own RFC-compliant parsing.
  147. for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE:
  148. m = regex.match(date)
  149. if m is not None:
  150. break
  151. else:
  152. raise ValueError("%r is not in a valid HTTP date format" % date)
  153. try:
  154. year = int(m.group('year'))
  155. if year < 100:
  156. current_year = datetime.datetime.utcnow().year
  157. current_century = current_year - (current_year % 100)
  158. if year - (current_year % 100) > 50:
  159. # year that appears to be more than 50 years in the future are
  160. # interpreted as representing the past.
  161. year += current_century - 100
  162. else:
  163. year += current_century
  164. month = MONTHS.index(m.group('mon').lower()) + 1
  165. day = int(m.group('day'))
  166. hour = int(m.group('hour'))
  167. min = int(m.group('min'))
  168. sec = int(m.group('sec'))
  169. result = datetime.datetime(year, month, day, hour, min, sec)
  170. return calendar.timegm(result.utctimetuple())
  171. except Exception as exc:
  172. raise ValueError("%r is not a valid date" % date) from exc
  173. def parse_http_date_safe(date):
  174. """
  175. Same as parse_http_date, but return None if the input is invalid.
  176. """
  177. try:
  178. return parse_http_date(date)
  179. except Exception:
  180. pass
  181. # Base 36 functions: useful for generating compact URLs
  182. def base36_to_int(s):
  183. """
  184. Convert a base 36 string to an int. Raise ValueError if the input won't fit
  185. into an int.
  186. """
  187. # To prevent overconsumption of server resources, reject any
  188. # base36 string that is longer than 13 base36 digits (13 digits
  189. # is sufficient to base36-encode any 64-bit integer)
  190. if len(s) > 13:
  191. raise ValueError("Base36 input too large")
  192. return int(s, 36)
  193. def int_to_base36(i):
  194. """Convert an integer to a base36 string."""
  195. char_set = '0123456789abcdefghijklmnopqrstuvwxyz'
  196. if i < 0:
  197. raise ValueError("Negative base36 conversion input.")
  198. if i < 36:
  199. return char_set[i]
  200. b36 = ''
  201. while i != 0:
  202. i, n = divmod(i, 36)
  203. b36 = char_set[n] + b36
  204. return b36
  205. def urlsafe_base64_encode(s):
  206. """
  207. Encode a bytestring to a base64 string for use in URLs. Strip any trailing
  208. equal signs.
  209. """
  210. return base64.urlsafe_b64encode(s).rstrip(b'\n=').decode('ascii')
  211. def urlsafe_base64_decode(s):
  212. """
  213. Decode a base64 encoded string. Add back any trailing equal signs that
  214. might have been stripped.
  215. """
  216. s = s.encode()
  217. try:
  218. return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b'='))
  219. except (LookupError, BinasciiError) as e:
  220. raise ValueError(e)
  221. def parse_etags(etag_str):
  222. """
  223. Parse a string of ETags given in an If-None-Match or If-Match header as
  224. defined by RFC 7232. Return a list of quoted ETags, or ['*'] if all ETags
  225. should be matched.
  226. """
  227. if etag_str.strip() == '*':
  228. return ['*']
  229. else:
  230. # Parse each ETag individually, and return any that are valid.
  231. etag_matches = (ETAG_MATCH.match(etag.strip()) for etag in etag_str.split(','))
  232. return [match.group(1) for match in etag_matches if match]
  233. def quote_etag(etag_str):
  234. """
  235. If the provided string is already a quoted ETag, return it. Otherwise, wrap
  236. the string in quotes, making it a strong ETag.
  237. """
  238. if ETAG_MATCH.match(etag_str):
  239. return etag_str
  240. else:
  241. return '"%s"' % etag_str
  242. def is_same_domain(host, pattern):
  243. """
  244. Return ``True`` if the host is either an exact match or a match
  245. to the wildcard pattern.
  246. Any pattern beginning with a period matches a domain and all of its
  247. subdomains. (e.g. ``.example.com`` matches ``example.com`` and
  248. ``foo.example.com``). Anything else is an exact string match.
  249. """
  250. if not pattern:
  251. return False
  252. pattern = pattern.lower()
  253. return (
  254. pattern[0] == '.' and (host.endswith(pattern) or host == pattern[1:]) or
  255. pattern == host
  256. )
  257. def url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False):
  258. """
  259. Return ``True`` if the url uses an allowed host and a safe scheme.
  260. Always return ``False`` on an empty url.
  261. If ``require_https`` is ``True``, only 'https' will be considered a valid
  262. scheme, as opposed to 'http' and 'https' with the default, ``False``.
  263. Note: "True" doesn't entail that a URL is "safe". It may still be e.g.
  264. quoted incorrectly. Ensure to also use django.utils.encoding.iri_to_uri()
  265. on the path component of untrusted URLs.
  266. """
  267. if url is not None:
  268. url = url.strip()
  269. if not url:
  270. return False
  271. if allowed_hosts is None:
  272. allowed_hosts = set()
  273. elif isinstance(allowed_hosts, str):
  274. allowed_hosts = {allowed_hosts}
  275. # Chrome treats \ completely as / in paths but it could be part of some
  276. # basic auth credentials so we need to check both URLs.
  277. return (
  278. _url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=require_https) and
  279. _url_has_allowed_host_and_scheme(url.replace('\\', '/'), allowed_hosts, require_https=require_https)
  280. )
  281. def is_safe_url(url, allowed_hosts, require_https=False):
  282. warnings.warn(
  283. 'django.utils.http.is_safe_url() is deprecated in favor of '
  284. 'url_has_allowed_host_and_scheme().',
  285. RemovedInDjango40Warning, stacklevel=2,
  286. )
  287. return url_has_allowed_host_and_scheme(url, allowed_hosts, require_https)
  288. # Copied from urllib.parse.urlparse() but uses fixed urlsplit() function.
  289. def _urlparse(url, scheme='', allow_fragments=True):
  290. """Parse a URL into 6 components:
  291. <scheme>://<netloc>/<path>;<params>?<query>#<fragment>
  292. Return a 6-tuple: (scheme, netloc, path, params, query, fragment).
  293. Note that we don't break the components up in smaller bits
  294. (e.g. netloc is a single string) and we don't expand % escapes."""
  295. url, scheme, _coerce_result = _coerce_args(url, scheme)
  296. splitresult = _urlsplit(url, scheme, allow_fragments)
  297. scheme, netloc, url, query, fragment = splitresult
  298. if scheme in uses_params and ';' in url:
  299. url, params = _splitparams(url)
  300. else:
  301. params = ''
  302. result = ParseResult(scheme, netloc, url, params, query, fragment)
  303. return _coerce_result(result)
  304. # Copied from urllib.parse.urlsplit() with
  305. # https://github.com/python/cpython/pull/661 applied.
  306. def _urlsplit(url, scheme='', allow_fragments=True):
  307. """Parse a URL into 5 components:
  308. <scheme>://<netloc>/<path>?<query>#<fragment>
  309. Return a 5-tuple: (scheme, netloc, path, query, fragment).
  310. Note that we don't break the components up in smaller bits
  311. (e.g. netloc is a single string) and we don't expand % escapes."""
  312. url, scheme, _coerce_result = _coerce_args(url, scheme)
  313. netloc = query = fragment = ''
  314. i = url.find(':')
  315. if i > 0:
  316. for c in url[:i]:
  317. if c not in scheme_chars:
  318. break
  319. else:
  320. scheme, url = url[:i].lower(), url[i + 1:]
  321. if url[:2] == '//':
  322. netloc, url = _splitnetloc(url, 2)
  323. if (('[' in netloc and ']' not in netloc) or
  324. (']' in netloc and '[' not in netloc)):
  325. raise ValueError("Invalid IPv6 URL")
  326. if allow_fragments and '#' in url:
  327. url, fragment = url.split('#', 1)
  328. if '?' in url:
  329. url, query = url.split('?', 1)
  330. v = SplitResult(scheme, netloc, url, query, fragment)
  331. return _coerce_result(v)
  332. def _url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False):
  333. # Chrome considers any URL with more than two slashes to be absolute, but
  334. # urlparse is not so flexible. Treat any url with three slashes as unsafe.
  335. if url.startswith('///'):
  336. return False
  337. try:
  338. url_info = _urlparse(url)
  339. except ValueError: # e.g. invalid IPv6 addresses
  340. return False
  341. # Forbid URLs like http:///example.com - with a scheme, but without a hostname.
  342. # In that URL, example.com is not the hostname but, a path component. However,
  343. # Chrome will still consider example.com to be the hostname, so we must not
  344. # allow this syntax.
  345. if not url_info.netloc and url_info.scheme:
  346. return False
  347. # Forbid URLs that start with control characters. Some browsers (like
  348. # Chrome) ignore quite a few control characters at the start of a
  349. # URL and might consider the URL as scheme relative.
  350. if unicodedata.category(url[0])[0] == 'C':
  351. return False
  352. scheme = url_info.scheme
  353. # Consider URLs without a scheme (e.g. //example.com/p) to be http.
  354. if not url_info.scheme and url_info.netloc:
  355. scheme = 'http'
  356. valid_schemes = ['https'] if require_https else ['http', 'https']
  357. return ((not url_info.netloc or url_info.netloc in allowed_hosts) and
  358. (not scheme or scheme in valid_schemes))
  359. def limited_parse_qsl(qs, keep_blank_values=False, encoding='utf-8',
  360. errors='replace', fields_limit=None):
  361. """
  362. Return a list of key/value tuples parsed from query string.
  363. Copied from urlparse with an additional "fields_limit" argument.
  364. Copyright (C) 2013 Python Software Foundation (see LICENSE.python).
  365. Arguments:
  366. qs: percent-encoded query string to be parsed
  367. keep_blank_values: flag indicating whether blank values in
  368. percent-encoded queries should be treated as blank strings. A
  369. true value indicates that blanks should be retained as blank
  370. strings. The default false value indicates that blank values
  371. are to be ignored and treated as if they were not included.
  372. encoding and errors: specify how to decode percent-encoded sequences
  373. into Unicode characters, as accepted by the bytes.decode() method.
  374. fields_limit: maximum number of fields parsed or an exception
  375. is raised. None means no limit and is the default.
  376. """
  377. if fields_limit:
  378. pairs = FIELDS_MATCH.split(qs, fields_limit)
  379. if len(pairs) > fields_limit:
  380. raise TooManyFieldsSent(
  381. 'The number of GET/POST parameters exceeded '
  382. 'settings.DATA_UPLOAD_MAX_NUMBER_FIELDS.'
  383. )
  384. else:
  385. pairs = FIELDS_MATCH.split(qs)
  386. r = []
  387. for name_value in pairs:
  388. if not name_value:
  389. continue
  390. nv = name_value.split('=', 1)
  391. if len(nv) != 2:
  392. # Handle case of a control-name with no equal sign
  393. if keep_blank_values:
  394. nv.append('')
  395. else:
  396. continue
  397. if nv[1] or keep_blank_values:
  398. name = nv[0].replace('+', ' ')
  399. name = unquote(name, encoding=encoding, errors=errors)
  400. value = nv[1].replace('+', ' ')
  401. value = unquote(value, encoding=encoding, errors=errors)
  402. r.append((name, value))
  403. return r
  404. def escape_leading_slashes(url):
  405. """
  406. If redirecting to an absolute path (two leading slashes), a slash must be
  407. escaped to prevent browsers from handling the path as schemaless and
  408. redirecting to another host.
  409. """
  410. if url.startswith('//'):
  411. url = '/%2F{}'.format(url[2:])
  412. return url