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 10 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. from __future__ import unicode_literals
  2. import base64
  3. import calendar
  4. import datetime
  5. import re
  6. import sys
  7. import unicodedata
  8. from binascii import Error as BinasciiError
  9. from email.utils import formatdate
  10. from django.utils import six
  11. from django.utils.datastructures import MultiValueDict
  12. from django.utils.encoding import force_bytes, force_str, force_text
  13. from django.utils.functional import allow_lazy
  14. from django.utils.six.moves.urllib.parse import (
  15. quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode,
  16. urlparse,
  17. )
  18. ETAG_MATCH = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"')
  19. MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split()
  20. __D = r'(?P<day>\d{2})'
  21. __D2 = r'(?P<day>[ \d]\d)'
  22. __M = r'(?P<mon>\w{3})'
  23. __Y = r'(?P<year>\d{4})'
  24. __Y2 = r'(?P<year>\d{2})'
  25. __T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})'
  26. RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T))
  27. RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T))
  28. ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y))
  29. RFC3986_GENDELIMS = str(":/?#[]@")
  30. RFC3986_SUBDELIMS = str("!$&'()*+,;=")
  31. PROTOCOL_TO_PORT = {
  32. 'http': 80,
  33. 'https': 443,
  34. }
  35. def urlquote(url, safe='/'):
  36. """
  37. A version of Python's urllib.quote() function that can operate on unicode
  38. strings. The url is first UTF-8 encoded before quoting. The returned string
  39. can safely be used as part of an argument to a subsequent iri_to_uri() call
  40. without double-quoting occurring.
  41. """
  42. return force_text(quote(force_str(url), force_str(safe)))
  43. urlquote = allow_lazy(urlquote, six.text_type)
  44. def urlquote_plus(url, safe=''):
  45. """
  46. A version of Python's urllib.quote_plus() function that can operate on
  47. unicode strings. The url is first UTF-8 encoded before quoting. The
  48. returned string can safely be used as part of an argument to a subsequent
  49. iri_to_uri() call without double-quoting occurring.
  50. """
  51. return force_text(quote_plus(force_str(url), force_str(safe)))
  52. urlquote_plus = allow_lazy(urlquote_plus, six.text_type)
  53. def urlunquote(quoted_url):
  54. """
  55. A wrapper for Python's urllib.unquote() function that can operate on
  56. the result of django.utils.http.urlquote().
  57. """
  58. return force_text(unquote(force_str(quoted_url)))
  59. urlunquote = allow_lazy(urlunquote, six.text_type)
  60. def urlunquote_plus(quoted_url):
  61. """
  62. A wrapper for Python's urllib.unquote_plus() function that can operate on
  63. the result of django.utils.http.urlquote_plus().
  64. """
  65. return force_text(unquote_plus(force_str(quoted_url)))
  66. urlunquote_plus = allow_lazy(urlunquote_plus, six.text_type)
  67. def urlencode(query, doseq=0):
  68. """
  69. A version of Python's urllib.urlencode() function that can operate on
  70. unicode strings. The parameters are first cast to UTF-8 encoded strings and
  71. then encoded as per normal.
  72. """
  73. if isinstance(query, MultiValueDict):
  74. query = query.lists()
  75. elif hasattr(query, 'items'):
  76. query = query.items()
  77. return original_urlencode(
  78. [(force_str(k),
  79. [force_str(i) for i in v] if isinstance(v, (list, tuple)) else force_str(v))
  80. for k, v in query],
  81. doseq)
  82. def cookie_date(epoch_seconds=None):
  83. """
  84. Formats the time to ensure compatibility with Netscape's cookie standard.
  85. Accepts a floating point number expressed in seconds since the epoch, in
  86. UTC - such as that outputted by time.time(). If set to None, defaults to
  87. the current time.
  88. Outputs a string in the format 'Wdy, DD-Mon-YYYY HH:MM:SS GMT'.
  89. """
  90. rfcdate = formatdate(epoch_seconds)
  91. return '%s-%s-%s GMT' % (rfcdate[:7], rfcdate[8:11], rfcdate[12:25])
  92. def http_date(epoch_seconds=None):
  93. """
  94. Formats the time to match the RFC1123 date format as specified by HTTP
  95. RFC7231 section 7.1.1.1.
  96. Accepts a floating point number expressed in seconds since the epoch, in
  97. UTC - such as that outputted by time.time(). If set to None, defaults to
  98. the current time.
  99. Outputs a string in the format 'Wdy, DD Mon YYYY HH:MM:SS GMT'.
  100. """
  101. return formatdate(epoch_seconds, usegmt=True)
  102. def parse_http_date(date):
  103. """
  104. Parses a date format as specified by HTTP RFC7231 section 7.1.1.1.
  105. The three formats allowed by the RFC are accepted, even if only the first
  106. one is still in widespread use.
  107. Returns an integer expressed in seconds since the epoch, in UTC.
  108. """
  109. # emails.Util.parsedate does the job for RFC1123 dates; unfortunately
  110. # RFC7231 makes it mandatory to support RFC850 dates too. So we roll
  111. # our own RFC-compliant parsing.
  112. for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE:
  113. m = regex.match(date)
  114. if m is not None:
  115. break
  116. else:
  117. raise ValueError("%r is not in a valid HTTP date format" % date)
  118. try:
  119. year = int(m.group('year'))
  120. if year < 100:
  121. if year < 70:
  122. year += 2000
  123. else:
  124. year += 1900
  125. month = MONTHS.index(m.group('mon').lower()) + 1
  126. day = int(m.group('day'))
  127. hour = int(m.group('hour'))
  128. min = int(m.group('min'))
  129. sec = int(m.group('sec'))
  130. result = datetime.datetime(year, month, day, hour, min, sec)
  131. return calendar.timegm(result.utctimetuple())
  132. except Exception:
  133. six.reraise(ValueError, ValueError("%r is not a valid date" % date), sys.exc_info()[2])
  134. def parse_http_date_safe(date):
  135. """
  136. Same as parse_http_date, but returns None if the input is invalid.
  137. """
  138. try:
  139. return parse_http_date(date)
  140. except Exception:
  141. pass
  142. # Base 36 functions: useful for generating compact URLs
  143. def base36_to_int(s):
  144. """
  145. Converts a base 36 string to an ``int``. Raises ``ValueError` if the
  146. input won't fit into an int.
  147. """
  148. # To prevent overconsumption of server resources, reject any
  149. # base36 string that is long than 13 base36 digits (13 digits
  150. # is sufficient to base36-encode any 64-bit integer)
  151. if len(s) > 13:
  152. raise ValueError("Base36 input too large")
  153. value = int(s, 36)
  154. # ... then do a final check that the value will fit into an int to avoid
  155. # returning a long (#15067). The long type was removed in Python 3.
  156. if six.PY2 and value > sys.maxint:
  157. raise ValueError("Base36 input too large")
  158. return value
  159. def int_to_base36(i):
  160. """
  161. Converts an integer to a base36 string
  162. """
  163. char_set = '0123456789abcdefghijklmnopqrstuvwxyz'
  164. if i < 0:
  165. raise ValueError("Negative base36 conversion input.")
  166. if six.PY2:
  167. if not isinstance(i, six.integer_types):
  168. raise TypeError("Non-integer base36 conversion input.")
  169. if i > sys.maxint:
  170. raise ValueError("Base36 conversion input too large.")
  171. if i < 36:
  172. return char_set[i]
  173. b36 = ''
  174. while i != 0:
  175. i, n = divmod(i, 36)
  176. b36 = char_set[n] + b36
  177. return b36
  178. def urlsafe_base64_encode(s):
  179. """
  180. Encodes a bytestring in base64 for use in URLs, stripping any trailing
  181. equal signs.
  182. """
  183. return base64.urlsafe_b64encode(s).rstrip(b'\n=')
  184. def urlsafe_base64_decode(s):
  185. """
  186. Decodes a base64 encoded string, adding back any trailing equal signs that
  187. might have been stripped.
  188. """
  189. s = force_bytes(s)
  190. try:
  191. return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b'='))
  192. except (LookupError, BinasciiError) as e:
  193. raise ValueError(e)
  194. def parse_etags(etag_str):
  195. """
  196. Parses a string with one or several etags passed in If-None-Match and
  197. If-Match headers by the rules in RFC 2616. Returns a list of etags
  198. without surrounding double quotes (") and unescaped from \<CHAR>.
  199. """
  200. etags = ETAG_MATCH.findall(etag_str)
  201. if not etags:
  202. # etag_str has wrong format, treat it as an opaque string then
  203. return [etag_str]
  204. etags = [e.encode('ascii').decode('unicode_escape') for e in etags]
  205. return etags
  206. def quote_etag(etag):
  207. """
  208. Wraps a string in double quotes escaping contents as necessary.
  209. """
  210. return '"%s"' % etag.replace('\\', '\\\\').replace('"', '\\"')
  211. def unquote_etag(etag):
  212. """
  213. Unquote an ETag string; i.e. revert quote_etag().
  214. """
  215. return etag.strip('"').replace('\\"', '"').replace('\\\\', '\\') if etag else etag
  216. def is_same_domain(host, pattern):
  217. """
  218. Return ``True`` if the host is either an exact match or a match
  219. to the wildcard pattern.
  220. Any pattern beginning with a period matches a domain and all of its
  221. subdomains. (e.g. ``.example.com`` matches ``example.com`` and
  222. ``foo.example.com``). Anything else is an exact string match.
  223. """
  224. if not pattern:
  225. return False
  226. pattern = pattern.lower()
  227. return (
  228. pattern[0] == '.' and (host.endswith(pattern) or host == pattern[1:]) or
  229. pattern == host
  230. )
  231. def is_safe_url(url, host=None):
  232. """
  233. Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
  234. a different host and uses a safe scheme).
  235. Always returns ``False`` on an empty url.
  236. """
  237. if url is not None:
  238. url = url.strip()
  239. if not url:
  240. return False
  241. if six.PY2:
  242. try:
  243. url = force_text(url)
  244. except UnicodeDecodeError:
  245. return False
  246. # Chrome treats \ completely as / in paths but it could be part of some
  247. # basic auth credentials so we need to check both URLs.
  248. return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)
  249. def _is_safe_url(url, host):
  250. # Chrome considers any URL with more than two slashes to be absolute, but
  251. # urlparse is not so flexible. Treat any url with three slashes as unsafe.
  252. if url.startswith('///'):
  253. return False
  254. url_info = urlparse(url)
  255. # Forbid URLs like http:///example.com - with a scheme, but without a hostname.
  256. # In that URL, example.com is not the hostname but, a path component. However,
  257. # Chrome will still consider example.com to be the hostname, so we must not
  258. # allow this syntax.
  259. if not url_info.netloc and url_info.scheme:
  260. return False
  261. # Forbid URLs that start with control characters. Some browsers (like
  262. # Chrome) ignore quite a few control characters at the start of a
  263. # URL and might consider the URL as scheme relative.
  264. if unicodedata.category(url[0])[0] == 'C':
  265. return False
  266. return ((not url_info.netloc or url_info.netloc == host) and
  267. (not url_info.scheme or url_info.scheme in ['http', 'https']))