http.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. import base64
  2. import re
  3. import unicodedata
  4. from binascii import Error as BinasciiError
  5. from datetime import UTC, datetime
  6. from email.utils import formatdate
  7. from urllib.parse import quote, unquote
  8. from urllib.parse import urlencode as original_urlencode
  9. from urllib.parse import urlsplit
  10. from django.utils.datastructures import MultiValueDict
  11. from django.utils.regex_helper import _lazy_re_compile
  12. # Based on RFC 9110 Appendix A.
  13. ETAG_MATCH = _lazy_re_compile(
  14. r"""
  15. \A( # start of string and capture group
  16. (?:W/)? # optional weak indicator
  17. " # opening quote
  18. [^"]* # any sequence of non-quote characters
  19. " # end quote
  20. )\Z # end of string and capture group
  21. """,
  22. re.X,
  23. )
  24. MAX_HEADER_LENGTH = 10_000
  25. MONTHS = "jan feb mar apr may jun jul aug sep oct nov dec".split()
  26. __D = r"(?P<day>[0-9]{2})"
  27. __D2 = r"(?P<day>[ 0-9][0-9])"
  28. __M = r"(?P<mon>\w{3})"
  29. __Y = r"(?P<year>[0-9]{4})"
  30. __Y2 = r"(?P<year>[0-9]{2})"
  31. __T = r"(?P<hour>[0-9]{2}):(?P<min>[0-9]{2}):(?P<sec>[0-9]{2})"
  32. RFC1123_DATE = _lazy_re_compile(r"^\w{3}, %s %s %s %s GMT$" % (__D, __M, __Y, __T))
  33. RFC850_DATE = _lazy_re_compile(r"^\w{6,9}, %s-%s-%s %s GMT$" % (__D, __M, __Y2, __T))
  34. ASCTIME_DATE = _lazy_re_compile(r"^\w{3} %s %s %s %s$" % (__M, __D2, __T, __Y))
  35. RFC3986_GENDELIMS = ":/?#[]@"
  36. RFC3986_SUBDELIMS = "!$&'()*+,;="
  37. MAX_URL_LENGTH = 2048
  38. MAX_URL_REDIRECT_LENGTH = 16384
  39. def urlencode(query, doseq=False):
  40. """
  41. A version of Python's urllib.parse.urlencode() function that can operate on
  42. MultiValueDict and non-string values.
  43. """
  44. if isinstance(query, MultiValueDict):
  45. query = query.lists()
  46. elif hasattr(query, "items"):
  47. query = query.items()
  48. query_params = []
  49. for key, value in query:
  50. if value is None:
  51. raise TypeError(
  52. "Cannot encode None for key '%s' in a query string. Did you "
  53. "mean to pass an empty string or omit the value?" % key
  54. )
  55. elif not doseq or isinstance(value, (str, bytes)):
  56. query_val = value
  57. else:
  58. try:
  59. itr = iter(value)
  60. except TypeError:
  61. query_val = value
  62. else:
  63. # Consume generators and iterators, when doseq=True, to
  64. # work around https://bugs.python.org/issue31706.
  65. query_val = []
  66. for item in itr:
  67. if item is None:
  68. raise TypeError(
  69. "Cannot encode None for key '%s' in a query "
  70. "string. Did you mean to pass an empty string or "
  71. "omit the value?" % key
  72. )
  73. elif not isinstance(item, bytes):
  74. item = str(item)
  75. query_val.append(item)
  76. query_params.append((key, query_val))
  77. return original_urlencode(query_params, doseq)
  78. def http_date(epoch_seconds=None):
  79. """
  80. Format the time to match the RFC 5322 date format as specified by RFC 9110
  81. Section 5.6.7.
  82. `epoch_seconds` is a floating point number expressed in seconds since the
  83. epoch, in UTC - such as that outputted by time.time(). If set to None, it
  84. defaults to the current time.
  85. Output a string in the format 'Wdy, DD Mon YYYY HH:MM:SS GMT'.
  86. """
  87. return formatdate(epoch_seconds, usegmt=True)
  88. def parse_http_date(date):
  89. """
  90. Parse a date format as specified by HTTP RFC 9110 Section 5.6.7.
  91. The three formats allowed by the RFC are accepted, even if only the first
  92. one is still in widespread use.
  93. Return an integer expressed in seconds since the epoch, in UTC.
  94. """
  95. # email.utils.parsedate() does the job for RFC 1123 dates; unfortunately
  96. # RFC 9110 makes it mandatory to support RFC 850 dates too. So we roll
  97. # our own RFC-compliant parsing.
  98. for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE:
  99. m = regex.match(date)
  100. if m is not None:
  101. break
  102. else:
  103. raise ValueError("%r is not in a valid HTTP date format" % date)
  104. try:
  105. year = int(m["year"])
  106. if year < 100:
  107. current_year = datetime.now(tz=UTC).year
  108. current_century = current_year - (current_year % 100)
  109. if year - (current_year % 100) > 50:
  110. # year that appears to be more than 50 years in the future are
  111. # interpreted as representing the past.
  112. year += current_century - 100
  113. else:
  114. year += current_century
  115. month = MONTHS.index(m["mon"].lower()) + 1
  116. day = int(m["day"])
  117. hour = int(m["hour"])
  118. min = int(m["min"])
  119. sec = int(m["sec"])
  120. result = datetime(year, month, day, hour, min, sec, tzinfo=UTC)
  121. return int(result.timestamp())
  122. except Exception as exc:
  123. raise ValueError("%r is not a valid date" % date) from exc
  124. def parse_http_date_safe(date):
  125. """
  126. Same as parse_http_date, but return None if the input is invalid.
  127. """
  128. try:
  129. return parse_http_date(date)
  130. except Exception:
  131. pass
  132. # Base 36 functions: useful for generating compact URLs
  133. def base36_to_int(s):
  134. """
  135. Convert a base 36 string to an int. Raise ValueError if the input won't fit
  136. into an int.
  137. """
  138. # To prevent overconsumption of server resources, reject any
  139. # base36 string that is longer than 13 base36 digits (13 digits
  140. # is sufficient to base36-encode any 64-bit integer)
  141. if len(s) > 13:
  142. raise ValueError("Base36 input too large")
  143. return int(s, 36)
  144. def int_to_base36(i):
  145. """Convert an integer to a base36 string."""
  146. char_set = "0123456789abcdefghijklmnopqrstuvwxyz"
  147. if i < 0:
  148. raise ValueError("Negative base36 conversion input.")
  149. if i < 36:
  150. return char_set[i]
  151. b36_parts = []
  152. while i != 0:
  153. i, n = divmod(i, 36)
  154. b36_parts.append(char_set[n])
  155. return "".join(reversed(b36_parts))
  156. def urlsafe_base64_encode(s):
  157. """
  158. Encode a bytestring to a base64 string for use in URLs. Strip any trailing
  159. equal signs.
  160. """
  161. return base64.urlsafe_b64encode(s).rstrip(b"\n=").decode("ascii")
  162. def urlsafe_base64_decode(s):
  163. """
  164. Decode a base64 encoded string. Add back any trailing equal signs that
  165. might have been stripped.
  166. """
  167. s = s.encode()
  168. try:
  169. return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b"="))
  170. except (LookupError, BinasciiError) as e:
  171. raise ValueError(e)
  172. def split_header_value(value, sep=","):
  173. """Yield stripped parts of an HTTP header value split by sep.
  174. Use only with headers whose values are token lists (e.g. Vary,
  175. Cache-Control). Do not use with headers that allow quoted strings in values
  176. (e.g. Set-Cookie), as commas inside values will be used as separators.
  177. """
  178. for part in value.split(sep):
  179. if stripped := part.strip():
  180. yield stripped
  181. def split_directive_names(value):
  182. """Yield the lowercased directive names from an HTTP header value.
  183. Any qualified value is discarded, so that qualified forms permitted by
  184. RFC 9111 (e.g. `private="Set-Cookie"`) reduce to their directive name
  185. ("private").
  186. Use to check for the presence of a directive when its value is not needed;
  187. use `split_header_value()` when the value matters (e.g. `max-age`).
  188. """
  189. for part in split_header_value(value):
  190. yield part.split("=", 1)[0].strip().lower()
  191. def parse_etags(etag_str):
  192. """
  193. Parse a string of ETags given in an If-None-Match or If-Match header as
  194. defined by RFC 9110. Return a list of quoted ETags, or ['*'] if all ETags
  195. should be matched.
  196. ETags values containing a comma are not supported, as the comma is used as
  197. list separator.
  198. """
  199. if etag_str.strip() == "*":
  200. return ["*"]
  201. else:
  202. # Parse each ETag individually, and return any that are valid.
  203. etag_matches = (ETAG_MATCH.match(etag) for etag in split_header_value(etag_str))
  204. return [match[1] for match in etag_matches if match]
  205. def quote_etag(etag_str):
  206. """
  207. If the provided string is already a quoted ETag, return it. Otherwise, wrap
  208. the string in quotes, making it a strong ETag.
  209. """
  210. if ETAG_MATCH.match(etag_str):
  211. return etag_str
  212. else:
  213. return '"%s"' % etag_str
  214. def is_same_domain(host, pattern):
  215. """
  216. Return ``True`` if the host is either an exact match or a match
  217. to the wildcard pattern.
  218. Any pattern beginning with a period matches a domain and all of its
  219. subdomains. (e.g. ``.example.com`` matches ``example.com`` and
  220. ``foo.example.com``). Anything else is an exact string match.
  221. """
  222. if not pattern:
  223. return False
  224. pattern = pattern.lower()
  225. return (
  226. pattern[0] == "."
  227. and (host.endswith(pattern) or host == pattern[1:])
  228. or pattern == host
  229. )
  230. def url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False):
  231. """
  232. Return ``True`` if the url uses an allowed host and a safe scheme.
  233. Always return ``False`` on an empty url.
  234. If ``require_https`` is ``True``, only 'https' will be considered a valid
  235. scheme, as opposed to 'http' and 'https' with the default, ``False``.
  236. Note: "True" doesn't entail that a URL is "safe". It may still be e.g.
  237. quoted incorrectly. Ensure to also use django.utils.encoding.iri_to_uri()
  238. on the path component of untrusted URLs.
  239. """
  240. if url is not None:
  241. url = url.strip()
  242. if not url:
  243. return False
  244. if allowed_hosts is None:
  245. allowed_hosts = set()
  246. elif isinstance(allowed_hosts, str):
  247. allowed_hosts = {allowed_hosts}
  248. # Chrome treats \ completely as / in paths but it could be part of some
  249. # basic auth credentials so we need to check both URLs.
  250. return _url_has_allowed_host_and_scheme(
  251. url, allowed_hosts, require_https=require_https
  252. ) and _url_has_allowed_host_and_scheme(
  253. url.replace("\\", "/"), allowed_hosts, require_https=require_https
  254. )
  255. def _url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False):
  256. # Chrome considers any URL with more than two slashes to be absolute, but
  257. # urlsplit is not so flexible. Treat any url with three slashes as unsafe.
  258. if url.startswith("///") or len(url) > MAX_URL_LENGTH:
  259. # urlsplit does not perform validation of inputs. Unicode normalization
  260. # is very slow on Windows and can be a DoS attack vector.
  261. # https://docs.python.org/3/library/urllib.parse.html#url-parsing-security
  262. return False
  263. try:
  264. url_info = urlsplit(url)
  265. except ValueError: # e.g. invalid IPv6 addresses
  266. return False
  267. # Forbid URLs like http:///example.com - with a scheme, but without a
  268. # hostname. In that URL, example.com is not the hostname but, a path
  269. # component. However, Chrome will still consider example.com to be the
  270. # hostname, so we must not allow this syntax.
  271. if not url_info.netloc and url_info.scheme:
  272. return False
  273. # Forbid URLs that start with control characters. Some browsers (like
  274. # Chrome) ignore quite a few control characters at the start of a
  275. # URL and might consider the URL as scheme relative.
  276. if unicodedata.category(url[0])[0] == "C":
  277. return False
  278. scheme = url_info.scheme
  279. # Consider URLs without a scheme (e.g. //example.com/p) to be http.
  280. if not url_info.scheme and url_info.netloc:
  281. scheme = "http"
  282. valid_schemes = ["https"] if require_https else ["http", "https"]
  283. return (not url_info.netloc or url_info.netloc in allowed_hosts) and (
  284. not scheme or scheme in valid_schemes
  285. )
  286. def escape_leading_slashes(url):
  287. """
  288. If redirecting to an absolute path (two leading slashes), a slash must be
  289. escaped to prevent browsers from handling the path as schemaless and
  290. redirecting to another host.
  291. """
  292. if url.startswith("//"):
  293. url = "/%2F{}".format(url.removeprefix("//"))
  294. return url
  295. def _parseparam(s):
  296. while s[:1] == ";":
  297. s = s[1:]
  298. end = s.find(";")
  299. while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2:
  300. end = s.find(";", end + 1)
  301. if end < 0:
  302. end = len(s)
  303. f = s[:end]
  304. yield f.strip()
  305. s = s[end:]
  306. def parse_header_parameters(line, max_length=MAX_HEADER_LENGTH):
  307. """
  308. Parse a Content-type like header.
  309. Return the main content-type and a dictionary of options.
  310. If `line` is longer than `max_length`, `ValueError` is raised.
  311. """
  312. if not line:
  313. return "", {}
  314. if max_length is not None and len(line) > max_length:
  315. raise ValueError("Unable to parse header parameters (value too long).")
  316. # Fast path for no params.
  317. if ";" not in line:
  318. return line.strip().lower(), {}
  319. parts = _parseparam(";" + line)
  320. key = parts.__next__().lower()
  321. pdict = {}
  322. for p in parts:
  323. i = p.find("=")
  324. if i >= 0:
  325. has_encoding = False
  326. name = p[:i].strip().lower()
  327. if name.endswith("*"):
  328. # Embedded lang/encoding, like "filename*=UTF-8''file.ext".
  329. # https://tools.ietf.org/html/rfc2231#section-4
  330. name = name[:-1]
  331. if p.count("'") == 2:
  332. has_encoding = True
  333. value = p[i + 1 :].strip()
  334. if len(value) >= 2 and value[0] == value[-1] == '"':
  335. value = value[1:-1]
  336. value = value.replace("\\\\", "\\").replace('\\"', '"')
  337. if has_encoding:
  338. encoding, lang, value = value.split("'")
  339. try:
  340. value = unquote(value, encoding=encoding)
  341. except (LookupError, UnicodeDecodeError):
  342. msg = f"Invalid encoding {encoding!r} for RFC 2231 param."
  343. raise ValueError(msg)
  344. pdict[name] = value
  345. return key, pdict
  346. def content_disposition_header(as_attachment, filename):
  347. """
  348. Construct a Content-Disposition HTTP header value from the given filename
  349. as specified by RFC 6266.
  350. """
  351. if filename:
  352. disposition = "attachment" if as_attachment else "inline"
  353. try:
  354. filename.encode("ascii")
  355. is_ascii = True
  356. except UnicodeEncodeError:
  357. is_ascii = False
  358. # Quoted strings can contain horizontal tabs, space characters, and
  359. # characters from 0x21 to 0x7e, except 0x22 (`"`) and 0x5C (`\`) which
  360. # can still be expressed but must be escaped with their own `\`.
  361. # https://datatracker.ietf.org/doc/html/rfc9110#name-quoted-strings
  362. quotable_characters = r"^[\t \x21-\x7e]*$"
  363. if is_ascii and re.match(quotable_characters, filename):
  364. file_expr = 'filename="{}"'.format(
  365. filename.replace("\\", "\\\\").replace('"', r"\"")
  366. )
  367. else:
  368. file_expr = "filename*=utf-8''{}".format(quote(filename))
  369. return f"{disposition}; {file_expr}"
  370. elif as_attachment:
  371. return "attachment"
  372. else:
  373. return None