http.py 17 KB

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