escape.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2009 Facebook
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. """Escaping/unescaping methods for HTML, JSON, URLs, and others.
  17. Also includes a few other miscellaneous string manipulation functions that
  18. have crept in over time.
  19. """
  20. from __future__ import absolute_import, division, print_function, with_statement
  21. import re
  22. import sys
  23. from tornado.util import unicode_type, basestring_type, u
  24. try:
  25. from urllib.parse import parse_qs as _parse_qs # py3
  26. except ImportError:
  27. from urlparse import parse_qs as _parse_qs # Python 2.6+
  28. try:
  29. import htmlentitydefs # py2
  30. except ImportError:
  31. import html.entities as htmlentitydefs # py3
  32. try:
  33. import urllib.parse as urllib_parse # py3
  34. except ImportError:
  35. import urllib as urllib_parse # py2
  36. import json
  37. try:
  38. unichr
  39. except NameError:
  40. unichr = chr
  41. _XHTML_ESCAPE_RE = re.compile('[&<>"\']')
  42. _XHTML_ESCAPE_DICT = {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;',
  43. '\'': '&#39;'}
  44. def xhtml_escape(value):
  45. """Escapes a string so it is valid within HTML or XML.
  46. Escapes the characters ``<``, ``>``, ``"``, ``'``, and ``&``.
  47. When used in attribute values the escaped strings must be enclosed
  48. in quotes.
  49. .. versionchanged:: 3.2
  50. Added the single quote to the list of escaped characters.
  51. """
  52. return _XHTML_ESCAPE_RE.sub(lambda match: _XHTML_ESCAPE_DICT[match.group(0)],
  53. to_basestring(value))
  54. def xhtml_unescape(value):
  55. """Un-escapes an XML-escaped string."""
  56. return re.sub(r"&(#?)(\w+?);", _convert_entity, _unicode(value))
  57. # The fact that json_encode wraps json.dumps is an implementation detail.
  58. # Please see https://github.com/tornadoweb/tornado/pull/706
  59. # before sending a pull request that adds **kwargs to this function.
  60. def json_encode(value):
  61. """JSON-encodes the given Python object."""
  62. # JSON permits but does not require forward slashes to be escaped.
  63. # This is useful when json data is emitted in a <script> tag
  64. # in HTML, as it prevents </script> tags from prematurely terminating
  65. # the javascript. Some json libraries do this escaping by default,
  66. # although python's standard library does not, so we do it here.
  67. # http://stackoverflow.com/questions/1580647/json-why-are-forward-slashes-escaped
  68. return json.dumps(value).replace("</", "<\\/")
  69. def json_decode(value):
  70. """Returns Python objects for the given JSON string."""
  71. return json.loads(to_basestring(value))
  72. def squeeze(value):
  73. """Replace all sequences of whitespace chars with a single space."""
  74. return re.sub(r"[\x00-\x20]+", " ", value).strip()
  75. def url_escape(value, plus=True):
  76. """Returns a URL-encoded version of the given value.
  77. If ``plus`` is true (the default), spaces will be represented
  78. as "+" instead of "%20". This is appropriate for query strings
  79. but not for the path component of a URL. Note that this default
  80. is the reverse of Python's urllib module.
  81. .. versionadded:: 3.1
  82. The ``plus`` argument
  83. """
  84. quote = urllib_parse.quote_plus if plus else urllib_parse.quote
  85. return quote(utf8(value))
  86. # python 3 changed things around enough that we need two separate
  87. # implementations of url_unescape. We also need our own implementation
  88. # of parse_qs since python 3's version insists on decoding everything.
  89. if sys.version_info[0] < 3:
  90. def url_unescape(value, encoding='utf-8', plus=True):
  91. """Decodes the given value from a URL.
  92. The argument may be either a byte or unicode string.
  93. If encoding is None, the result will be a byte string. Otherwise,
  94. the result is a unicode string in the specified encoding.
  95. If ``plus`` is true (the default), plus signs will be interpreted
  96. as spaces (literal plus signs must be represented as "%2B"). This
  97. is appropriate for query strings and form-encoded values but not
  98. for the path component of a URL. Note that this default is the
  99. reverse of Python's urllib module.
  100. .. versionadded:: 3.1
  101. The ``plus`` argument
  102. """
  103. unquote = (urllib_parse.unquote_plus if plus else urllib_parse.unquote)
  104. if encoding is None:
  105. return unquote(utf8(value))
  106. else:
  107. return unicode_type(unquote(utf8(value)), encoding)
  108. parse_qs_bytes = _parse_qs
  109. else:
  110. def url_unescape(value, encoding='utf-8', plus=True):
  111. """Decodes the given value from a URL.
  112. The argument may be either a byte or unicode string.
  113. If encoding is None, the result will be a byte string. Otherwise,
  114. the result is a unicode string in the specified encoding.
  115. If ``plus`` is true (the default), plus signs will be interpreted
  116. as spaces (literal plus signs must be represented as "%2B"). This
  117. is appropriate for query strings and form-encoded values but not
  118. for the path component of a URL. Note that this default is the
  119. reverse of Python's urllib module.
  120. .. versionadded:: 3.1
  121. The ``plus`` argument
  122. """
  123. if encoding is None:
  124. if plus:
  125. # unquote_to_bytes doesn't have a _plus variant
  126. value = to_basestring(value).replace('+', ' ')
  127. return urllib_parse.unquote_to_bytes(value)
  128. else:
  129. unquote = (urllib_parse.unquote_plus if plus
  130. else urllib_parse.unquote)
  131. return unquote(to_basestring(value), encoding=encoding)
  132. def parse_qs_bytes(qs, keep_blank_values=False, strict_parsing=False):
  133. """Parses a query string like urlparse.parse_qs, but returns the
  134. values as byte strings.
  135. Keys still become type str (interpreted as latin1 in python3!)
  136. because it's too painful to keep them as byte strings in
  137. python3 and in practice they're nearly always ascii anyway.
  138. """
  139. # This is gross, but python3 doesn't give us another way.
  140. # Latin1 is the universal donor of character encodings.
  141. result = _parse_qs(qs, keep_blank_values, strict_parsing,
  142. encoding='latin1', errors='strict')
  143. encoded = {}
  144. for k, v in result.items():
  145. encoded[k] = [i.encode('latin1') for i in v]
  146. return encoded
  147. _UTF8_TYPES = (bytes, type(None))
  148. def utf8(value):
  149. """Converts a string argument to a byte string.
  150. If the argument is already a byte string or None, it is returned unchanged.
  151. Otherwise it must be a unicode string and is encoded as utf8.
  152. """
  153. if isinstance(value, _UTF8_TYPES):
  154. return value
  155. if not isinstance(value, unicode_type):
  156. raise TypeError(
  157. "Expected bytes, unicode, or None; got %r" % type(value)
  158. )
  159. return value.encode("utf-8")
  160. _TO_UNICODE_TYPES = (unicode_type, type(None))
  161. def to_unicode(value):
  162. """Converts a string argument to a unicode string.
  163. If the argument is already a unicode string or None, it is returned
  164. unchanged. Otherwise it must be a byte string and is decoded as utf8.
  165. """
  166. if isinstance(value, _TO_UNICODE_TYPES):
  167. return value
  168. if not isinstance(value, bytes):
  169. raise TypeError(
  170. "Expected bytes, unicode, or None; got %r" % type(value)
  171. )
  172. return value.decode("utf-8")
  173. # to_unicode was previously named _unicode not because it was private,
  174. # but to avoid conflicts with the built-in unicode() function/type
  175. _unicode = to_unicode
  176. # When dealing with the standard library across python 2 and 3 it is
  177. # sometimes useful to have a direct conversion to the native string type
  178. if str is unicode_type:
  179. native_str = to_unicode
  180. else:
  181. native_str = utf8
  182. _BASESTRING_TYPES = (basestring_type, type(None))
  183. def to_basestring(value):
  184. """Converts a string argument to a subclass of basestring.
  185. In python2, byte and unicode strings are mostly interchangeable,
  186. so functions that deal with a user-supplied argument in combination
  187. with ascii string constants can use either and should return the type
  188. the user supplied. In python3, the two types are not interchangeable,
  189. so this method is needed to convert byte strings to unicode.
  190. """
  191. if isinstance(value, _BASESTRING_TYPES):
  192. return value
  193. if not isinstance(value, bytes):
  194. raise TypeError(
  195. "Expected bytes, unicode, or None; got %r" % type(value)
  196. )
  197. return value.decode("utf-8")
  198. def recursive_unicode(obj):
  199. """Walks a simple data structure, converting byte strings to unicode.
  200. Supports lists, tuples, and dictionaries.
  201. """
  202. if isinstance(obj, dict):
  203. return dict((recursive_unicode(k), recursive_unicode(v)) for (k, v) in obj.items())
  204. elif isinstance(obj, list):
  205. return list(recursive_unicode(i) for i in obj)
  206. elif isinstance(obj, tuple):
  207. return tuple(recursive_unicode(i) for i in obj)
  208. elif isinstance(obj, bytes):
  209. return to_unicode(obj)
  210. else:
  211. return obj
  212. # I originally used the regex from
  213. # http://daringfireball.net/2010/07/improved_regex_for_matching_urls
  214. # but it gets all exponential on certain patterns (such as too many trailing
  215. # dots), causing the regex matcher to never return.
  216. # This regex should avoid those problems.
  217. # Use to_unicode instead of tornado.util.u - we don't want backslashes getting
  218. # processed as escapes.
  219. _URL_RE = re.compile(to_unicode(r"""\b((?:([\w-]+):(/{1,3})|www[.])(?:(?:(?:[^\s&()]|&amp;|&quot;)*(?:[^!"#$%&'()*+,.:;<=>?@\[\]^`{|}~\s]))|(?:\((?:[^\s&()]|&amp;|&quot;)*\)))+)"""))
  220. def linkify(text, shorten=False, extra_params="",
  221. require_protocol=False, permitted_protocols=["http", "https"]):
  222. """Converts plain text into HTML with links.
  223. For example: ``linkify("Hello http://tornadoweb.org!")`` would return
  224. ``Hello <a href="http://tornadoweb.org">http://tornadoweb.org</a>!``
  225. Parameters:
  226. * ``shorten``: Long urls will be shortened for display.
  227. * ``extra_params``: Extra text to include in the link tag, or a callable
  228. taking the link as an argument and returning the extra text
  229. e.g. ``linkify(text, extra_params='rel="nofollow" class="external"')``,
  230. or::
  231. def extra_params_cb(url):
  232. if url.startswith("http://example.com"):
  233. return 'class="internal"'
  234. else:
  235. return 'class="external" rel="nofollow"'
  236. linkify(text, extra_params=extra_params_cb)
  237. * ``require_protocol``: Only linkify urls which include a protocol. If
  238. this is False, urls such as www.facebook.com will also be linkified.
  239. * ``permitted_protocols``: List (or set) of protocols which should be
  240. linkified, e.g. ``linkify(text, permitted_protocols=["http", "ftp",
  241. "mailto"])``. It is very unsafe to include protocols such as
  242. ``javascript``.
  243. """
  244. if extra_params and not callable(extra_params):
  245. extra_params = " " + extra_params.strip()
  246. def make_link(m):
  247. url = m.group(1)
  248. proto = m.group(2)
  249. if require_protocol and not proto:
  250. return url # not protocol, no linkify
  251. if proto and proto not in permitted_protocols:
  252. return url # bad protocol, no linkify
  253. href = m.group(1)
  254. if not proto:
  255. href = "http://" + href # no proto specified, use http
  256. if callable(extra_params):
  257. params = " " + extra_params(href).strip()
  258. else:
  259. params = extra_params
  260. # clip long urls. max_len is just an approximation
  261. max_len = 30
  262. if shorten and len(url) > max_len:
  263. before_clip = url
  264. if proto:
  265. proto_len = len(proto) + 1 + len(m.group(3) or "") # +1 for :
  266. else:
  267. proto_len = 0
  268. parts = url[proto_len:].split("/")
  269. if len(parts) > 1:
  270. # Grab the whole host part plus the first bit of the path
  271. # The path is usually not that interesting once shortened
  272. # (no more slug, etc), so it really just provides a little
  273. # extra indication of shortening.
  274. url = url[:proto_len] + parts[0] + "/" + \
  275. parts[1][:8].split('?')[0].split('.')[0]
  276. if len(url) > max_len * 1.5: # still too long
  277. url = url[:max_len]
  278. if url != before_clip:
  279. amp = url.rfind('&')
  280. # avoid splitting html char entities
  281. if amp > max_len - 5:
  282. url = url[:amp]
  283. url += "..."
  284. if len(url) >= len(before_clip):
  285. url = before_clip
  286. else:
  287. # full url is visible on mouse-over (for those who don't
  288. # have a status bar, such as Safari by default)
  289. params += ' title="%s"' % href
  290. return u('<a href="%s"%s>%s</a>') % (href, params, url)
  291. # First HTML-escape so that our strings are all safe.
  292. # The regex is modified to avoid character entites other than &amp; so
  293. # that we won't pick up &quot;, etc.
  294. text = _unicode(xhtml_escape(text))
  295. return _URL_RE.sub(make_link, text)
  296. def _convert_entity(m):
  297. if m.group(1) == "#":
  298. try:
  299. if m.group(2)[:1].lower() == 'x':
  300. return unichr(int(m.group(2)[1:], 16))
  301. else:
  302. return unichr(int(m.group(2)))
  303. except ValueError:
  304. return "&#%s;" % m.group(2)
  305. try:
  306. return _HTML_UNICODE_MAP[m.group(2)]
  307. except KeyError:
  308. return "&%s;" % m.group(2)
  309. def _build_unicode_map():
  310. unicode_map = {}
  311. for name, value in htmlentitydefs.name2codepoint.items():
  312. unicode_map[name] = unichr(value)
  313. return unicode_map
  314. _HTML_UNICODE_MAP = _build_unicode_map()