Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

http.py 13KB

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