Development of an internal social media platform with personalised dashboards for students
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 15KB

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