encoding.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import codecs
  2. import datetime
  3. import locale
  4. import warnings
  5. from decimal import Decimal
  6. from urllib.parse import quote
  7. from django.utils.deprecation import RemovedInDjango40Warning
  8. from django.utils.functional import Promise
  9. class DjangoUnicodeDecodeError(UnicodeDecodeError):
  10. def __init__(self, obj, *args):
  11. self.obj = obj
  12. super().__init__(*args)
  13. def __str__(self):
  14. return '%s. You passed in %r (%s)' % (super().__str__(), self.obj, type(self.obj))
  15. def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
  16. """
  17. Return a string representing 's'. Treat bytestrings using the 'encoding'
  18. codec.
  19. If strings_only is True, don't convert (some) non-string-like objects.
  20. """
  21. if isinstance(s, Promise):
  22. # The input is the result of a gettext_lazy() call.
  23. return s
  24. return force_str(s, encoding, strings_only, errors)
  25. _PROTECTED_TYPES = (
  26. type(None), int, float, Decimal, datetime.datetime, datetime.date, datetime.time,
  27. )
  28. def is_protected_type(obj):
  29. """Determine if the object instance is of a protected type.
  30. Objects of protected types are preserved as-is when passed to
  31. force_str(strings_only=True).
  32. """
  33. return isinstance(obj, _PROTECTED_TYPES)
  34. def force_str(s, encoding='utf-8', strings_only=False, errors='strict'):
  35. """
  36. Similar to smart_str(), except that lazy instances are resolved to
  37. strings, rather than kept as lazy objects.
  38. If strings_only is True, don't convert (some) non-string-like objects.
  39. """
  40. # Handle the common case first for performance reasons.
  41. if issubclass(type(s), str):
  42. return s
  43. if strings_only and is_protected_type(s):
  44. return s
  45. try:
  46. if isinstance(s, bytes):
  47. s = str(s, encoding, errors)
  48. else:
  49. s = str(s)
  50. except UnicodeDecodeError as e:
  51. raise DjangoUnicodeDecodeError(s, *e.args)
  52. return s
  53. def smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
  54. """
  55. Return a bytestring version of 's', encoded as specified in 'encoding'.
  56. If strings_only is True, don't convert (some) non-string-like objects.
  57. """
  58. if isinstance(s, Promise):
  59. # The input is the result of a gettext_lazy() call.
  60. return s
  61. return force_bytes(s, encoding, strings_only, errors)
  62. def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
  63. """
  64. Similar to smart_bytes, except that lazy instances are resolved to
  65. strings, rather than kept as lazy objects.
  66. If strings_only is True, don't convert (some) non-string-like objects.
  67. """
  68. # Handle the common case first for performance reasons.
  69. if isinstance(s, bytes):
  70. if encoding == 'utf-8':
  71. return s
  72. else:
  73. return s.decode('utf-8', errors).encode(encoding, errors)
  74. if strings_only and is_protected_type(s):
  75. return s
  76. if isinstance(s, memoryview):
  77. return bytes(s)
  78. return str(s).encode(encoding, errors)
  79. def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'):
  80. warnings.warn(
  81. 'smart_text() is deprecated in favor of smart_str().',
  82. RemovedInDjango40Warning, stacklevel=2,
  83. )
  84. return smart_str(s, encoding, strings_only, errors)
  85. def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
  86. warnings.warn(
  87. 'force_text() is deprecated in favor of force_str().',
  88. RemovedInDjango40Warning, stacklevel=2,
  89. )
  90. return force_str(s, encoding, strings_only, errors)
  91. def iri_to_uri(iri):
  92. """
  93. Convert an Internationalized Resource Identifier (IRI) portion to a URI
  94. portion that is suitable for inclusion in a URL.
  95. This is the algorithm from section 3.1 of RFC 3987, slightly simplified
  96. since the input is assumed to be a string rather than an arbitrary byte
  97. stream.
  98. Take an IRI (string or UTF-8 bytes, e.g. '/I ♥ Django/' or
  99. b'/I \xe2\x99\xa5 Django/') and return a string containing the encoded
  100. result with ASCII chars only (e.g. '/I%20%E2%99%A5%20Django/').
  101. """
  102. # The list of safe characters here is constructed from the "reserved" and
  103. # "unreserved" characters specified in sections 2.2 and 2.3 of RFC 3986:
  104. # reserved = gen-delims / sub-delims
  105. # gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
  106. # sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  107. # / "*" / "+" / "," / ";" / "="
  108. # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  109. # Of the unreserved characters, urllib.parse.quote() already considers all
  110. # but the ~ safe.
  111. # The % character is also added to the list of safe characters here, as the
  112. # end of section 3.1 of RFC 3987 specifically mentions that % must not be
  113. # converted.
  114. if iri is None:
  115. return iri
  116. elif isinstance(iri, Promise):
  117. iri = str(iri)
  118. return quote(iri, safe="/#%[]=:;$&()+,!?*@'~")
  119. # List of byte values that uri_to_iri() decodes from percent encoding.
  120. # First, the unreserved characters from RFC 3986:
  121. _ascii_ranges = [[45, 46, 95, 126], range(65, 91), range(97, 123)]
  122. _hextobyte = {
  123. (fmt % char).encode(): bytes((char,))
  124. for ascii_range in _ascii_ranges
  125. for char in ascii_range
  126. for fmt in ['%02x', '%02X']
  127. }
  128. # And then everything above 128, because bytes ≥ 128 are part of multibyte
  129. # unicode characters.
  130. _hexdig = '0123456789ABCDEFabcdef'
  131. _hextobyte.update({
  132. (a + b).encode(): bytes.fromhex(a + b)
  133. for a in _hexdig[8:] for b in _hexdig
  134. })
  135. def uri_to_iri(uri):
  136. """
  137. Convert a Uniform Resource Identifier(URI) into an Internationalized
  138. Resource Identifier(IRI).
  139. This is the algorithm from section 3.2 of RFC 3987, excluding step 4.
  140. Take an URI in ASCII bytes (e.g. '/I%20%E2%99%A5%20Django/') and return
  141. a string containing the encoded result (e.g. '/I%20♥%20Django/').
  142. """
  143. if uri is None:
  144. return uri
  145. uri = force_bytes(uri)
  146. # Fast selective unqote: First, split on '%' and then starting with the
  147. # second block, decode the first 2 bytes if they represent a hex code to
  148. # decode. The rest of the block is the part after '%AB', not containing
  149. # any '%'. Add that to the output without further processing.
  150. bits = uri.split(b'%')
  151. if len(bits) == 1:
  152. iri = uri
  153. else:
  154. parts = [bits[0]]
  155. append = parts.append
  156. hextobyte = _hextobyte
  157. for item in bits[1:]:
  158. hex = item[:2]
  159. if hex in hextobyte:
  160. append(hextobyte[item[:2]])
  161. append(item[2:])
  162. else:
  163. append(b'%')
  164. append(item)
  165. iri = b''.join(parts)
  166. return repercent_broken_unicode(iri).decode()
  167. def escape_uri_path(path):
  168. """
  169. Escape the unsafe characters from the path portion of a Uniform Resource
  170. Identifier (URI).
  171. """
  172. # These are the "reserved" and "unreserved" characters specified in
  173. # sections 2.2 and 2.3 of RFC 2396:
  174. # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
  175. # unreserved = alphanum | mark
  176. # mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
  177. # The list of safe characters here is constructed subtracting ";", "=",
  178. # and "?" according to section 3.3 of RFC 2396.
  179. # The reason for not subtracting and escaping "/" is that we are escaping
  180. # the entire path, not a path segment.
  181. return quote(path, safe="/:@&+$,-_.!~*'()")
  182. def punycode(domain):
  183. """Return the Punycode of the given domain if it's non-ASCII."""
  184. return domain.encode('idna').decode('ascii')
  185. def repercent_broken_unicode(path):
  186. """
  187. As per section 3.2 of RFC 3987, step three of converting a URI into an IRI,
  188. repercent-encode any octet produced that is not part of a strictly legal
  189. UTF-8 octet sequence.
  190. """
  191. while True:
  192. try:
  193. path.decode()
  194. except UnicodeDecodeError as e:
  195. # CVE-2019-14235: A recursion shouldn't be used since the exception
  196. # handling uses massive amounts of memory
  197. repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~")
  198. path = path[:e.start] + repercent.encode() + path[e.end:]
  199. else:
  200. return path
  201. def filepath_to_uri(path):
  202. """Convert a file system path to a URI portion that is suitable for
  203. inclusion in a URL.
  204. Encode certain chars that would normally be recognized as special chars
  205. for URIs. Do not encode the ' character, as it is a valid character
  206. within URIs. See the encodeURIComponent() JavaScript function for details.
  207. """
  208. if path is None:
  209. return path
  210. # I know about `os.sep` and `os.altsep` but I want to leave
  211. # some flexibility for hardcoding separators.
  212. return quote(path.replace("\\", "/"), safe="/~!*()'")
  213. def get_system_encoding():
  214. """
  215. The encoding of the default system locale. Fallback to 'ascii' if the
  216. #encoding is unsupported by Python or could not be determined. See tickets
  217. #10335 and #5846.
  218. """
  219. try:
  220. encoding = locale.getdefaultlocale()[1] or 'ascii'
  221. codecs.lookup(encoding)
  222. except Exception:
  223. encoding = 'ascii'
  224. return encoding
  225. DEFAULT_LOCALE_ENCODING = get_system_encoding()