http.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import base64
  2. import datetime
  3. import re
  4. import unicodedata
  5. from binascii import Error as BinasciiError
  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. tz = datetime.timezone.utc
  103. year = int(m["year"])
  104. if year < 100:
  105. current_year = datetime.datetime.now(tz=tz).year
  106. current_century = current_year - (current_year % 100)
  107. if year - (current_year % 100) > 50:
  108. # year that appears to be more than 50 years in the future are
  109. # interpreted as representing the past.
  110. year += current_century - 100
  111. else:
  112. year += current_century
  113. month = MONTHS.index(m["mon"].lower()) + 1
  114. day = int(m["day"])
  115. hour = int(m["hour"])
  116. min = int(m["min"])
  117. sec = int(m["sec"])
  118. result = datetime.datetime(year, month, day, hour, min, sec, tzinfo=tz)
  119. return int(result.timestamp())
  120. except Exception as exc:
  121. raise ValueError("%r is not a valid date" % date) from exc
  122. def parse_http_date_safe(date):
  123. """
  124. Same as parse_http_date, but return None if the input is invalid.
  125. """
  126. try:
  127. return parse_http_date(date)
  128. except Exception:
  129. pass
  130. # Base 36 functions: useful for generating compact URLs
  131. def base36_to_int(s):
  132. """
  133. Convert a base 36 string to an int. Raise ValueError if the input won't fit
  134. into an int.
  135. """
  136. # To prevent overconsumption of server resources, reject any
  137. # base36 string that is longer than 13 base36 digits (13 digits
  138. # is sufficient to base36-encode any 64-bit integer)
  139. if len(s) > 13:
  140. raise ValueError("Base36 input too large")
  141. return int(s, 36)
  142. def int_to_base36(i):
  143. """Convert an integer to a base36 string."""
  144. char_set = "0123456789abcdefghijklmnopqrstuvwxyz"
  145. if i < 0:
  146. raise ValueError("Negative base36 conversion input.")
  147. if i < 36:
  148. return char_set[i]
  149. b36 = ""
  150. while i != 0:
  151. i, n = divmod(i, 36)
  152. b36 = char_set[n] + b36
  153. return b36
  154. def urlsafe_base64_encode(s):
  155. """
  156. Encode a bytestring to a base64 string for use in URLs. Strip any trailing
  157. equal signs.
  158. """
  159. return base64.urlsafe_b64encode(s).rstrip(b"\n=").decode("ascii")
  160. def urlsafe_base64_decode(s):
  161. """
  162. Decode a base64 encoded string. Add back any trailing equal signs that
  163. might have been stripped.
  164. """
  165. s = s.encode()
  166. try:
  167. return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b"="))
  168. except (LookupError, BinasciiError) as e:
  169. raise ValueError(e)
  170. def parse_etags(etag_str):
  171. """
  172. Parse a string of ETags given in an If-None-Match or If-Match header as
  173. defined by RFC 9110. Return a list of quoted ETags, or ['*'] if all ETags
  174. should be matched.
  175. """
  176. if etag_str.strip() == "*":
  177. return ["*"]
  178. else:
  179. # Parse each ETag individually, and return any that are valid.
  180. etag_matches = (ETAG_MATCH.match(etag.strip()) for etag in etag_str.split(","))
  181. return [match[1] for match in etag_matches if match]
  182. def quote_etag(etag_str):
  183. """
  184. If the provided string is already a quoted ETag, return it. Otherwise, wrap
  185. the string in quotes, making it a strong ETag.
  186. """
  187. if ETAG_MATCH.match(etag_str):
  188. return etag_str
  189. else:
  190. return '"%s"' % etag_str
  191. def is_same_domain(host, pattern):
  192. """
  193. Return ``True`` if the host is either an exact match or a match
  194. to the wildcard pattern.
  195. Any pattern beginning with a period matches a domain and all of its
  196. subdomains. (e.g. ``.example.com`` matches ``example.com`` and
  197. ``foo.example.com``). Anything else is an exact string match.
  198. """
  199. if not pattern:
  200. return False
  201. pattern = pattern.lower()
  202. return (
  203. pattern[0] == "."
  204. and (host.endswith(pattern) or host == pattern[1:])
  205. or pattern == host
  206. )
  207. def url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False):
  208. """
  209. Return ``True`` if the url uses an allowed host and a safe scheme.
  210. Always return ``False`` on an empty url.
  211. If ``require_https`` is ``True``, only 'https' will be considered a valid
  212. scheme, as opposed to 'http' and 'https' with the default, ``False``.
  213. Note: "True" doesn't entail that a URL is "safe". It may still be e.g.
  214. quoted incorrectly. Ensure to also use django.utils.encoding.iri_to_uri()
  215. on the path component of untrusted URLs.
  216. """
  217. if url is not None:
  218. url = url.strip()
  219. if not url:
  220. return False
  221. if allowed_hosts is None:
  222. allowed_hosts = set()
  223. elif isinstance(allowed_hosts, str):
  224. allowed_hosts = {allowed_hosts}
  225. # Chrome treats \ completely as / in paths but it could be part of some
  226. # basic auth credentials so we need to check both URLs.
  227. return _url_has_allowed_host_and_scheme(
  228. url, allowed_hosts, require_https=require_https
  229. ) and _url_has_allowed_host_and_scheme(
  230. url.replace("\\", "/"), allowed_hosts, require_https=require_https
  231. )
  232. def _url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False):
  233. # Chrome considers any URL with more than two slashes to be absolute, but
  234. # urlparse is not so flexible. Treat any url with three slashes as unsafe.
  235. if url.startswith("///"):
  236. return False
  237. try:
  238. url_info = urlparse(url)
  239. except ValueError: # e.g. invalid IPv6 addresses
  240. return False
  241. # Forbid URLs like http:///example.com - with a scheme, but without a hostname.
  242. # In that URL, example.com is not the hostname but, a path component. However,
  243. # Chrome will still consider example.com to be the hostname, so we must not
  244. # allow this syntax.
  245. if not url_info.netloc and url_info.scheme:
  246. return False
  247. # Forbid URLs that start with control characters. Some browsers (like
  248. # Chrome) ignore quite a few control characters at the start of a
  249. # URL and might consider the URL as scheme relative.
  250. if unicodedata.category(url[0])[0] == "C":
  251. return False
  252. scheme = url_info.scheme
  253. # Consider URLs without a scheme (e.g. //example.com/p) to be http.
  254. if not url_info.scheme and url_info.netloc:
  255. scheme = "http"
  256. valid_schemes = ["https"] if require_https else ["http", "https"]
  257. return (not url_info.netloc or url_info.netloc in allowed_hosts) and (
  258. not scheme or scheme in valid_schemes
  259. )
  260. def escape_leading_slashes(url):
  261. """
  262. If redirecting to an absolute path (two leading slashes), a slash must be
  263. escaped to prevent browsers from handling the path as schemaless and
  264. redirecting to another host.
  265. """
  266. if url.startswith("//"):
  267. url = "/%2F{}".format(url.removeprefix("//"))
  268. return url
  269. def _parseparam(s):
  270. while s[:1] == ";":
  271. s = s[1:]
  272. end = s.find(";")
  273. while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2:
  274. end = s.find(";", end + 1)
  275. if end < 0:
  276. end = len(s)
  277. f = s[:end]
  278. yield f.strip()
  279. s = s[end:]
  280. def parse_header_parameters(line):
  281. """
  282. Parse a Content-type like header.
  283. Return the main content-type and a dictionary of options.
  284. """
  285. parts = _parseparam(";" + line)
  286. key = parts.__next__().lower()
  287. pdict = {}
  288. for p in parts:
  289. i = p.find("=")
  290. if i >= 0:
  291. has_encoding = False
  292. name = p[:i].strip().lower()
  293. if name.endswith("*"):
  294. # Lang/encoding embedded in the value (like "filename*=UTF-8''file.ext")
  295. # https://tools.ietf.org/html/rfc2231#section-4
  296. name = name[:-1]
  297. if p.count("'") == 2:
  298. has_encoding = True
  299. value = p[i + 1 :].strip()
  300. if len(value) >= 2 and value[0] == value[-1] == '"':
  301. value = value[1:-1]
  302. value = value.replace("\\\\", "\\").replace('\\"', '"')
  303. if has_encoding:
  304. encoding, lang, value = value.split("'")
  305. value = unquote(value, encoding=encoding)
  306. pdict[name] = value
  307. return key, pdict
  308. def content_disposition_header(as_attachment, filename):
  309. """
  310. Construct a Content-Disposition HTTP header value from the given filename
  311. as specified by RFC 6266.
  312. """
  313. if filename:
  314. disposition = "attachment" if as_attachment else "inline"
  315. try:
  316. filename.encode("ascii")
  317. file_expr = 'filename="{}"'.format(
  318. filename.replace("\\", "\\\\").replace('"', r"\"")
  319. )
  320. except UnicodeEncodeError:
  321. file_expr = "filename*=utf-8''{}".format(quote(filename))
  322. return f"{disposition}; {file_expr}"
  323. elif as_attachment:
  324. return "attachment"
  325. else:
  326. return None