http.py 12 KB

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