http.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 keep_lazy_text
  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. @keep_lazy_text
  36. def urlquote(url, safe='/'):
  37. """
  38. A version of Python's urllib.quote() function that can operate on unicode
  39. strings. The url is first UTF-8 encoded before quoting. The returned string
  40. can safely be used as part of an argument to a subsequent iri_to_uri() call
  41. without double-quoting occurring.
  42. """
  43. return force_text(quote(force_str(url), force_str(safe)))
  44. @keep_lazy_text
  45. def urlquote_plus(url, safe=''):
  46. """
  47. A version of Python's urllib.quote_plus() function that can operate on
  48. unicode strings. The url is first UTF-8 encoded before quoting. The
  49. returned string can safely be used as part of an argument to a subsequent
  50. iri_to_uri() call without double-quoting occurring.
  51. """
  52. return force_text(quote_plus(force_str(url), force_str(safe)))
  53. @keep_lazy_text
  54. def urlunquote(quoted_url):
  55. """
  56. A wrapper for Python's urllib.unquote() function that can operate on
  57. the result of django.utils.http.urlquote().
  58. """
  59. return force_text(unquote(force_str(quoted_url)))
  60. @keep_lazy_text
  61. def urlunquote_plus(quoted_url):
  62. """
  63. A wrapper for Python's urllib.unquote_plus() function that can operate on
  64. the result of django.utils.http.urlquote_plus().
  65. """
  66. return force_text(unquote_plus(force_str(quoted_url)))
  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. RFC2616 section 3.3.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 RFC2616 section 3.3.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. # RFC2616 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 is_same_domain(host, pattern):
  212. """
  213. Return ``True`` if the host is either an exact match or a match
  214. to the wildcard pattern.
  215. Any pattern beginning with a period matches a domain and all of its
  216. subdomains. (e.g. ``.example.com`` matches ``example.com`` and
  217. ``foo.example.com``). Anything else is an exact string match.
  218. """
  219. if not pattern:
  220. return False
  221. pattern = pattern.lower()
  222. return (
  223. pattern[0] == '.' and (host.endswith(pattern) or host == pattern[1:]) or
  224. pattern == host
  225. )
  226. def is_safe_url(url, host=None):
  227. """
  228. Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
  229. a different host and uses a safe scheme).
  230. Always returns ``False`` on an empty url.
  231. """
  232. if url is not None:
  233. url = url.strip()
  234. if not url:
  235. return False
  236. # Chrome treats \ completely as /
  237. url = url.replace('\\', '/')
  238. # Chrome considers any URL with more than two slashes to be absolute, but
  239. # urlparse is not so flexible. Treat any url with three slashes as unsafe.
  240. if url.startswith('///'):
  241. return False
  242. url_info = urlparse(url)
  243. # Forbid URLs like http:///example.com - with a scheme, but without a hostname.
  244. # In that URL, example.com is not the hostname but, a path component. However,
  245. # Chrome will still consider example.com to be the hostname, so we must not
  246. # allow this syntax.
  247. if not url_info.netloc and url_info.scheme:
  248. return False
  249. # Forbid URLs that start with control characters. Some browsers (like
  250. # Chrome) ignore quite a few control characters at the start of a
  251. # URL and might consider the URL as scheme relative.
  252. if unicodedata.category(url[0])[0] == 'C':
  253. return False
  254. return ((not url_info.netloc or url_info.netloc == host) and
  255. (not url_info.scheme or url_info.scheme in ['http', 'https']))