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

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