utf1632prober.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. ######################## BEGIN LICENSE BLOCK ########################
  2. #
  3. # Contributor(s):
  4. # Jason Zavaglia
  5. #
  6. # This library is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public
  8. # License as published by the Free Software Foundation; either
  9. # version 2.1 of the License, or (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public
  17. # License along with this library; if not, write to the Free Software
  18. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  19. # 02110-1301 USA
  20. ######################### END LICENSE BLOCK #########################
  21. from typing import List, Union
  22. from .charsetprober import CharSetProber
  23. from .enums import ProbingState
  24. class UTF1632Prober(CharSetProber):
  25. """
  26. This class simply looks for occurrences of zero bytes, and infers
  27. whether the file is UTF16 or UTF32 (low-endian or big-endian)
  28. For instance, files looking like ( \0 \0 \0 [nonzero] )+
  29. have a good probability to be UTF32BE. Files looking like ( \0 [nonzero] )+
  30. may be guessed to be UTF16BE, and inversely for little-endian varieties.
  31. """
  32. # how many logical characters to scan before feeling confident of prediction
  33. MIN_CHARS_FOR_DETECTION = 20
  34. # a fixed constant ratio of expected zeros or non-zeros in modulo-position.
  35. EXPECTED_RATIO = 0.94
  36. def __init__(self) -> None:
  37. super().__init__()
  38. self.position = 0
  39. self.zeros_at_mod = [0] * 4
  40. self.nonzeros_at_mod = [0] * 4
  41. self._state = ProbingState.DETECTING
  42. self.quad = [0, 0, 0, 0]
  43. self.invalid_utf16be = False
  44. self.invalid_utf16le = False
  45. self.invalid_utf32be = False
  46. self.invalid_utf32le = False
  47. self.first_half_surrogate_pair_detected_16be = False
  48. self.first_half_surrogate_pair_detected_16le = False
  49. self.reset()
  50. def reset(self) -> None:
  51. super().reset()
  52. self.position = 0
  53. self.zeros_at_mod = [0] * 4
  54. self.nonzeros_at_mod = [0] * 4
  55. self._state = ProbingState.DETECTING
  56. self.invalid_utf16be = False
  57. self.invalid_utf16le = False
  58. self.invalid_utf32be = False
  59. self.invalid_utf32le = False
  60. self.first_half_surrogate_pair_detected_16be = False
  61. self.first_half_surrogate_pair_detected_16le = False
  62. self.quad = [0, 0, 0, 0]
  63. @property
  64. def charset_name(self) -> str:
  65. if self.is_likely_utf32be():
  66. return "utf-32be"
  67. if self.is_likely_utf32le():
  68. return "utf-32le"
  69. if self.is_likely_utf16be():
  70. return "utf-16be"
  71. if self.is_likely_utf16le():
  72. return "utf-16le"
  73. # default to something valid
  74. return "utf-16"
  75. @property
  76. def language(self) -> str:
  77. return ""
  78. def approx_32bit_chars(self) -> float:
  79. return max(1.0, self.position / 4.0)
  80. def approx_16bit_chars(self) -> float:
  81. return max(1.0, self.position / 2.0)
  82. def is_likely_utf32be(self) -> bool:
  83. approx_chars = self.approx_32bit_chars()
  84. return approx_chars >= self.MIN_CHARS_FOR_DETECTION and (
  85. self.zeros_at_mod[0] / approx_chars > self.EXPECTED_RATIO
  86. and self.zeros_at_mod[1] / approx_chars > self.EXPECTED_RATIO
  87. and self.zeros_at_mod[2] / approx_chars > self.EXPECTED_RATIO
  88. and self.nonzeros_at_mod[3] / approx_chars > self.EXPECTED_RATIO
  89. and not self.invalid_utf32be
  90. )
  91. def is_likely_utf32le(self) -> bool:
  92. approx_chars = self.approx_32bit_chars()
  93. return approx_chars >= self.MIN_CHARS_FOR_DETECTION and (
  94. self.nonzeros_at_mod[0] / approx_chars > self.EXPECTED_RATIO
  95. and self.zeros_at_mod[1] / approx_chars > self.EXPECTED_RATIO
  96. and self.zeros_at_mod[2] / approx_chars > self.EXPECTED_RATIO
  97. and self.zeros_at_mod[3] / approx_chars > self.EXPECTED_RATIO
  98. and not self.invalid_utf32le
  99. )
  100. def is_likely_utf16be(self) -> bool:
  101. approx_chars = self.approx_16bit_chars()
  102. return approx_chars >= self.MIN_CHARS_FOR_DETECTION and (
  103. (self.nonzeros_at_mod[1] + self.nonzeros_at_mod[3]) / approx_chars
  104. > self.EXPECTED_RATIO
  105. and (self.zeros_at_mod[0] + self.zeros_at_mod[2]) / approx_chars
  106. > self.EXPECTED_RATIO
  107. and not self.invalid_utf16be
  108. )
  109. def is_likely_utf16le(self) -> bool:
  110. approx_chars = self.approx_16bit_chars()
  111. return approx_chars >= self.MIN_CHARS_FOR_DETECTION and (
  112. (self.nonzeros_at_mod[0] + self.nonzeros_at_mod[2]) / approx_chars
  113. > self.EXPECTED_RATIO
  114. and (self.zeros_at_mod[1] + self.zeros_at_mod[3]) / approx_chars
  115. > self.EXPECTED_RATIO
  116. and not self.invalid_utf16le
  117. )
  118. def validate_utf32_characters(self, quad: List[int]) -> None:
  119. """
  120. Validate if the quad of bytes is valid UTF-32.
  121. UTF-32 is valid in the range 0x00000000 - 0x0010FFFF
  122. excluding 0x0000D800 - 0x0000DFFF
  123. https://en.wikipedia.org/wiki/UTF-32
  124. """
  125. if (
  126. quad[0] != 0
  127. or quad[1] > 0x10
  128. or (quad[0] == 0 and quad[1] == 0 and 0xD8 <= quad[2] <= 0xDF)
  129. ):
  130. self.invalid_utf32be = True
  131. if (
  132. quad[3] != 0
  133. or quad[2] > 0x10
  134. or (quad[3] == 0 and quad[2] == 0 and 0xD8 <= quad[1] <= 0xDF)
  135. ):
  136. self.invalid_utf32le = True
  137. def validate_utf16_characters(self, pair: List[int]) -> None:
  138. """
  139. Validate if the pair of bytes is valid UTF-16.
  140. UTF-16 is valid in the range 0x0000 - 0xFFFF excluding 0xD800 - 0xFFFF
  141. with an exception for surrogate pairs, which must be in the range
  142. 0xD800-0xDBFF followed by 0xDC00-0xDFFF
  143. https://en.wikipedia.org/wiki/UTF-16
  144. """
  145. if not self.first_half_surrogate_pair_detected_16be:
  146. if 0xD8 <= pair[0] <= 0xDB:
  147. self.first_half_surrogate_pair_detected_16be = True
  148. elif 0xDC <= pair[0] <= 0xDF:
  149. self.invalid_utf16be = True
  150. else:
  151. if 0xDC <= pair[0] <= 0xDF:
  152. self.first_half_surrogate_pair_detected_16be = False
  153. else:
  154. self.invalid_utf16be = True
  155. if not self.first_half_surrogate_pair_detected_16le:
  156. if 0xD8 <= pair[1] <= 0xDB:
  157. self.first_half_surrogate_pair_detected_16le = True
  158. elif 0xDC <= pair[1] <= 0xDF:
  159. self.invalid_utf16le = True
  160. else:
  161. if 0xDC <= pair[1] <= 0xDF:
  162. self.first_half_surrogate_pair_detected_16le = False
  163. else:
  164. self.invalid_utf16le = True
  165. def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
  166. for c in byte_str:
  167. mod4 = self.position % 4
  168. self.quad[mod4] = c
  169. if mod4 == 3:
  170. self.validate_utf32_characters(self.quad)
  171. self.validate_utf16_characters(self.quad[0:2])
  172. self.validate_utf16_characters(self.quad[2:4])
  173. if c == 0:
  174. self.zeros_at_mod[mod4] += 1
  175. else:
  176. self.nonzeros_at_mod[mod4] += 1
  177. self.position += 1
  178. return self.state
  179. @property
  180. def state(self) -> ProbingState:
  181. if self._state in {ProbingState.NOT_ME, ProbingState.FOUND_IT}:
  182. # terminal, decided states
  183. return self._state
  184. if self.get_confidence() > 0.80:
  185. self._state = ProbingState.FOUND_IT
  186. elif self.position > 4 * 1024:
  187. # if we get to 4kb into the file, and we can't conclude it's UTF,
  188. # let's give up
  189. self._state = ProbingState.NOT_ME
  190. return self._state
  191. def get_confidence(self) -> float:
  192. return (
  193. 0.85
  194. if (
  195. self.is_likely_utf16le()
  196. or self.is_likely_utf16be()
  197. or self.is_likely_utf32le()
  198. or self.is_likely_utf32be()
  199. )
  200. else 0.00
  201. )